diff --git a/.github/images/gospa.png b/.github/images/gospa.png new file mode 100644 index 0000000..5d1ec28 Binary files /dev/null and b/.github/images/gospa.png differ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c579fbc..6f8cd69 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,7 @@ jobs: strategy: fail-fast: false matrix: - module: ["dbkit", "dbkit/sqlite", "mailkit", "goncierge", "gonsole", "gonsole/auth", "gonsole/auth/sqlite", "pluginkit", "pluginkit/features", "pluginkit/graphwire"] + module: ["dbkit", "dbkit/sqlite", "mailkit", "goncierge", "gonsole", "gonsole/auth", "gonsole/auth/sqlite", "gospa", "gospa/features", "pluginkit", "pluginkit/features", "pluginkit/graphwire"] defaults: run: working-directory: ${{ matrix.module }} @@ -101,7 +101,7 @@ jobs: strategy: fail-fast: false matrix: - module: ["dbkit", "dbkit/postgres", "dbkit/sqlite", "mailkit", "goncierge", "gonsole", "gonsole/auth", "gonsole/auth/postgres", "gonsole/auth/sqlite", "pluginkit", "pluginkit/features", "pluginkit/graphwire", "postgresblob"] + module: ["dbkit", "dbkit/postgres", "dbkit/sqlite", "mailkit", "goncierge", "gonsole", "gonsole/auth", "gonsole/auth/postgres", "gonsole/auth/sqlite", "gospa", "gospa/features", "pluginkit", "pluginkit/features", "pluginkit/graphwire", "postgresblob"] steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: @@ -123,7 +123,7 @@ jobs: strategy: fail-fast: false matrix: - module: ["dbkit", "dbkit/postgres", "dbkit/sqlite", "mailkit", "goncierge", "gonsole", "gonsole/auth", "gonsole/auth/postgres", "gonsole/auth/sqlite", "pluginkit", "pluginkit/features", "pluginkit/graphwire", "postgresblob"] + module: ["dbkit", "dbkit/postgres", "dbkit/sqlite", "mailkit", "goncierge", "gonsole", "gonsole/auth", "gonsole/auth/postgres", "gonsole/auth/sqlite", "gospa", "gospa/features", "pluginkit", "pluginkit/features", "pluginkit/graphwire", "postgresblob"] defaults: run: working-directory: ${{ matrix.module }} diff --git a/README.md b/README.md index 31a1f2a..7553987 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,8 @@ need and ignore the rest. commands and their records on a program's PostgreSQL database. - [`gonsole/auth/sqlite`](gonsole/auth/sqlite/) runs those account commands and their records on a program's one SQLite handle. +- [GoSPA](gospa/) serves a built single-page app and the files of a + public folder. - [`gottext`](gottext/) reads, writes and syncs gettext catalogs for TypeScript applications, published to npm as `@gopherium/gottext`. - [`mailkit`](mailkit/) renders mail from template files and sends it diff --git a/gospa/.golangci.yml b/gospa/.golangci.yml new file mode 100644 index 0000000..6ec9459 --- /dev/null +++ b/gospa/.golangci.yml @@ -0,0 +1,48 @@ +version: "2" + +linters: + default: standard + enable: + - cyclop + - depguard + - gocognit + - lll + - misspell + - revive + - unconvert + - unparam + settings: + cyclop: + max-complexity: 10 + gocognit: + min-complexity: 15 + lll: + line-length: 120 + revive: + rules: + - name: blank-imports + disabled: true + - name: exported + depguard: + rules: + dependency-purity: + list-mode: strict + allow: + - $gostd + - github.com/gopherium/framework/gospa + - golang.org/x/net/html + exclusions: + rules: + - path: _test\.go + linters: + - cyclop + - gocognit + +formatters: + enable: + - gofmt + - goimports + settings: + goimports: + local-prefixes: + - github.com/gopherium/framework diff --git a/gospa/CHANGELOG.md b/gospa/CHANGELOG.md new file mode 100644 index 0000000..4aab016 --- /dev/null +++ b/gospa/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog + +All notable changes to GoSPA, the `gospa` module, are documented in +this file. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the +module follows [Semantic Versioning](https://semver.org/). While at +v0.x, minor releases may contain breaking changes. + +Releases of this module are tagged `gospa/vX.Y.Z`. + +## [Unreleased] + +### Added + +- `App`, a handler that serves a built single-page app from an `fs.FS`, sending `index.html` for every path that names no file outside `assets/`. +- A path under `assets/` that names no file answers not found. +- A hashed file under `assets/` is kept for `HashedMaxAge`, one year by default, and every other file and the page get `no-cache`. +- `App` fails when the build holds no `index.html`, when `HashedMaxAge` is below one second, and on a value with no name or a name given twice. +- `Meta`, server values the page carries as meta elements where its head opens. +- The page is read again each time it is sent and checked by a tag of the bytes sent. +- `Files`, a handler that sends the regular files of an `fs.FS` and nothing else. +- Both answer only GET and HEAD, never list a folder and never send a name starting with a dot, `.well-known` excepted. +- A path with an empty segment, or a segment that holds a tilde or ends in a dot or a space, answers not found. +- A file with no date, or dated at the Unix epoch, that can seek is checked by a tag of the bytes sent, worked out on every request. +- A file that cannot seek is read only as far as the answer needs, and gets the whole file when asked for several ranges. +- Types come from GoSPA's own table, `application/octet-stream` for an extension it does not know, and every file and page carries `X-Content-Type-Options: nosniff`. +- `AppOptions.NotFound` and `FilesOptions.NotFound` replace the plain not found answer. +- Requires `golang.org/x/net` v0.63.0. diff --git a/gospa/README.md b/gospa/README.md new file mode 100644 index 0000000..836928c --- /dev/null +++ b/gospa/README.md @@ -0,0 +1,138 @@ +# GoSPA + +![A gopher in a hot spring, saying AAAHH](../.github/images/gospa.png) + +Serve a built single-page app, and the files of a public folder, from a +Go program. + +A build tool such as Vite turns a single-page app into one page, +`index.html`, and a folder of scripts, styles and fonts. The browser +loads the page once, and the app's own router shows a screen for each +address. Go's `http.FileServer` can send these files, but it lists +folders, sends hidden files such as `.env`, sets no cache rules and +cannot send the page for an address the app routes. GoSPA adds those +rules. + +If you know Laravel, GoSPA does the job Nginx does in front of a +Laravel app: it sends the app for every address that names no file, +and serves the `public` folder file by file. + +The guide is at . + +## Serving a built app + +```go +//go:embed all:dist +var dist embed.FS + +build, err := fs.Sub(dist, "dist") +if err != nil { + return err +} +admin, err := gospa.App(build, gospa.AppOptions{ + Meta: []gospa.Meta{{Name: "api-root", Content: "/api/"}}, +}) +if err != nil { + return err +} +mux.Handle("/admin/", http.StripPrefix("/admin", admin)) +``` + +`App` fails when the build holds no `index.html`. Then it answers: + +| The path | The answer | +| --- | --- | +| a file of the build | the file | +| `index.html` | the page | +| under `assets/`, no file | not found | +| anywhere else, no file | the page | + +The page is read again each time it is sent, so a new build shows +without a restart. + +### How long a browser keeps a file + +A hashed file is kept for `HashedMaxAge` without asking, one year when +it is zero, and `App` fails when it is below one second. A hashed file +is a file under `assets/` whose name ends in a dash, 8 +letters, digits, dashes or underscores, and an extension, as Vite names +`assets/index-DWLUpakq.js`. Its name changes whenever its content does. + +The page and every other file get `no-cache`. The browser keeps them +but checks each one on every load, which costs a 304 with no body while +nothing changed. A file with a date is checked by its date. A file with +no date, as every embedded file is, is checked by a tag of the bytes +sent, worked out on every request. A file with no date that cannot seek +has nothing to be checked by, so the browser gets it again on every +load. The page is checked by a tag of the bytes sent, values included. + +A name such as `assets/my-settings.js` looks hashed too. Vite writes no +such name under `assets/` unless your project has `public/assets/`. + +### Server values in the page + +Each `Meta` becomes a meta element right where the head opens: + +```html + +``` + +The app reads it with +`document.querySelector('meta[name="api-root"]').content`. Names and +values are escaped. `App` fails on a value with no name or a name given +twice. + +## Serving a public folder + +```go +root, err := os.OpenRoot("uploads") +if err != nil { + return err +} +mux.Handle("/media/", http.StripPrefix("/media", gospa.Files(root.FS(), gospa.FilesOptions{}))) +``` + +`Files` sends each file by its path with `no-cache`. A missing file and +a folder answer not found, and a folder's `index.html` is sent only +when asked for by name. Use `os.OpenRoot` for a folder on disk, since +unlike `os.DirFS` it never follows a link out of the folder. + +An uploaded HTML or SVG file can run scripts on your site. Serve +uploads from another domain, or check what people upload. + +## Rules both share + +- Only GET and HEAD are answered. Any other method gets 405. +- A path segment that starts with a dot, such as `.env` or `.git`, + answers not found. `.well-known` is the one exception. +- A segment that holds a tilde or ends in a dot or a space answers not + found, since Windows reads `GIT~1` as `.git`. +- A path with an empty segment, such as `//app.js`, answers not found. +- Ranges and checks work as `http.ServeContent` answers them. A file + that cannot seek, such as one inside a zip, gets the whole file when + asked for several ranges. +- The type comes from the extension, by GoSPA's own table, the same on + every system. An extension it does not know gets + `application/octet-stream`, so the browser downloads the file. Every + file, page and plain not found answer carries + `X-Content-Type-Options: nosniff`, so the browser never guesses a type + from the bytes. +- `NotFound` replaces the plain 404 answer. + +GoSPA serves the path it receives, so strip a prefix with +`http.StripPrefix`, as above. + +The table knows `html`, `htm`, `css`, `js`, `mjs`, `json`, `map`, +`webmanifest`, `txt`, `xml`, `svg`, `png`, `jpg`, `jpeg`, `gif`, +`webp`, `avif`, `ico`, `woff`, `woff2`, `ttf`, `otf`, `wasm`, `pdf`, +`zip`, `mp3`, `m4a`, `wav`, `ogg`, `flac`, `mp4` and `webm`. + +## Testing + +`go test ./...` runs the unit tests and the fuzz seeds. The scenarios +sit in `features/`, a module of their own, run with +`cd features && go test ./...`. + +## License + +Apache-2.0. diff --git a/gospa/app.go b/gospa/app.go new file mode 100644 index 0000000..a43f3da --- /dev/null +++ b/gospa/app.go @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "bytes" + "crypto/sha256" + "fmt" + "io/fs" + "net/http" + "regexp" + "strings" + "time" +) + +// DefaultHashedMaxAge is how long a browser keeps a hashed file when AppOptions sets no window. +const DefaultHashedMaxAge = 365 * 24 * time.Hour + +// pageName is the file that holds the page of a built app. +const pageName = "index.html" + +// assetsDir is the folder a build writes its hashed files to. +const assetsDir = "assets" + +// hashedName matches a name under assets ending in a dash, 8 letters, digits, dashes or underscores and an extension. +var hashedName = regexp.MustCompile(`^assets/(?:[^/]+/)*[^/]*-[A-Za-z0-9_-]{8}(?:\.[A-Za-z0-9]+)+$`) + +// AppOptions says how long App lets a browser keep hashed files, what its page carries and how it answers not found. +type AppOptions struct { + // HashedMaxAge is how long a browser keeps a hashed file, DefaultHashedMaxAge when zero, else one second or more. + HashedMaxAge time.Duration + // Meta holds the values the page carries in its head, in order. + Meta []Meta + // NotFound answers a path that names no file and may not get the page, http.NotFound when nil. + NotFound http.Handler +} + +// app is the handler App returns. +type app struct { + folder folder + head []byte + hashed string + notFound http.Handler +} + +// App returns a handler serving the built single-page app in fsys, its page for a path outside assets naming no file. +func App(fsys fs.FS, opts AppOptions) (http.Handler, error) { + if _, err := fs.ReadFile(fsys, pageName); err != nil { + return nil, fmt.Errorf("gospa: read the app page: %w", err) + } + head, err := metaElements(opts.Meta) + if err != nil { + return nil, err + } + hashed, err := hashedControl(opts.HashedMaxAge) + if err != nil { + return nil, err + } + return &app{folder: folder{fsys: fsys}, head: head, hashed: hashed, notFound: orNotFound(opts.NotFound)}, nil +} + +// hashedControl returns the Cache-Control of a hashed file kept for maxAge, DefaultHashedMaxAge when zero. +func hashedControl(maxAge time.Duration) (string, error) { + if maxAge == 0 { + maxAge = DefaultHashedMaxAge + } + if maxAge < time.Second { + return "", fmt.Errorf("gospa: HashedMaxAge %v is below one second", maxAge) + } + return fmt.Sprintf("public, max-age=%d, immutable", int64(maxAge/time.Second)), nil +} + +// ServeHTTP sends the file r names, the page when it names no file outside assets, or the not found answer. +func (a *app) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if !readable(w, r) { + return + } + name, ok := fileName(r.URL.Path) + switch { + case !ok: + a.notFound.ServeHTTP(w, r) + case strings.EqualFold(name, pageName): + a.sendPage(w, r) + default: + a.sendFile(w, r, name) + } +} + +// sendFile sends the file at name, or else the not found answer under assets and the page elsewhere. +func (a *app) sendFile(w http.ResponseWriter, r *http.Request, name string) { + open, ok := a.folder.open(name) + switch { + case ok: + a.folder.send(w, r, open, a.controlOf(name)) + case name == assetsDir || strings.HasPrefix(name, assetsDir+"/"): + a.notFound.ServeHTTP(w, r) + default: + a.sendPage(w, r) + } +} + +// controlOf returns the Cache-Control of the file at name. +func (a *app) controlOf(name string) string { + if hashedName.MatchString(name) { + return a.hashed + } + return noCache +} + +// sendPage sends the page with its values, tagged by the bytes sent and dated by nothing. +func (a *app) sendPage(w http.ResponseWriter, r *http.Request) { + page, err := fs.ReadFile(a.folder.fsys, pageName) + if err != nil { + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + if a.head != nil { + page = withHead(page, a.head) + } + header := w.Header() + header.Set("ETag", tagOf(page)) + describe(header, pageName, noCache) + http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(page)) +} + +// tagOf returns the strong entity tag of data. +func tagOf(data []byte) string { + sum := sha256.Sum256(data) + return tagFrom(sum[:]) +} diff --git a/gospa/app_test.go b/gospa/app_test.go new file mode 100644 index 0000000..412123a --- /dev/null +++ b/gospa/app_test.go @@ -0,0 +1,356 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa_test + +import ( + "io/fs" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "testing/fstest" + "time" + + "github.com/gopherium/framework/gospa" +) + +// page is the page of the test apps. +const page = `App
` + +// builtApp returns a dated build holding the page and each name with its own name as content. +func builtApp(names ...string) fstest.MapFS { + build := dated(names...) + build["index.html"] = &fstest.MapFile{Data: []byte(page), ModTime: built} + return build +} + +// caselessFS wraps a folder that opens a name in any case, as on macOS and Windows. +type caselessFS struct { + fstest.MapFS +} + +// Open opens name in lower case. +func (c caselessFS) Open(name string) (fs.File, error) { + return c.MapFS.Open(strings.ToLower(name)) +} + +// newApp returns the handler App gives for build and opts, failing the test when App fails. +func newApp(t *testing.T, build fstest.MapFS, opts gospa.AppOptions) http.Handler { + t.Helper() + handler, err := gospa.App(build, opts) + if err != nil { + t.Fatalf("App() = %v", err) + } + return handler +} + +// isPage checks that answer sends want as the page, checked on every load and dated by nothing. +func isPage(t *testing.T, target string, answer *httptest.ResponseRecorder, want string) { + t.Helper() + header := answer.Header() + if answer.Code != http.StatusOK || answer.Body.String() != want { + t.Errorf("GET %s = %d %q, want 200 with the page %q", target, answer.Code, answer.Body, want) + } + for key, value := range map[string]string{ + "Content-Type": "text/html; charset=utf-8", + "Cache-Control": "no-cache", + "X-Content-Type-Options": "nosniff", + } { + if got := header.Get(key); got != value { + t.Errorf("GET %s %s = %q, want %q", target, key, got, value) + } + } + if !absent(header, "Last-Modified") { + t.Errorf("GET %s Last-Modified = %q, want none", target, header.Values("Last-Modified")) + } + if tag := header.Get("Etag"); !strongTag.MatchString(tag) { + t.Errorf("GET %s Etag = %q, want a tag of 32 hex digits in quotes", target, tag) + } +} + +func TestAppSendsThePageForEveryPathThatNamesNoFile(t *testing.T) { + t.Parallel() + + handler := newApp(t, builtApp("favicon.svg", "images/logo.png"), gospa.AppOptions{}) + for _, target := range []string{ + "/", "/posts/42", "/settings/", "/images", "/images/", "/images/missing.png", "/favicon.svg/", + "/index.html", "/.well-known/missing", "/assets-old/app.js", "/assetsfoo", "/docs/assets/missing.js", + } { + answer := ask(handler, http.MethodGet, target) + isPage(t, target, answer, page) + } +} + +func TestAppSendsThePageWithItsValuesForIndexHTMLInAnyCase(t *testing.T) { + t.Parallel() + + build := caselessFS{MapFS: builtApp()} + handler, err := gospa.App(build, gospa.AppOptions{Meta: []gospa.Meta{{Name: "api-root", Content: "/api/"}}}) + if err != nil { + t.Fatalf("App() = %v", err) + } + want := strings.Replace(page, "", ``, 1) + for _, target := range []string{"/index.html", "/INDEX.HTML", "/Index.html"} { + isPage(t, target, ask(handler, http.MethodGet, target), want) + } +} + +func TestAppSendsThePageForAnEmptyPath(t *testing.T) { + t.Parallel() + + handler := newApp(t, builtApp(), gospa.AppOptions{}) + answer := ask(http.StripPrefix("/admin", handler), http.MethodGet, "/admin") + isPage(t, "/admin", answer, page) +} + +func TestAppSendsAFileTheBuildWrote(t *testing.T) { + t.Parallel() + + handler := newApp(t, builtApp("images/logo.png", "docs/index.html", ".well-known/security.txt"), gospa.AppOptions{}) + for target, kind := range map[string]string{ + "/images/logo.png": "image/png", + "/docs/index.html": "text/html; charset=utf-8", + "/.well-known/security.txt": "text/plain; charset=utf-8", + } { + answer := ask(handler, http.MethodGet, target) + if answer.Code != http.StatusOK || answer.Body.String() != "content of "+target[1:] { + t.Errorf("GET %s = %d %q, want 200 with the file", target, answer.Code, answer.Body) + } + if got := answer.Header().Get("Content-Type"); got != kind { + t.Errorf("GET %s Content-Type = %q, want %q", target, got, kind) + } + if got := answer.Header().Get("Last-Modified"); got != "Sun, 01 Nov 2026 10:00:00 GMT" { + t.Errorf("GET %s Last-Modified = %q, want the date of the file", target, got) + } + } +} + +func TestAppAnswersNotFoundUnderAssetsForAPathThatNamesNoFile(t *testing.T) { + t.Parallel() + + handler := newApp(t, builtApp("assets/index-DWLUpakq.js", "assets/fonts/inter-Bx3kP9qa.woff2"), gospa.AppOptions{}) + for _, target := range []string{ + "/assets/index-0ldHa5h1.js", "/assets/", "/assets", "/assets/fonts", "/assets/fonts/", "/assets/index-DWLUpakq.js/", + } { + answer := ask(handler, http.MethodGet, target) + if answer.Code != http.StatusNotFound || strings.Contains(answer.Body.String(), "") { + t.Errorf("GET %s = %d %q, want 404", target, answer.Code, answer.Body) + } + } +} + +func TestAppLetsABrowserKeepAHashedFileForTheWindow(t *testing.T) { + t.Parallel() + + build := builtApp( + "assets/index-DWLUpakq.js", "assets/vendor-a_B-9xYz.js", "assets/chunks/posts-0ldHa5h1.js", + "assets/index-DWLUpakq.js.map", "assets/index-DWLUpak.js", "assets/logo.svg", "assets/index-DWLUpakq", + "assets/index-DWLUpakqX.js", "docs/assets/index-DWLUpakq.js", "favicon-DWLUpakq.svg", "favicon.svg", + ) + cases := map[time.Duration]string{ + 0: "public, max-age=31536000, immutable", + time.Hour: "public, max-age=3600, immutable", + 90*time.Minute + time.Second: "public, max-age=5401, immutable", + 1500 * time.Millisecond: "public, max-age=1, immutable", + } + for window, hashed := range cases { + handler := newApp(t, build, gospa.AppOptions{HashedMaxAge: window}) + for target, want := range map[string]string{ + "/assets/index-DWLUpakq.js": hashed, + "/assets/vendor-a_B-9xYz.js": hashed, + "/assets/chunks/posts-0ldHa5h1.js": hashed, + "/assets/index-DWLUpakq.js.map": hashed, + "/assets/index-DWLUpak.js": "no-cache", + "/assets/logo.svg": "no-cache", + "/assets/index-DWLUpakq": "no-cache", + "/assets/index-DWLUpakqX.js": "no-cache", + "/docs/assets/index-DWLUpakq.js": "no-cache", + "/favicon-DWLUpakq.svg": "no-cache", + "/favicon.svg": "no-cache", + "/": "no-cache", + "/posts/42": "no-cache", + } { + if got := ask(handler, http.MethodGet, target).Header().Get("Cache-Control"); got != want { + t.Errorf("GET %s with the window %v Cache-Control = %q, want %q", target, window, got, want) + } + } + } + if gospa.DefaultHashedMaxAge != 365*24*time.Hour { + t.Errorf("DefaultHashedMaxAge = %v, want one year", gospa.DefaultHashedMaxAge) + } +} + +func TestAppReadsThePageAgainEachTimeItIsSent(t *testing.T) { + t.Parallel() + + build := builtApp() + handler := newApp(t, build, gospa.AppOptions{}) + first := ask(handler, http.MethodGet, "/posts/42") + build["index.html"] = &fstest.MapFile{Data: []byte(`Rebuilt`), ModTime: built} + again := ask(handler, http.MethodGet, "/posts/42", "If-None-Match", first.Header().Get("Etag")) + isPage(t, "/posts/42", again, `Rebuilt`) +} + +func TestAppAnswersAServerErrorWhenThePageIsGone(t *testing.T) { + t.Parallel() + + build := builtApp() + handler := newApp(t, build, gospa.AppOptions{}) + delete(build, "index.html") + answer := ask(handler, http.MethodGet, "/posts/42") + if answer.Code != http.StatusInternalServerError || strings.Contains(answer.Body.String(), "index.html") { + t.Errorf("GET /posts/42 with no page = %d %q, want 500 naming no file", answer.Code, answer.Body) + } +} + +func TestAppChecksThePageByATagOfTheBytesSentAndNeverByItsDate(t *testing.T) { + t.Parallel() + + handler := newApp(t, builtApp(), gospa.AppOptions{}) + first := ask(handler, http.MethodGet, "/posts/42") + tag := first.Header().Get("Etag") + checked := ask(handler, http.MethodGet, "/posts/42", "If-None-Match", tag) + if checked.Code != http.StatusNotModified || checked.Body.Len() != 0 { + t.Errorf("GET /posts/42 with its tag = %d %q, want 304 with no body", checked.Code, checked.Body) + } + later := built.Add(time.Hour).Format(http.TimeFormat) + dated := ask(handler, http.MethodGet, "/posts/42", "If-Modified-Since", later) + isPage(t, "/posts/42", dated, page) +} + +func TestAppWritesItsValuesIntoThePage(t *testing.T) { + t.Parallel() + + values := []gospa.Meta{{Name: "api-root", Content: "/api/"}, {Name: "write-timeout", Content: "30"}} + handler := newApp(t, builtApp("help.html"), gospa.AppOptions{Meta: values}) + want := `` + + `App
` + for _, target := range []string{"/", "/posts/42", "/index.html"} { + answer := ask(handler, http.MethodGet, target) + isPage(t, target, answer, want) + } + if got := ask(handler, http.MethodGet, "/help.html").Body.String(); got != "content of help.html" { + t.Errorf("GET /help.html = %q, want the file as built", got) + } +} + +func TestAppTagsThePageAfreshWhenItsValuesChange(t *testing.T) { + t.Parallel() + + build := builtApp() + before := newApp(t, build, gospa.AppOptions{Meta: []gospa.Meta{{Name: "write-timeout", Content: "30"}}}) + tag := ask(before, http.MethodGet, "/").Header().Get("Etag") + after := newApp(t, build, gospa.AppOptions{Meta: []gospa.Meta{{Name: "write-timeout", Content: "60"}}}) + answer := ask(after, http.MethodGet, "/", "If-None-Match", tag) + want := strings.Replace(page, "", ``, 1) + isPage(t, "/", answer, want) +} + +func TestAppAnswersHeadWithTheHeadersOfThePage(t *testing.T) { + t.Parallel() + + handler := newApp(t, builtApp(), gospa.AppOptions{}) + answer := ask(handler, http.MethodHead, "/posts/42") + isPage(t, "HEAD /posts/42", answer, "") + if got := answer.Header().Get("Content-Length"); got != strconv.Itoa(len(page)) { + t.Errorf("HEAD /posts/42 Content-Length = %q, want %d", got, len(page)) + } +} + +func TestAppAnswersOnlyGetAndHead(t *testing.T) { + t.Parallel() + + handler := newApp(t, builtApp("favicon.svg"), gospa.AppOptions{NotFound: callersNotFound}) + for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} { + for _, target := range []string{"/", "/posts/42", "/favicon.svg", "/assets/index-0ldHa5h1.js", "/.env"} { + answer := ask(handler, method, target) + if answer.Code != http.StatusMethodNotAllowed || answer.Header().Get("Allow") != "GET, HEAD" { + t.Errorf("%s %s = %d allowing %q, want 405 allowing GET, HEAD", + method, target, answer.Code, answer.Header().Get("Allow")) + } + } + } +} + +func TestAppNeverSendsAHiddenFileOrAPathWithAnEmptySegment(t *testing.T) { + t.Parallel() + + build := builtApp(".env", ".git/config", "assets/index-DWLUpakq.js", "GIT~1/config", "index.html.", "INDEX~1.HTM") + handler := newApp(t, build, gospa.AppOptions{}) + for _, target := range []string{ + "/.env", "/.git/config", "/.git/", "/../go.mod", "/%2e%2e/go.mod", "/posts/../.env", + "//assets/index-DWLUpakq.js", "/posts//42", "//", + "/GIT~1/config", "/index.html.", "/index.html%20", "/INDEX~1.HTM", "/posts/~42", + } { + answer := ask(handler, http.MethodGet, target) + if answer.Code != http.StatusNotFound || answer.Body.String() == page { + t.Errorf("GET %s = %d %q, want 404", target, answer.Code, answer.Body) + } + } +} + +func TestAppSendsTheCallersNotFound(t *testing.T) { + t.Parallel() + + handler := newApp(t, builtApp(".env"), gospa.AppOptions{NotFound: callersNotFound}) + for _, target := range []string{"/assets/index-0ldHa5h1.js", "/assets/", "/.env", "/posts//42"} { + answer := ask(handler, http.MethodGet, target) + if answer.Code != http.StatusTeapot || answer.Body.String() != "the caller's own answer" { + t.Errorf("GET %s = %d %q, want the caller's own answer", target, answer.Code, answer.Body) + } + } +} + +func TestAppIsNotSetUpWithoutWhatItNeeds(t *testing.T) { + t.Parallel() + + folder := builtApp() + folder["index.html"] = &fstest.MapFile{Mode: fs.ModeDir | 0o755} + cases := []struct { + name string + build fstest.MapFS + opts gospa.AppOptions + want string + }{ + {name: "a build with no page", build: dated("favicon.svg"), want: "index.html"}, + {name: "a page that is a folder", build: folder, want: "index.html"}, + { + name: "a value with no name", + opts: gospa.AppOptions{Meta: []gospa.Meta{{Content: "30"}}}, + want: "gospa: page value 0 has no name", + }, + { + name: "a name given twice", + opts: gospa.AppOptions{Meta: []gospa.Meta{{Name: "a", Content: "1"}, {Name: "a", Content: "2"}}}, + want: `gospa: page value "a" is given twice`, + }, + { + name: "a window below one second", + opts: gospa.AppOptions{HashedMaxAge: 500 * time.Millisecond}, + want: "gospa: HashedMaxAge 500ms is below one second", + }, + { + name: "a negative window", + opts: gospa.AppOptions{HashedMaxAge: -time.Hour}, + want: "gospa: HashedMaxAge -1h0m0s is below one second", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + build := tc.build + if build == nil { + build = builtApp() + } + handler, err := gospa.App(build, tc.opts) + if err == nil || handler != nil { + t.Fatalf("App() = %v, %v, want an error holding %q", handler, err, tc.want) + } + if !strings.Contains(err.Error(), tc.want) || !strings.HasPrefix(err.Error(), "gospa: ") { + t.Errorf("App() = %q, want a gospa error holding %q", err, tc.want) + } + }) + } +} diff --git a/gospa/doc.go b/gospa/doc.go new file mode 100644 index 0000000..11e237a --- /dev/null +++ b/gospa/doc.go @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package gospa serves a built single-page app and the files of a public folder from an fs.FS. +package gospa diff --git a/gospa/example_test.go b/gospa/example_test.go new file mode 100644 index 0000000..629ebba --- /dev/null +++ b/gospa/example_test.go @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa_test + +import ( + "log" + "net/http" + "os" + "time" + + "github.com/gopherium/framework/gospa" +) + +func ExampleApp() { + admin, err := gospa.App(os.DirFS("dist"), gospa.AppOptions{ + HashedMaxAge: 30 * 24 * time.Hour, + Meta: []gospa.Meta{{Name: "api-root", Content: "/api/"}}, + }) + if err != nil { + log.Fatal(err) + } + http.Handle("/admin/", http.StripPrefix("/admin", admin)) +} + +func ExampleFiles() { + root, err := os.OpenRoot("uploads") + if err != nil { + log.Fatal(err) + } + http.Handle("/media/", http.StripPrefix("/media", gospa.Files(root.FS(), gospa.FilesOptions{}))) +} diff --git a/gospa/features/.golangci.yml b/gospa/features/.golangci.yml new file mode 100644 index 0000000..9fa6720 --- /dev/null +++ b/gospa/features/.golangci.yml @@ -0,0 +1,36 @@ +version: "2" + +linters: + default: standard + enable: + - depguard + - lll + - misspell + - revive + - unconvert + - unparam + settings: + lll: + line-length: 120 + revive: + rules: + - name: blank-imports + disabled: true + - name: exported + depguard: + rules: + dependency-purity: + list-mode: strict + allow: + - $gostd + - github.com/cucumber/godog + - github.com/gopherium/framework/gospa + +formatters: + enable: + - gofmt + - goimports + settings: + goimports: + local-prefixes: + - github.com/gopherium/framework diff --git a/gospa/features/app.feature b/gospa/features/app.feature new file mode 100644 index 0000000..0d941d4 --- /dev/null +++ b/gospa/features/app.feature @@ -0,0 +1,59 @@ +Feature: Serving a built single-page app + A built single-page app is one page, index.html, and the files its build + wrote beside it. The app's own router reads the address in the browser, + so every path that names no file gets the page, a missing file outside + assets/ included. The build writes its scripts, styles and fonts under + assets/, and only the page asks for them, so a path there that names no + file answers not found instead. A page from an older build that asks for + a file a newer build replaced then gets an error it can handle, never + HTML it would run as a script. A folder is never listed. The page is + read again each time it is sent, so a new build shows without a restart. + + Background: + Given a built app that holds "index.html", "favicon.svg", "images/logo.png" and "assets/index-DWLUpakq.js" + + Scenario Outline: Every path that names no file gets the page + When a browser asks for "" + Then the answer is the page + + Examples: + | path | + | / | + | /posts/42 | + | /settings/ | + | /images | + | /images/ | + | /images/missing.png | + | /assets-old/app.js | + + Scenario: A file the build wrote is sent as itself + When a browser asks for "/images/logo.png" + Then the answer is the file "images/logo.png" with the type "image/png" + + Scenario Outline: A path under assets that names no file answers not found + When a browser asks for "" + Then the answer is not found + + Examples: + | path | + | /assets/index-0ldHa5h1.js | + | /assets/fonts/ | + | /assets/ | + | /assets | + + Scenario: A page the build writes again is sent without a restart + When a browser asks for "/posts/42" + And the build writes "index.html" again as: + """ + Rebuilt + """ + And a browser asks for "/posts/42" + Then the answer reads: + """ + Rebuilt + """ + + Scenario: The app is not set up when its build holds no page + Given the build holds no "index.html" + When the app is set up + Then setting it up fails naming "index.html" diff --git a/gospa/features/caching.feature b/gospa/features/caching.feature new file mode 100644 index 0000000..4fa4ebb --- /dev/null +++ b/gospa/features/caching.feature @@ -0,0 +1,72 @@ +Feature: How long a browser keeps each file of a built app + A file under assets/ whose name ends in a hash of its content never + changes under that name, so a browser may keep it for a set window + without asking again. The hash is the 8 letters, digits, dashes or + underscores the build puts after a dash, just before the extension, in + any folder under assets/. The caller sets the + window, and it is one year when none is set. The page and every other + file may be kept too, but the browser checks each one with the server + on every load, so a new build shows at once. A check costs a 304 with + no body while nothing changed. A file is checked by its date when it has + one, and by a tag of its content when it has none, as files embedded in + the program do. The page is always checked by a tag of the bytes sent, + never by the date of its file. + + Background: + Given a built app that holds "index.html", "favicon.svg", "favicon-DWLUpakq.svg", "assets/logo.svg", "assets/index-DWLUpakq.js", "assets/vendor-a_B-9xYz.js" and "assets/index-DWLUpak.js" + + Scenario Outline: Only a file under assets with a hash in its name is kept without asking + When a browser asks for "" + Then the answer carries "Cache-Control: " + + Examples: + | path | rule | + | /assets/index-DWLUpakq.js | public, max-age=31536000, immutable | + | /assets/vendor-a_B-9xYz.js | public, max-age=31536000, immutable | + | /assets/index-DWLUpak.js | no-cache | + | /assets/logo.svg | no-cache | + | /favicon-DWLUpakq.svg | no-cache | + | /favicon.svg | no-cache | + | / | no-cache | + | /posts/42 | no-cache | + + Scenario: The caller sets a shorter window for hashed files + Given the window for hashed files is 1 hour + When a browser asks for "/assets/index-DWLUpakq.js" + Then the answer carries "Cache-Control: public, max-age=3600, immutable" + + Scenario: A file with a date is checked by its date + Given the files were last changed at "2026-11-01T10:00:00Z" + When a browser asks for "/favicon.svg" + Then the answer carries "Last-Modified: Sun, 01 Nov 2026 10:00:00 GMT" + When the browser asks for "/favicon.svg" again with the date it got + Then the answer is 304 with no body + + Scenario: A file with no date is checked by a tag of its content + Given the files carry no date, as embedded files do + When a browser asks for "/favicon.svg" + Then the answer carries a tag + When the browser asks for "/favicon.svg" again with the tag it got + Then the answer is 304 with no body + + Scenario: A file with no date that changes is sent again + Given the files carry no date, as embedded files do + When a browser asks for "/favicon.svg" + Then the answer carries a tag + When the build writes "favicon.svg" again as: + """ + a new logo + """ + And the browser asks for "/favicon.svg" again with the tag it got + Then the answer reads: + """ + a new logo + """ + + Scenario: The page is checked by a tag of the bytes sent, never by its date + Given the files were last changed at "2026-11-01T10:00:00Z" + When a browser asks for "/posts/42" + Then the answer carries a tag + And the answer carries no date + When the browser asks for "/posts/42" again with the tag it got + Then the answer is 304 with no body diff --git a/gospa/features/features_test.go b/gospa/features/features_test.go new file mode 100644 index 0000000..86f7be5 --- /dev/null +++ b/gospa/features/features_test.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 + +package features_test + +import ( + "os" + "testing" + + "github.com/cucumber/godog" +) + +// wipTag selects the scenarios no code makes pass yet. +const wipTag = "@wip" + +func TestFeatures(t *testing.T) { + tags := "~" + wipTag + if os.Getenv("GOSPA_BDD_WIP") != "" { + tags = "" + } + suite := godog.TestSuite{ + ScenarioInitializer: initializeScenario, + Options: &godog.Options{ + Format: "pretty", + Paths: []string{"."}, + Tags: tags, + Strict: true, + TestingT: t, + }, + } + if suite.Run() != 0 { + t.Error("the features did not pass") + } +} diff --git a/gospa/features/files.feature b/gospa/features/files.feature new file mode 100644 index 0000000..b87fefd --- /dev/null +++ b/gospa/features/files.feature @@ -0,0 +1,33 @@ +Feature: Serving a public folder + A public folder, such as the files people upload or the static files of + a site, is served file by file. There is no page to fall back to, so a + path that names no file answers not found. A folder is never listed, + and its index.html is sent only when asked for by name. The browser + checks every file with the server on every load. + + Background: + Given a public folder that holds "logo.png", "docs/guide.pdf" and "docs/index.html" + + Scenario: A file is sent as itself and checked on every load + When a browser asks for "/logo.png" + Then the answer is the file "logo.png" with the type "image/png" + And the answer carries "Cache-Control: no-cache" + + Scenario Outline: A path that names no file answers not found + When a browser asks for "" + Then the answer is not found + + Examples: + | path | + | /missing.png | + | / | + | /docs | + | /docs/ | + + Scenario: An index.html is sent when asked for by name + When a browser asks for "/docs/index.html" + Then the answer is the file "docs/index.html" with the type "text/html; charset=utf-8" + + Scenario: A part of a file is sent when asked + When a browser asks for "/docs/guide.pdf" with the range "bytes=0-3" + Then the answer is 206 holding the first 4 bytes of "docs/guide.pdf" diff --git a/gospa/features/go.mod b/gospa/features/go.mod new file mode 100644 index 0000000..4cb9b6d --- /dev/null +++ b/gospa/features/go.mod @@ -0,0 +1,21 @@ +module github.com/gopherium/framework/gospa/features + +go 1.27.4 + +require ( + github.com/cucumber/godog v0.16.0 + github.com/gopherium/framework/gospa v0.0.0 +) + +require ( + github.com/cucumber/gherkin/go/v42 v42.0.0 // indirect + github.com/cucumber/messages/go/v34 v34.2.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/hashicorp/go-immutable-radix v1.3.1 // indirect + github.com/hashicorp/go-memdb v1.3.5 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect + github.com/spf13/pflag v1.0.10 // indirect + golang.org/x/net v0.63.0 // indirect +) + +replace github.com/gopherium/framework/gospa => ../ diff --git a/gospa/features/go.sum b/gospa/features/go.sum new file mode 100644 index 0000000..bab606b --- /dev/null +++ b/gospa/features/go.sum @@ -0,0 +1,30 @@ +github.com/cucumber/gherkin/go/v42 v42.0.0 h1:Ulh3E2awUUSSja+wonP/IOQ+ycmiZwZbgmzqk5H8JNI= +github.com/cucumber/gherkin/go/v42 v42.0.0/go.mod h1:CsaumaO2dR9XvBc6ZyiGLMhWCKtTRDxgoxqJigSjSSg= +github.com/cucumber/godog v0.16.0 h1:ezQbgItuWqZrjPUQwLJ3muwIlvzXBOfZso5QZfG7efE= +github.com/cucumber/godog v0.16.0/go.mod h1:EDUX9yCqANK+GpbftMDeu61sUDtdLuo1JJgXD2n3bbM= +github.com/cucumber/messages/go/v34 v34.2.0 h1:VCbcNOMz+f8ccjjOOx1NLBNhwvE7/X49Atc8klJa+i8= +github.com/cucumber/messages/go/v34 v34.2.0/go.mod h1:LYUPjqlTS1kS0pdkdf6sS5uirnjwiIzEGyXPezXNhL8= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= +github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-memdb v1.3.5 h1:b3taDMxCBCBVgyRrS1AZVHO14ubMYZB++QpNhBg+Nyo= +github.com/hashicorp/go-memdb v1.3.5/go.mod h1:8IVKKBkVe+fxFgdFOYxzQQNjz+sWCyHCdIC/+5+Vy1Y= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.2 h1:cfejS+Tpcp13yd5nYHWDI6qVCny6wyX2Mt5SGur2IGE= +github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= +golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/gospa/features/requests.feature b/gospa/features/requests.feature new file mode 100644 index 0000000..7ad9778 --- /dev/null +++ b/gospa/features/requests.feature @@ -0,0 +1,127 @@ +Feature: Rules a built app and a public folder share + A built app and a public folder follow the same rules. A path segment + that starts with a dot names a hidden file, such as .env or .git, and + answers not found whether or not the file is there. The one exception + is .well-known itself, the folder the web keeps for public files such + as security.txt. A segment that holds a tilde or ends in a dot or a + space answers not found too, since Windows reads GIT~1 as .git and + index.html. as index.html. A path with an empty segment answers not + found. Only GET and HEAD are answered, and any other method gets 405 + with the methods allowed. A file gets the type its name gives, from a + table that is the same on every system, and a name the table does not + know gets a type that makes the browser download the file. Every file, + page and plain not found answer tells the browser never to guess a + type from the bytes. The caller may answer not found in its own way. + + Scenario Outline: A hidden file is never sent + Given a that holds "index.html", ".env", ".git/config", "docs/.draft.md", ".well-known.bak/key", "GIT~1/config" and "docs/notes.md." + When a browser asks for "" + Then the answer is not found + + Examples: + | source | path | + | built app | /.env | + | built app | /.git/config | + | built app | /.git/ | + | built app | /../go.mod | + | built app | /%2e%2e/go.mod | + | built app | /GIT~1/config | + | built app | /index.html. | + | public folder | /.env | + | public folder | /docs/.draft.md | + | public folder | /docs/../.env | + | public folder | /.well-known.bak/key | + | public folder | /GIT~1/config | + | public folder | /docs/notes.md. | + | public folder | /docs/notes.md%20 | + + Scenario Outline: A file under .well-known is sent + Given a that holds "index.html" and ".well-known/security.txt" + When a browser asks for "/.well-known/security.txt" + Then the answer is the file ".well-known/security.txt" with the type "text/plain; charset=utf-8" + + Examples: + | source | + | built app | + | public folder | + + Scenario Outline: A path with an empty segment answers not found + Given a that holds "index.html" and "assets/index-DWLUpakq.js" + When a browser asks for "" + Then the answer is not found + + Examples: + | source | path | + | built app | //assets/index-DWLUpakq.js | + | built app | /posts//42 | + | public folder | //index.html | + | public folder | /assets//index-DWLUpakq.js | + + Scenario Outline: Only GET and HEAD are answered + Given a that holds "index.html" and "favicon.svg" + When a browser asks for "" with the method "" + Then the answer is 405 allowing "GET, HEAD" + + Examples: + | source | method | path | + | built app | POST | / | + | built app | DELETE | /posts/42 | + | built app | PUT | /favicon.svg | + | public folder | POST | /favicon.svg | + | public folder | PATCH | /missing.png | + + Scenario: HEAD gets the headers of the page without its body + Given a built app that holds "index.html" + When a browser asks for "/posts/42" with the method "HEAD" + Then the answer carries "Content-Type: text/html; charset=utf-8" + And the answer carries the length of the page + And the answer has no body + + Scenario Outline: A file gets the type its name gives, the same on every system + Given a public folder that holds "" + When a browser asks for "/" + Then the answer is the file "" with the type "" + + Examples: + | name | type | + | robots.txt | text/plain; charset=utf-8 | + | fonts/inter.woff2 | font/woff2 | + | media/clip.mp4 | video/mp4 | + | site.webmanifest | application/manifest+json | + | notes | application/octet-stream | + | report.unknowntype | application/octet-stream | + + Scenario: A file that looks like HTML but whose name gives no type is sent as a download + Given a public folder that holds "notes" that reads: + """ + + """ + When a browser asks for "/notes" + Then the answer is the file "notes" with the type "application/octet-stream" + + Scenario Outline: Every file, page and plain not found answer tells the browser never to guess a type + Given a that holds "index.html", "favicon.svg" and "assets/index-DWLUpakq.js" + When a browser asks for "" + Then the answer carries "X-Content-Type-Options: nosniff" + + Examples: + | source | path | + | built app | /posts/42 | + | built app | /assets/index-DWLUpakq.js | + | built app | /assets/index-0ldHa5h1.js | + | built app | /.env | + | public folder | /favicon.svg | + | public folder | /missing.png | + + Scenario Outline: The caller may answer not found in its own way + Given a that holds "index.html" and "favicon.svg" + And the caller answers not found in its own way + When a browser asks for "" + Then the caller's own answer is sent + + Examples: + | source | path | + | built app | /assets/index-0ldHa5h1.js | + | built app | /.env | + | public folder | /missing.png | + | public folder | /.env | diff --git a/gospa/features/steps_test.go b/gospa/features/steps_test.go new file mode 100644 index 0000000..c11a241 --- /dev/null +++ b/gospa/features/steps_test.go @@ -0,0 +1,346 @@ +// SPDX-License-Identifier: Apache-2.0 + +package features_test + +import ( + "context" + "errors" + "fmt" + "html" + "net/http" + "strconv" + "strings" + "time" + + "github.com/cucumber/godog" +) + +// bindBuildSteps binds the steps that describe the folder and how it is served. +func bindBuildSteps(sc *godog.ScenarioContext) { + sc.Step(`^a (built app|public folder) that holds ((?:"[^"]*"(?:, | and )?)+)$`, holds) + sc.Step(`^a public folder that holds "([^"]*)" that reads:$`, holdsReading) + sc.Step(`^a built app whose page reads:$`, pageReads) + sc.Step(`^the build holds no "([^"]*)"$`, holdsNo) + sc.Step(`^the build writes "([^"]*)"(?: again)? as:$`, buildWrites) + sc.Step(`^the window for hashed files is (\d+) hours?$`, windowIs) + sc.Step(`^the files were last changed at "([^"]*)"$`, changedAt) + sc.Step(`^the files carry no date, as embedded files do$`, carryNoDate) + sc.Step(`^the app carries the value "([^"]*)" set to "([^"]*)"$`, carriesValue) + sc.Step(`^the app carries the value "([^"]*)" set to:$`, carriesValueReading) + sc.Step(`^the caller answers not found in its own way$`, answersNotFound) +} + +// bindRequestSteps binds the steps in which a browser asks and the program starts. +func bindRequestSteps(sc *godog.ScenarioContext) { + sc.Step(`^a browser asks for "([^"]*)"$`, asksFor) + sc.Step(`^the browser asks for "([^"]*)" again with the (tag|date) it got$`, asksAgain) + sc.Step(`^a browser asks for "([^"]*)" with the method "([^"]*)"$`, asksWithMethod) + sc.Step(`^a browser asks for "([^"]*)" with the range "([^"]*)"$`, asksForRange) + sc.Step(`^the program starts again with the value "([^"]*)" set to "([^"]*)"$`, startsAgain) + sc.Step(`^the app is set up$`, isSetUp) +} + +// bindAnswerSteps binds the steps that check the answer. +func bindAnswerSteps(sc *godog.ScenarioContext) { + sc.Step(`^the answer is the page$`, isThePage) + sc.Step(`^the answer is the file "([^"]*)" with the type "([^"]*)"$`, isTheFile) + sc.Step(`^the answer is not found$`, isNotFound) + sc.Step(`^the answer reads:$`, reads) + sc.Step(`^the answer holds:$`, answerHolds) + sc.Step(`^the answer carries "([^":]+): ([^"]*)"$`, carriesHeader) + sc.Step(`^the answer carries a tag$`, carriesTag) + sc.Step(`^the answer carries no date$`, carriesNoDate) + sc.Step(`^the answer is 304 with no body$`, isNotModified) + sc.Step(`^the answer is 405 allowing "([^"]*)"$`, isNotAllowed) + sc.Step(`^the answer is 206 holding the first (\d+) bytes of "([^"]*)"$`, isPart) + sc.Step(`^the answer carries the length of the page$`, carriesPageLength) + sc.Step(`^the answer has no body$`, hasNoBody) + sc.Step(`^setting it up fails naming "([^"]*)"$`, setUpFails) + sc.Step(`^the caller's own answer is sent$`, isCallersAnswer) +} + +// holds puts each name of list in a folder served as source, index.html as a page and the rest named by content. +func holds(ctx context.Context, source, list string) { + w := worldOf(ctx) + w.app = source == "built app" + for _, name := range names(list) { + data := "content of " + name + if name == "index.html" { + data = defaultPage + } + w.write(name, data) + } +} + +// holdsReading puts name in a public folder with the doc string as its content. +func holdsReading(ctx context.Context, name string, content *godog.DocString) { + worldOf(ctx).write(name, content.Content) +} + +// pageReads makes the scenario a built app whose page is the doc string. +func pageReads(ctx context.Context, content *godog.DocString) { + w := worldOf(ctx) + w.app = true + w.write("index.html", content.Content) +} + +// holdsNo takes name out of the build. +func holdsNo(ctx context.Context, name string) { + delete(worldOf(ctx).folder, name) +} + +// buildWrites puts name in the build with the doc string as its content. +func buildWrites(ctx context.Context, name string, content *godog.DocString) { + worldOf(ctx).write(name, content.Content) +} + +// windowIs sets how many hours a browser keeps a hashed file. +func windowIs(ctx context.Context, hours int) { + worldOf(ctx).opts.HashedMaxAge = time.Duration(hours) * time.Hour +} + +// changedAt makes every file carry the date stamp. +func changedAt(ctx context.Context, stamp string) error { + changed, err := time.Parse(time.RFC3339, stamp) + if err != nil { + return err + } + worldOf(ctx).redate(changed) + return nil +} + +// carryNoDate makes every file carry no date. +func carryNoDate(ctx context.Context) { + worldOf(ctx).redate(time.Time{}) +} + +// carriesValue makes the page carry content under name. +func carriesValue(ctx context.Context, name, content string) { + worldOf(ctx).setValue(name, content) +} + +// carriesValueReading makes the page carry the doc string under name. +func carriesValueReading(ctx context.Context, name string, content *godog.DocString) { + worldOf(ctx).setValue(name, content.Content) +} + +// answersNotFound makes the caller answer not found with its own body. +func answersNotFound(ctx context.Context) { + worldOf(ctx).opts.NotFound = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(callersAnswer)) + }) +} + +// asksFor sends a GET for target. +func asksFor(ctx context.Context, target string) error { + return worldOf(ctx).ask(http.MethodGet, target) +} + +// asksAgain sends a GET for target that checks the tag or the date the last answer gave. +func asksAgain(ctx context.Context, target, by string) error { + w := worldOf(ctx) + if by == "tag" { + return w.ask(http.MethodGet, target, "If-None-Match", w.tag) + } + return w.ask(http.MethodGet, target, "If-Modified-Since", w.date) +} + +// asksWithMethod sends a request for target with method. +func asksWithMethod(ctx context.Context, target, method string) error { + return worldOf(ctx).ask(method, target) +} + +// asksForRange sends a GET for the part of target that span names. +func asksForRange(ctx context.Context, target, span string) error { + return worldOf(ctx).ask(http.MethodGet, target, "Range", span) +} + +// startsAgain sets the value under name to content and sets the app up again. +func startsAgain(ctx context.Context, name, content string) { + w := worldOf(ctx) + w.setValue(name, content) + w.handler = nil +} + +// isSetUp sets the app up and keeps the error App gives. +func isSetUp(ctx context.Context) { + worldOf(ctx).setUp() +} + +// isThePage checks that the answer is index.html with every value the app carries written in. +func isThePage(ctx context.Context) error { + w := worldOf(ctx) + if err := hasStatus(w, http.StatusOK); err != nil { + return err + } + if kind := w.answer.Header().Get("Content-Type"); kind != "text/html; charset=utf-8" { + return fmt.Errorf("the answer to %s is typed %q, not as a page", w.path, kind) + } + body := w.answer.Body.String() + for _, value := range w.opts.Meta { + element := `` + if strings.Count(body, element) != 1 { + return fmt.Errorf("the page %q does not hold %q once", body, element) + } + body = strings.Replace(body, element, "", 1) + } + if page := string(w.folder["index.html"].Data); body != page { + return fmt.Errorf("the answer to %s reads %q, not the page %q", w.path, w.answer.Body, page) + } + return nil +} + +// isTheFile checks that the answer sends the file name typed as kind. +func isTheFile(ctx context.Context, name, kind string) error { + w := worldOf(ctx) + if err := hasStatus(w, http.StatusOK); err != nil { + return err + } + if got := w.answer.Header().Get("Content-Type"); got != kind { + return fmt.Errorf("the answer to %s is typed %q, not %q", w.path, got, kind) + } + if body, want := w.answer.Body.String(), string(w.folder[name].Data); body != want { + return fmt.Errorf("the answer to %s reads %q, not the file %q", w.path, body, want) + } + return nil +} + +// isNotFound checks that the answer is 404. +func isNotFound(ctx context.Context) error { + return hasStatus(worldOf(ctx), http.StatusNotFound) +} + +// reads checks that the answer reads the doc string exactly. +func reads(ctx context.Context, content *godog.DocString) error { + w := worldOf(ctx) + if body := w.answer.Body.String(); body != content.Content { + return fmt.Errorf("the answer to %s reads %q, not %q", w.path, body, content.Content) + } + return nil +} + +// answerHolds checks that the answer holds the doc string. +func answerHolds(ctx context.Context, content *godog.DocString) error { + w := worldOf(ctx) + if body := w.answer.Body.String(); !strings.Contains(body, content.Content) { + return fmt.Errorf("the answer to %s reads %q, which does not hold %q", w.path, body, content.Content) + } + return nil +} + +// carriesHeader checks that the answer carries value under key. +func carriesHeader(ctx context.Context, key, value string) error { + w := worldOf(ctx) + if got := w.answer.Header().Get(key); got != value { + return fmt.Errorf("the answer to %s carries %s %q, not %q", w.path, key, got, value) + } + return nil +} + +// carriesTag checks that the answer carries an entity tag. +func carriesTag(ctx context.Context) error { + w := worldOf(ctx) + if tag := w.answer.Header().Get("ETag"); !strings.HasPrefix(tag, `"`) || !strings.HasSuffix(tag, `"`) { + return fmt.Errorf("the answer to %s carries the tag %q, not a strong tag", w.path, tag) + } + return nil +} + +// carriesNoDate checks that the answer carries no Last-Modified date. +func carriesNoDate(ctx context.Context) error { + w := worldOf(ctx) + if dates := w.answer.Header().Values("Last-Modified"); len(dates) > 0 { + return fmt.Errorf("the answer to %s carries the date %q", w.path, dates) + } + return nil +} + +// isNotModified checks that the answer is 304 with no body. +func isNotModified(ctx context.Context) error { + w := worldOf(ctx) + if err := hasStatus(w, http.StatusNotModified); err != nil { + return err + } + return hasNoBody(ctx) +} + +// isNotAllowed checks that the answer is 405 and allows methods. +func isNotAllowed(ctx context.Context, methods string) error { + w := worldOf(ctx) + if err := hasStatus(w, http.StatusMethodNotAllowed); err != nil { + return err + } + return carriesHeader(ctx, "Allow", methods) +} + +// isPart checks that the answer is 206 holding the first count bytes of name. +func isPart(ctx context.Context, count int, name string) error { + w := worldOf(ctx) + if err := hasStatus(w, http.StatusPartialContent); err != nil { + return err + } + if body, want := w.answer.Body.String(), string(w.folder[name].Data[:count]); body != want { + return fmt.Errorf("the answer to %s holds %q, not %q", w.path, body, want) + } + return nil +} + +// carriesPageLength checks that the answer carries the length of the page a GET of the same path sends. +func carriesPageLength(ctx context.Context) error { + w := worldOf(ctx) + head := w.answer + if err := w.ask(http.MethodGet, w.path); err != nil { + return err + } + length, want := head.Header().Get("Content-Length"), strconv.Itoa(w.answer.Body.Len()) + w.answer = head + if length != want { + return fmt.Errorf("the answer to HEAD %s carries the length %q, not %s", w.path, length, want) + } + return nil +} + +// hasNoBody checks that the answer has no body. +func hasNoBody(ctx context.Context) error { + w := worldOf(ctx) + if w.answer.Body.Len() != 0 { + return fmt.Errorf("the answer to %s has the body %q", w.path, w.answer.Body) + } + return nil +} + +// setUpFails checks that App failed with an error naming name. +func setUpFails(ctx context.Context, name string) error { + w := worldOf(ctx) + if w.setupErr == nil { + return errors.New("the app was set up") + } + if !strings.Contains(w.setupErr.Error(), name) { + return fmt.Errorf("setting the app up failed with %q, which does not name %q", w.setupErr, name) + } + return nil +} + +// isCallersAnswer checks that the answer is the caller's own not found answer. +func isCallersAnswer(ctx context.Context) error { + w := worldOf(ctx) + if err := hasStatus(w, http.StatusNotFound); err != nil { + return err + } + if body := w.answer.Body.String(); body != callersAnswer { + return fmt.Errorf("the answer to %s reads %q, not the caller's own answer", w.path, body) + } + return nil +} + +// hasStatus checks that the answer has the status code. +func hasStatus(w *world, code int) error { + if w.answer == nil { + return errors.New("no browser asked for anything") + } + if w.answer.Code != code { + return fmt.Errorf("the answer to %s is %d %q, not %d", w.path, w.answer.Code, w.answer.Body, code) + } + return nil +} diff --git a/gospa/features/values.feature b/gospa/features/values.feature new file mode 100644 index 0000000..839c0ad --- /dev/null +++ b/gospa/features/values.feature @@ -0,0 +1,104 @@ +Feature: Server values in the page of a built app + A program often holds values its app needs before it asks the server + anything, such as where the API lives or how long a write may take. + GoSPA writes each value into the page head as a meta element, which the + app reads with document.querySelector. The values go right where the + head opens, before anything the page holds, in the order the caller + gave them. Each name and value is escaped, so no value can end its + element or add markup. Only the page carries the values, whichever path + it answers. + + Background: + Given a built app whose page reads: + """ + + + + App + +
+ + """ + + Scenario: Each value is written as a meta element where the head opens + Given the app carries the value "api-root" set to "/api/" + And the app carries the value "write-timeout" set to "30" + When a browser asks for "/posts/42" + Then the answer reads: + """ + + + + App + +
+ + """ + + Scenario: A value that holds markup is escaped + Given the app carries the value "notice" set to: + """ + say "hi" & bye + """ + When a browser asks for "/" + Then the answer holds: + """ + + """ + + Scenario: A page with no head tag gets the values where its head would start + Given the build writes "index.html" again as: + """ + App
+ """ + And the app carries the value "api-root" set to "/api/" + When a browser asks for "/" + Then the answer reads: + """ + App
+ """ + + Scenario: Asking for index.html by name gets the page with its values + Given the app carries the value "api-root" set to "/api/" + When a browser asks for "/index.html" + Then the answer is the page + And the answer holds: + """ + + """ + + Scenario: A browser that kept the page from before a change of values gets the new page + Given the app carries the value "write-timeout" set to "30" + When a browser asks for "/" + And the program starts again with the value "write-timeout" set to "60" + And the browser asks for "/" again with the tag it got + Then the answer is the page + And the answer holds: + """ + + """ + + Scenario: Without values the page is sent as the build wrote it + When a browser asks for "/" + Then the answer reads: + """ + + + + App + +
+ + """ + + Scenario: No other HTML file carries the values + Given the build writes "help.html" as: + """ + Help + """ + And the app carries the value "api-root" set to "/api/" + When a browser asks for "/help.html" + Then the answer reads: + """ + Help + """ diff --git a/gospa/features/world_test.go b/gospa/features/world_test.go new file mode 100644 index 0000000..96cc6bd --- /dev/null +++ b/gospa/features/world_test.go @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: Apache-2.0 + +package features_test + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "regexp" + "testing/fstest" + "time" + + "github.com/cucumber/godog" + + "github.com/gopherium/framework/gospa" +) + +// built is the date every file of a scenario was last changed, unless the scenario says otherwise. +var built = time.Date(2026, 10, 1, 9, 0, 0, 0, time.UTC) + +// defaultPage is the page a built app holds when a scenario names index.html without its content. +const defaultPage = `App
` + +// callersAnswer is the body of the caller's own not found answer. +const callersAnswer = "the caller's own not found answer" + +// quoted matches each quoted name of a list such as "a", "b" and "c". +var quoted = regexp.MustCompile(`"([^"]*)"`) + +// world is the state of one scenario. +type world struct { + app bool + folder fstest.MapFS + changed time.Time + opts gospa.AppOptions + handler http.Handler + setupErr error + path string + answer *httptest.ResponseRecorder + tag string + date string +} + +// worldKey carries a scenario's world in its context. +type worldKey struct{} + +// worldOf returns the world of the scenario ctx belongs to. +func worldOf(ctx context.Context) *world { + return ctx.Value(worldKey{}).(*world) +} + +// initializeScenario gives each scenario a fresh world and binds every step. +func initializeScenario(sc *godog.ScenarioContext) { + sc.Before(func(ctx context.Context, _ *godog.Scenario) (context.Context, error) { + return context.WithValue(ctx, worldKey{}, &world{folder: fstest.MapFS{}, changed: built}), nil + }) + bindBuildSteps(sc) + bindRequestSteps(sc) + bindAnswerSteps(sc) +} + +// names returns the quoted names of list in order. +func names(list string) []string { + var found []string + for _, match := range quoted.FindAllStringSubmatch(list, -1) { + found = append(found, match[1]) + } + return found +} + +// write puts name in the folder with data as its content, changed when the scenario's files were. +func (w *world) write(name, data string) { + w.folder[name] = &fstest.MapFile{Data: []byte(data), ModTime: w.changed} +} + +// redate makes every file of the folder carry changed as its date. +func (w *world) redate(changed time.Time) { + w.changed = changed + for _, file := range w.folder { + file.ModTime = changed + } +} + +// setValue sets the value the app carries under name, keeping its place when it carries it already. +func (w *world) setValue(name, content string) { + for i, value := range w.opts.Meta { + if value.Name == name { + w.opts.Meta[i].Content = content + return + } + } + w.opts.Meta = append(w.opts.Meta, gospa.Meta{Name: name, Content: content}) +} + +// setUp builds the handler of the scenario's folder, keeping the error when App fails. +func (w *world) setUp() { + if !w.app { + w.handler = gospa.Files(w.folder, gospa.FilesOptions{NotFound: w.opts.NotFound}) + return + } + w.handler, w.setupErr = gospa.App(w.folder, w.opts) +} + +// ask sends one request for target with the given header pairs and keeps the answer, its tag and its date. +func (w *world) ask(method, target string, header ...string) error { + if w.handler == nil { + w.setUp() + } + if w.setupErr != nil { + return fmt.Errorf("the app was not set up: %w", w.setupErr) + } + request := httptest.NewRequest(method, target, nil) + for i := 0; i+1 < len(header); i += 2 { + request.Header.Set(header[i], header[i+1]) + } + w.path = target + w.answer = httptest.NewRecorder() + w.handler.ServeHTTP(w.answer, request) + if tag := w.answer.Header().Get("ETag"); tag != "" { + w.tag = tag + } + if date := w.answer.Header().Get("Last-Modified"); date != "" { + w.date = date + } + return nil +} diff --git a/gospa/files.go b/gospa/files.go new file mode 100644 index 0000000..6206c9b --- /dev/null +++ b/gospa/files.go @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "io/fs" + "net/http" +) + +// FilesOptions says how Files answers a path that names no file it may send. +type FilesOptions struct { + // NotFound answers such a path, http.NotFound when nil. + NotFound http.Handler +} + +// files is the handler Files returns. +type files struct { + folder folder + notFound http.Handler +} + +// Files returns a handler that sends the regular files of fsys by their path and nothing else. +func Files(fsys fs.FS, opts FilesOptions) http.Handler { + return &files{folder: folder{fsys: fsys}, notFound: orNotFound(opts.NotFound)} +} + +// ServeHTTP sends the file r names, or the not found answer when it names none it may send. +func (h *files) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if !readable(w, r) { + return + } + name, ok := fileName(r.URL.Path) + if !ok { + h.notFound.ServeHTTP(w, r) + return + } + open, ok := h.folder.open(name) + if !ok { + h.notFound.ServeHTTP(w, r) + return + } + h.folder.send(w, r, open, noCache) +} diff --git a/gospa/files_test.go b/gospa/files_test.go new file mode 100644 index 0000000..d6618ff --- /dev/null +++ b/gospa/files_test.go @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa_test + +import ( + "crypto/sha256" + "encoding/hex" + "io/fs" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync/atomic" + "testing" + "testing/fstest" + "time" + + "github.com/gopherium/framework/gospa" +) + +func TestFilesSendsAFileWithItsTypeCheckedOnEveryLoad(t *testing.T) { + t.Parallel() + + handler := gospa.Files(dated("images/logo.png"), gospa.FilesOptions{}) + answer := ask(handler, http.MethodGet, "/images/logo.png") + + want := map[string]string{ + "Content-Type": "image/png", + "Cache-Control": "no-cache", + "X-Content-Type-Options": "nosniff", + "Last-Modified": "Sun, 01 Nov 2026 10:00:00 GMT", + } + if answer.Code != http.StatusOK || answer.Body.String() != "content of images/logo.png" { + t.Errorf("GET /images/logo.png = %d %q, want 200 with the file", answer.Code, answer.Body) + } + for key, value := range want { + if got := answer.Header().Get(key); got != value { + t.Errorf("GET /images/logo.png %s = %q, want %q", key, got, value) + } + } + if !absent(answer.Header(), "Etag") { + t.Errorf("GET /images/logo.png Etag = %q, want none", answer.Header().Values("Etag")) + } +} + +func TestFilesSendsOnlyRegularFiles(t *testing.T) { + t.Parallel() + + folder := fstest.MapFS{ + "link.png": {Data: []byte("logo.png"), Mode: fs.ModeSymlink, ModTime: built}, + "device": {Mode: fs.ModeDevice, ModTime: built}, + "pipe": {Mode: fs.ModeNamedPipe, ModTime: built}, + "socket": {Mode: fs.ModeSocket, ModTime: built}, + } + handler := gospa.Files(folder, gospa.FilesOptions{}) + for _, target := range []string{"/link.png", "/device", "/pipe", "/socket"} { + if answer := ask(handler, http.MethodGet, target); answer.Code != http.StatusNotFound { + t.Errorf("GET %s = %d %q, want 404", target, answer.Code, answer.Body) + } + } +} + +func TestFilesAnswersNotFoundForANameAFolderCouldNotHold(t *testing.T) { + t.Parallel() + + handler := gospa.Files(lenientFS{MapFS: dated("logo.png")}, gospa.FilesOptions{}) + if answer := ask(handler, http.MethodGet, "/logo.png/"); answer.Code != http.StatusNotFound { + t.Errorf("GET /logo.png/ from a lenient folder = %d %q, want 404", answer.Code, answer.Body) + } +} + +func TestFilesAnswersNotFoundForAPathThatNamesNoFile(t *testing.T) { + t.Parallel() + + handler := gospa.Files(dated("logo.png", "docs/index.html"), gospa.FilesOptions{}) + for _, target := range []string{"/missing.png", "/", "/docs", "/docs/", "/logo.png/", "/index.html"} { + answer := ask(handler, http.MethodGet, target) + if answer.Code != http.StatusNotFound { + t.Errorf("GET %s = %d %q, want 404", target, answer.Code, answer.Body) + } + if got := answer.Header().Get("X-Content-Type-Options"); got != "nosniff" { + t.Errorf("GET %s X-Content-Type-Options = %q, want nosniff", target, got) + } + } +} + +func TestFilesAnswersNotFoundForAnEmptyPath(t *testing.T) { + t.Parallel() + + handler := gospa.Files(dated("logo.png"), gospa.FilesOptions{}) + request := ask(http.StripPrefix("/media", handler), http.MethodGet, "/media") + if request.Code != http.StatusNotFound { + t.Errorf("GET /media under /media = %d, want 404", request.Code) + } +} + +func TestFilesNeverSendsAHiddenFile(t *testing.T) { + t.Parallel() + + folder := dated( + ".env", ".git/config", "docs/.draft.md", ".well-known/.key", "..well-known/x", "docs/guide.pdf", + ".well-known.bak/key", ".well-known-old/key", + ) + handler := gospa.Files(folder, gospa.FilesOptions{}) + for _, target := range []string{ + "/.env", "/.git/config", "/.git/", "/docs/.draft.md", "/docs/../.env", "/../go.mod", + "/%2e%2e/go.mod", "/docs/%2e%2e/.env", "/.", "/./docs/guide.pdf", "/..", "/.well-known/.key", "/..well-known/x", + "/.well-known.bak/key", "/.well-known-old/key", + } { + answer := ask(handler, http.MethodGet, target) + if answer.Code != http.StatusNotFound || strings.Contains(answer.Body.String(), "content of") { + t.Errorf("GET %s = %d %q, want 404", target, answer.Code, answer.Body) + } + } +} + +func TestFilesAnswersNotFoundForANameWindowsReadsAsAnother(t *testing.T) { + t.Parallel() + + folder := dated("GIT~1/config", "ENV~1", "env~1", "docs~/guide.pdf", "docs/guide.pdf.", "docs/guide.pdf ", "docs. /x") + handler := gospa.Files(folder, gospa.FilesOptions{}) + for _, target := range []string{ + "/GIT~1/config", "/ENV~1", "/env~1", "/docs~/guide.pdf", "/docs/guide.pdf.", "/docs/guide.pdf%20", "/docs.%20/x", + } { + answer := ask(handler, http.MethodGet, target) + if answer.Code != http.StatusNotFound || strings.Contains(answer.Body.String(), "content of") { + t.Errorf("GET %s = %d %q, want 404", target, answer.Code, answer.Body) + } + } +} + +func TestFilesSendsAFileUnderWellKnown(t *testing.T) { + t.Parallel() + + handler := gospa.Files(dated(".well-known/security.txt", "site/.well-known/assetlinks.json"), gospa.FilesOptions{}) + for target, kind := range map[string]string{ + "/.well-known/security.txt": "text/plain; charset=utf-8", + "/site/.well-known/assetlinks.json": "application/json", + } { + answer := ask(handler, http.MethodGet, target) + if answer.Code != http.StatusOK || answer.Header().Get("Content-Type") != kind { + t.Errorf("GET %s = %d %q, want 200 as %s", target, answer.Code, answer.Header().Get("Content-Type"), kind) + } + } +} + +func TestFilesAnswersNotFoundForAnEmptySegment(t *testing.T) { + t.Parallel() + + handler := gospa.Files(dated("logo.png", "docs/guide.pdf"), gospa.FilesOptions{}) + for _, target := range []string{"//logo.png", "/docs//guide.pdf", "//"} { + if answer := ask(handler, http.MethodGet, target); answer.Code != http.StatusNotFound { + t.Errorf("GET %s = %d %q, want 404", target, answer.Code, answer.Body) + } + } +} + +func TestFilesAnswersOnlyGetAndHead(t *testing.T) { + t.Parallel() + + handler := gospa.Files(dated("logo.png"), gospa.FilesOptions{NotFound: callersNotFound}) + for _, method := range []string{ + http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodOptions, http.MethodTrace, + } { + for _, target := range []string{"/logo.png", "/missing.png", "/.env"} { + answer := ask(handler, method, target) + if answer.Code != http.StatusMethodNotAllowed || answer.Header().Get("Allow") != "GET, HEAD" { + t.Errorf("%s %s = %d allowing %q, want 405 allowing GET, HEAD", + method, target, answer.Code, answer.Header().Get("Allow")) + } + } + } +} + +func TestFilesAnswersHeadWithTheHeadersAlone(t *testing.T) { + t.Parallel() + + handler := gospa.Files(dated("logo.png"), gospa.FilesOptions{}) + answer := ask(handler, http.MethodHead, "/logo.png") + if answer.Code != http.StatusOK || answer.Body.Len() != 0 { + t.Errorf("HEAD /logo.png = %d with %d bytes, want 200 with none", answer.Code, answer.Body.Len()) + } + if got, want := answer.Header().Get("Content-Length"), strconv.Itoa(len("content of logo.png")); got != want { + t.Errorf("HEAD /logo.png Content-Length = %q, want %s", got, want) + } +} + +func TestFilesSendsTheTypeOfEachNameFromItsOwnTable(t *testing.T) { + t.Parallel() + + types := map[string]string{ + "page.html": "text/html; charset=utf-8", + "page.htm": "text/html; charset=utf-8", + "style.css": "text/css; charset=utf-8", + "app.js": "text/javascript; charset=utf-8", + "app.mjs": "text/javascript; charset=utf-8", + "data.json": "application/json", + "app.js.map": "application/json", + "site.webmanifest": "application/manifest+json", + "robots.txt": "text/plain; charset=utf-8", + "feed.xml": "text/xml; charset=utf-8", + "logo.svg": "image/svg+xml", + "logo.png": "image/png", + "photo.jpg": "image/jpeg", + "photo.jpeg": "image/jpeg", + "anim.gif": "image/gif", + "photo.webp": "image/webp", + "photo.avif": "image/avif", + "favicon.ico": "image/vnd.microsoft.icon", + "font.woff": "font/woff", + "font.woff2": "font/woff2", + "font.ttf": "font/ttf", + "font.otf": "font/otf", + "module.wasm": "application/wasm", + "guide.pdf": "application/pdf", + "bundle.zip": "application/zip", + "song.mp3": "audio/mpeg", + "song.m4a": "audio/mp4", + "song.wav": "audio/wav", + "song.ogg": "audio/ogg", + "song.flac": "audio/flac", + "clip.mp4": "video/mp4", + "clip.webm": "video/webm", + "LOGO.PNG": "image/png", + "notes": "application/octet-stream", + "report.xyz": "application/octet-stream", + "archive.tar.gz": "application/octet-stream", + } + folder := fstest.MapFS{} + for name := range types { + folder[name] = &fstest.MapFile{Data: []byte(""), ModTime: built} + } + handler := gospa.Files(folder, gospa.FilesOptions{}) + for name, kind := range types { + if got := ask(handler, http.MethodGet, "/"+name).Header().Get("Content-Type"); got != kind { + t.Errorf("GET /%s Content-Type = %q, want %q", name, got, kind) + } + } +} + +func TestFilesChecksADatedFileByItsDate(t *testing.T) { + t.Parallel() + + handler := gospa.Files(dated("logo.png"), gospa.FilesOptions{}) + answer := ask(handler, http.MethodGet, "/logo.png", "If-Modified-Since", "Sun, 01 Nov 2026 10:00:00 GMT") + if answer.Code != http.StatusNotModified || answer.Body.Len() != 0 { + t.Errorf("GET /logo.png since its date = %d %q, want 304 with no body", answer.Code, answer.Body) + } +} + +func TestFilesChecksAFileWithNoDateByATagOfItsContent(t *testing.T) { + t.Parallel() + + handler := gospa.Files(undated("logo.png"), gospa.FilesOptions{}) + tag := contentTag(t, ask(handler, http.MethodGet, "/logo.png")) + checked := ask(handler, http.MethodGet, "/logo.png", "If-None-Match", tag) + if checked.Code != http.StatusNotModified || checked.Body.Len() != 0 { + t.Errorf("GET /logo.png with its tag = %d %q, want 304 with no body", checked.Code, checked.Body) + } +} + +func TestFilesTagsAFileWithNoDateTheSameEachTimeAndApartFromOtherContent(t *testing.T) { + t.Parallel() + + handler := gospa.Files(undated("logo.png", "icon.png"), gospa.FilesOptions{}) + tag := contentTag(t, ask(handler, http.MethodGet, "/logo.png")) + if again := contentTag(t, ask(handler, http.MethodGet, "/logo.png")); again != tag { + t.Errorf("GET /logo.png again tagged %q, want %q", again, tag) + } + if other := contentTag(t, ask(handler, http.MethodGet, "/icon.png")); other == tag { + t.Errorf("GET /icon.png tagged %q, the same as another content", other) + } +} + +// contentTag returns the tag of an answer that sent a file with no date, failing the test when it has another shape. +func contentTag(t *testing.T, answer *httptest.ResponseRecorder) string { + t.Helper() + if answer.Code != http.StatusOK { + t.Fatalf("the answer = %d %q, want 200", answer.Code, answer.Body) + } + tag := answer.Header().Get("Etag") + if !strongTag.MatchString(tag) { + t.Fatalf("the answer is tagged %q, want 32 hex digits in quotes", tag) + } + if !absent(answer.Header(), "Last-Modified") { + t.Errorf("the answer Last-Modified = %q, want none", answer.Header().Values("Last-Modified")) + } + return tag +} + +func TestFilesChecksAFileDatedAtTheEpochByATagOfItsContent(t *testing.T) { + t.Parallel() + + folder := fstest.MapFS{"robots.txt": {Data: []byte("User-agent: *"), ModTime: time.Unix(0, 0)}} + handler := gospa.Files(folder, gospa.FilesOptions{}) + tag := contentTag(t, ask(handler, http.MethodGet, "/robots.txt")) + checked := ask(handler, http.MethodGet, "/robots.txt", "If-None-Match", tag) + if checked.Code != http.StatusNotModified { + t.Errorf("GET /robots.txt dated at the epoch with its tag = %d %q, want 304", checked.Code, checked.Body) + } +} + +func TestFilesSendsAPartOfAFile(t *testing.T) { + t.Parallel() + + for name, folder := range datedAndUndated("docs/guide.pdf") { + handler := gospa.Files(folder, gospa.FilesOptions{}) + answer := ask(handler, http.MethodGet, "/docs/guide.pdf", "Range", "bytes=0-6") + if answer.Code != http.StatusPartialContent || answer.Body.String() != "content" { + t.Errorf("GET the first 7 bytes of a %s /docs/guide.pdf = %d %q, want 206 content", name, answer.Code, answer.Body) + } + } +} + +func TestFilesSendsAFileThatCannotSeek(t *testing.T) { + t.Parallel() + + for name, folder := range datedAndUndated("logo.png") { + handler := gospa.Files(brokenFS{MapFS: folder}, gospa.FilesOptions{}) + for range 2 { + answer := ask(handler, http.MethodGet, "/logo.png", "Range", "bytes=11-") + if answer.Code != http.StatusPartialContent || answer.Body.String() != "logo.png" { + t.Errorf("GET the end of a %s /logo.png that cannot seek = %d %q, want 206 logo.png", + name, answer.Code, answer.Body) + } + } + } +} + +func TestFilesReadsAFileThatCannotSeekOnlyAsFarAsItSends(t *testing.T) { + t.Parallel() + + size := 1 << 20 + folder := fstest.MapFS{"clip.mp4": {Data: make([]byte, size), ModTime: built}} + cases := []struct { + method, span string + most int64 + }{ + {method: http.MethodHead, most: 0}, + {method: http.MethodGet, span: "bytes=0-0", most: 1}, + {method: http.MethodGet, span: "bytes=0-99", most: 100}, + } + for _, tc := range cases { + read := &atomic.Int64{} + handler := gospa.Files(brokenFS{MapFS: folder, read: read}, gospa.FilesOptions{}) + answer := ask(handler, tc.method, "/clip.mp4", "Range", tc.span) + if got := read.Load(); got > tc.most { + t.Errorf("%s /clip.mp4 %s read %d bytes, want at most %d", tc.method, tc.span, got, tc.most) + } + if got := answer.Header().Get("Content-Length"); tc.span == "" && got != strconv.Itoa(size) { + t.Errorf("%s /clip.mp4 Content-Length = %q, want %d", tc.method, got, size) + } + } +} + +func TestFilesSendsTheWholeFileThatCannotSeekForSeveralRanges(t *testing.T) { + t.Parallel() + + handler := gospa.Files(brokenFS{MapFS: dated("logo.png")}, gospa.FilesOptions{}) + for _, spans := range []string{"bytes=11-12,0-3", "bytes=0-5,3-8", "bytes=0-1,5-6"} { + request := httptest.NewRequest(http.MethodGet, "/logo.png", nil) + request.Header.Set("Range", spans) + answer := httptest.NewRecorder() + handler.ServeHTTP(answer, request) + if answer.Code != http.StatusOK || answer.Body.String() != "content of logo.png" { + t.Errorf("GET %s of /logo.png that cannot seek = %d %q, want 200 with the whole file", + spans, answer.Code, answer.Body) + } + if got := request.Header.Get("Range"); got != spans { + t.Errorf("GET %s of /logo.png left the request Range %q, want it as sent", spans, got) + } + } +} + +func TestFilesSendsSeveralRangesOfAFileThatCanSeek(t *testing.T) { + t.Parallel() + + handler := gospa.Files(dated("logo.png"), gospa.FilesOptions{}) + answer := ask(handler, http.MethodGet, "/logo.png", "Range", "bytes=11-12,0-3") + if answer.Code != http.StatusPartialContent { + t.Fatalf("GET two ranges of /logo.png = %d %q, want 206", answer.Code, answer.Body) + } + if got := answer.Header().Get("Content-Type"); !strings.HasPrefix(got, "multipart/byteranges") { + t.Errorf("GET two ranges of /logo.png Content-Type = %q, want multipart/byteranges", got) + } + body := answer.Body.String() + if !strings.Contains(body, "\r\n\r\nlo\r\n") || !strings.Contains(body, "\r\n\r\ncont\r\n") { + t.Errorf("GET two ranges of /logo.png = %q, want the parts lo and cont", body) + } +} + +func TestFilesSendsAChangedFileWithNoDateToABrowserHoldingItsOldTag(t *testing.T) { + t.Parallel() + + folder := undated("logo.png") + handler := gospa.Files(folder, gospa.FilesOptions{}) + old := contentTag(t, ask(handler, http.MethodGet, "/logo.png")) + folder["logo.png"].Data = []byte("a new logo") + answer := ask(handler, http.MethodGet, "/logo.png", "If-None-Match", old) + if answer.Code != http.StatusOK || answer.Body.String() != "a new logo" { + t.Fatalf("GET the changed /logo.png with its old tag = %d %q, want 200 a new logo", answer.Code, answer.Body) + } + if tag := contentTag(t, answer); tag == old { + t.Errorf("GET the changed /logo.png tagged %q, the tag of its old content", tag) + } +} + +func TestFilesTagsAFileWithNoDateByTheBytesItSends(t *testing.T) { + t.Parallel() + + handler := gospa.Files(undated("docs/guide.pdf"), gospa.FilesOptions{}) + answer := ask(handler, http.MethodGet, "/docs/guide.pdf") + sum := sha256.Sum256(answer.Body.Bytes()) + if got, want := contentTag(t, answer), `"`+hex.EncodeToString(sum[:16])+`"`; got != want { + t.Errorf("GET /docs/guide.pdf %q tagged %s, want %s", answer.Body, got, want) + } +} + +func TestFilesSendsAFileWithNoDateThatCannotSeekWithNothingToCheck(t *testing.T) { + t.Parallel() + + handler := gospa.Files(brokenFS{MapFS: undated("logo.png")}, gospa.FilesOptions{}) + answer := ask(handler, http.MethodGet, "/logo.png") + if answer.Code != http.StatusOK || answer.Body.String() != "content of logo.png" { + t.Fatalf("GET an undated /logo.png that cannot seek = %d %q, want 200 with the file", answer.Code, answer.Body) + } + for _, key := range []string{"ETag", "Last-Modified"} { + if !absent(answer.Header(), key) { + t.Errorf("GET an undated /logo.png that cannot seek %s = %q, want none", key, answer.Header().Values(key)) + } + } +} + +func TestFilesAnswersAServerErrorForAFileWithNoDateItCannotRead(t *testing.T) { + t.Parallel() + + handler := gospa.Files(unreadableFS{MapFS: undated("logo.png")}, gospa.FilesOptions{}) + answer := ask(handler, http.MethodGet, "/logo.png") + if answer.Code != http.StatusInternalServerError || strings.Contains(answer.Body.String(), "unreadable") { + t.Errorf("GET an undated /logo.png that cannot be read = %d %q, want 500 naming no cause", answer.Code, answer.Body) + } +} + +func TestFilesCutsShortTheAnswerForADatedFileItCannotRead(t *testing.T) { + t.Parallel() + + handler := gospa.Files(brokenFS{MapFS: dated("logo.png"), failRead: true}, gospa.FilesOptions{}) + answer := ask(handler, http.MethodGet, "/logo.png") + if answer.Code != http.StatusOK || answer.Body.Len() != 0 { + t.Errorf("GET a dated /logo.png that cannot be read = %d %q, want 200 with no byte", answer.Code, answer.Body) + } + if got, want := answer.Header().Get("Content-Length"), strconv.Itoa(len("content of logo.png")); got != want { + t.Errorf("GET a dated /logo.png that cannot be read Content-Length = %q, want %s", got, want) + } +} + +func TestFilesAnswersNotFoundForAFileWithoutDetails(t *testing.T) { + t.Parallel() + + handler := gospa.Files(brokenFS{MapFS: dated("logo.png"), failStat: true}, gospa.FilesOptions{}) + if answer := ask(handler, http.MethodGet, "/logo.png"); answer.Code != http.StatusNotFound { + t.Errorf("GET /logo.png without details = %d %q, want 404", answer.Code, answer.Body) + } +} + +func TestFilesSendsTheCallersNotFound(t *testing.T) { + t.Parallel() + + handler := gospa.Files(dated("logo.png", "docs/guide.pdf"), gospa.FilesOptions{NotFound: callersNotFound}) + for _, target := range []string{"/missing.png", "/docs/", "/.env", "//logo.png"} { + answer := ask(handler, http.MethodGet, target) + if answer.Code != http.StatusTeapot || answer.Body.String() != "the caller's own answer" { + t.Errorf("GET %s = %d %q, want the caller's own answer", target, answer.Code, answer.Body) + } + } +} diff --git a/gospa/forward.go b/gospa/forward.go new file mode 100644 index 0000000..ed7ac60 --- /dev/null +++ b/gospa/forward.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "io" + "net/http" + "strings" +) + +// forward reads a file that cannot seek as an io.ReadSeeker that seeks only before its first read. +type forward struct { + io.Reader + size int64 +} + +// Seek tells the size for a seek to the end, and otherwise skips to offset. +func (f *forward) Seek(offset int64, whence int) (int64, error) { + if whence == io.SeekEnd { + return f.size, nil + } + return io.CopyN(io.Discard, f.Reader, offset) +} + +// ranged returns r, or a copy without its Range header when content only moves ahead and r asks for several ranges. +func ranged(r *http.Request, content io.ReadSeeker) *http.Request { + if _, ahead := content.(*forward); !ahead || !strings.Contains(r.Header.Get("Range"), ",") { + return r + } + whole := r.Clone(r.Context()) + whole.Header.Del("Range") + return whole +} diff --git a/gospa/go.mod b/gospa/go.mod new file mode 100644 index 0000000..985eff7 --- /dev/null +++ b/gospa/go.mod @@ -0,0 +1,5 @@ +module github.com/gopherium/framework/gospa + +go 1.27.4 + +require golang.org/x/net v0.63.0 diff --git a/gospa/go.sum b/gospa/go.sum new file mode 100644 index 0000000..62db04d --- /dev/null +++ b/gospa/go.sum @@ -0,0 +1,2 @@ +golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= +golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= diff --git a/gospa/head.go b/gospa/head.go new file mode 100644 index 0000000..18d03c0 --- /dev/null +++ b/gospa/head.go @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "bytes" + "fmt" + "slices" + + "golang.org/x/net/html" +) + +// byteOrderMark is the mark a UTF-8 page may open with. +const byteOrderMark = string(rune(0xFEFF)) + +// Meta is one server value the page carries in its head as a meta element. +type Meta struct { + // Name is the name the app looks the value up by. + Name string + // Content is the value the app reads. + Content string +} + +// metaElements returns the meta elements of values in order, nil when there are none. +func metaElements(values []Meta) ([]byte, error) { + var elements []byte + seen := make(map[string]bool, len(values)) + for i, value := range values { + if value.Name == "" { + return nil, fmt.Errorf("gospa: page value %d has no name", i) + } + if seen[value.Name] { + return nil, fmt.Errorf("gospa: page value %q is given twice", value.Name) + } + seen[value.Name] = true + elements = fmt.Appendf(elements, ``, + html.EscapeString(value.Name), html.EscapeString(value.Content)) + } + return elements, nil +} + +// withHead returns page with head written just after the doctype, html and head tags it opens with. +func withHead(page, head []byte) []byte { + at := headOffset(page) + return slices.Concat(page[:at], head, page[at:]) +} + +// headOffset returns the offset just after the doctype, html and head tags the page opens with. +func headOffset(page []byte) int { + start := 0 + if bytes.HasPrefix(page, []byte(byteOrderMark)) { + start = len(byteOrderMark) + } + tokens := html.NewTokenizer(bytes.NewReader(page[start:])) + offset, at := start, start + for kind := tokens.Next(); kind != html.ErrorToken; kind = tokens.Next() { + offset += len(tokens.Raw()) + switch { + case opensThePage(tokens, kind): + at = offset + case !blank(tokens, kind): + return at + } + } + return at +} + +// opensThePage reports whether the current token is a closed doctype or an html or head start tag. +func opensThePage(tokens *html.Tokenizer, kind html.TokenType) bool { + switch kind { + case html.DoctypeToken: + return bytes.HasSuffix(tokens.Raw(), []byte(">")) + case html.StartTagToken, html.SelfClosingTagToken: + name, _ := tokens.TagName() + return string(name) == "html" || string(name) == "head" + } + return false +} + +// blank reports whether the current token is a comment or text holding only HTML white space. +func blank(tokens *html.Tokenizer, kind html.TokenType) bool { + if kind == html.TextToken { + return len(bytes.Trim(tokens.Raw(), " \t\n\r\f")) == 0 + } + return kind == html.CommentToken +} diff --git a/gospa/head_test.go b/gospa/head_test.go new file mode 100644 index 0000000..96a74e1 --- /dev/null +++ b/gospa/head_test.go @@ -0,0 +1,272 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "slices" + "strings" + "testing" + + "golang.org/x/net/html" + "golang.org/x/net/html/atom" +) + +// head is the meta element the page shapes are written with. +const head = `` + +// mark is the byte order mark a page may open with. +const mark = byteOrderMark + +// pageShapes are pages of every shape, each with the page withHead makes of it. +var pageShapes = []struct { + name, page, want string +}{ + { + name: "a doctype, an html tag and a head tag", + page: `App`, + want: `` + head + `App`, + }, + { + name: "space and a comment between the opening tags", + page: "\n\n\n \n App", + want: "\n\n\n " + head + "\n App", + }, + { + name: "an upper case doctype and head", + page: `App`, + want: `` + head + `App`, + }, + { + name: "no doctype", + page: ``, + want: `` + head + ``, + }, + { + name: "no opening tag before the content", + page: `App`, + want: head + `App`, + }, + { + name: "an empty page", + page: ``, + want: head, + }, + { + name: "a head written inside a title", + page: `<head>`, + want: `` + head + `<head>`, + }, + { + name: "a head written inside a script", + page: ``, + want: `` + head + ``, + }, + { + name: "a head written inside a template", + page: `App`, + want: `` + head + `App`, + }, + { + name: "an html tag with attributes and no head", + page: `App`, + want: `` + head + `App`, + }, + { + name: "a head written inside an attribute", + page: ``, + want: `` + head + ``, + }, + { + name: "a self-closing head", + page: `App`, + want: `` + head + `App`, + }, + { + name: "an empty comment closed at once", + page: ``, + want: `` + head + ``, + }, + { + name: "a processing instruction before the doctype", + page: `App`, + want: `` + head + `App`, + }, + { + name: "a doctype that never closes", + page: `App`, + want: mark + `` + head + `App`, + }, + { + name: "a byte order mark alone", + page: mark, + want: mark + head, + }, + { + name: "a no-break space before the head", + page: " App", + want: "" + head + " App", + }, + { + name: "a vertical tab before the head", + page: "\vApp", + want: "" + head + "\vApp", + }, + { + name: "every HTML white space before the head", + page: " \t\n\r\fApp", + want: " \t\n\r\f" + head + "App", + }, + { + name: "a body as the first tag", + page: `
`, + want: `` + head + `
`, + }, + { + name: "a byte order mark after the doctype", + page: `` + mark + `App`, + want: `` + head + mark + `App`, + }, +} + +func TestWithHeadWritesTheValuesWhereThePageOpens(t *testing.T) { + t.Parallel() + + for _, tc := range pageShapes { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + got := string(withHead([]byte(tc.page), []byte(head))) + if got != tc.want { + t.Errorf("withHead(%q) = %q, want %q", tc.page, got, tc.want) + } + }) + } +} + +func TestMetaElementsWritesEachValueInOrderEscaped(t *testing.T) { + t.Parallel() + + got, err := metaElements([]Meta{ + {Name: "api-root", Content: "/api/"}, + {Name: `say "hi"`, Content: `it's &`}, + {Name: "empty", Content: ""}, + }) + want := `` + + `` + + `` + if err != nil || string(got) != want { + t.Errorf("metaElements() = %q, %v, want %q", got, err, want) + } +} + +func TestMetaElementsWritesNothingWithoutValues(t *testing.T) { + t.Parallel() + + got, err := metaElements(nil) + if err != nil || got != nil { + t.Errorf("metaElements(nil) = %q, %v, want nil", got, err) + } +} + +func TestMetaElementsRejectsAValueItCannotName(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + values []Meta + want string + }{ + { + name: "a value with no name", + values: []Meta{{Name: "api-root", Content: "/api/"}, {Content: "30"}}, + want: "gospa: page value 1 has no name", + }, + { + name: "a name given twice", + values: []Meta{{Name: "api-root", Content: "/api/"}, {Name: "api-root", Content: "/v2/"}}, + want: `gospa: page value "api-root" is given twice`, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + got, err := metaElements(tc.values) + if err == nil { + t.Fatalf("metaElements() = %q, want the error %q", got, tc.want) + } + if err.Error() != tc.want || got != nil { + t.Errorf("metaElements() = %q, %q, want nothing and the error %q", got, err, tc.want) + } + }) + } +} + +func FuzzWithHeadPutsTheValuesInTheHead(f *testing.F) { + for _, page := range []string{ + ``, + `App`, + "\n\n\n \n App", + `App`, + `App`, + `App`, + `` + mark + `App`, + ``, + "\x00", + " App", + "\vApp", + `
`, + } { + f.Add(page) + } + values := `` + f.Fuzz(func(t *testing.T, page string) { + if len(fuzzValues(t, page)) > 0 { + t.Skip("the page already holds the values") + } + out := string(withHead([]byte(page), []byte(values))) + if strings.Replace(out, values, "", 1) != page { + t.Fatalf("withHead(%q) = %q, which is not the page with the values added", page, out) + } + if got := fuzzValues(t, out); !slices.Equal(got, []string{"1", "2"}) { + t.Errorf("withHead(%q) = %q, whose head holds the values %q, want [1 2]", page, out, got) + } + }) +} + +// fuzzValues returns, in order, the content of each gospa-fuzz meta element in page as a browser decodes it. +func fuzzValues(t *testing.T, page string) []string { + t.Helper() + doc, err := html.Parse(strings.NewReader(strings.TrimPrefix(page, byteOrderMark))) + if err != nil { + t.Fatalf("parse %q: %v", page, err) + } + var values []string + for node := range doc.Descendants() { + if node.DataAtom != atom.Meta || attribute(node, "name") != "gospa-fuzz" { + continue + } + if node.Parent == nil || node.Parent.DataAtom != atom.Head { + values = append(values, "outside the head") + continue + } + values = append(values, attribute(node, "content")) + } + return values +} + +// attribute returns the value of the attribute key on node, or an empty string when node has none. +func attribute(node *html.Node, key string) string { + for _, attr := range node.Attr { + if attr.Key == key { + return attr.Val + } + } + return "" +} diff --git a/gospa/request_test.go b/gospa/request_test.go new file mode 100644 index 0000000..b082e1a --- /dev/null +++ b/gospa/request_test.go @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa_test + +import ( + "errors" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "sync/atomic" + "testing/fstest" + "time" +) + +// strongTag matches the strong entity tag GoSPA gives, 32 hex digits in quotes. +var strongTag = regexp.MustCompile(`^"[0-9a-f]{32}"$`) + +// built is the date the dated test files were last changed. +var built = time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC) + +// ask sends one request for target to handler with the given header pairs and returns the answer. +func ask(handler http.Handler, method, target string, header ...string) *httptest.ResponseRecorder { + request := httptest.NewRequest(method, target, nil) + for i := 0; i+1 < len(header); i += 2 { + request.Header.Set(header[i], header[i+1]) + } + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + return recorder +} + +// dated returns a folder holding each name with its own name as content, every file changed at built. +func dated(names ...string) fstest.MapFS { + folder := fstest.MapFS{} + for _, name := range names { + folder[name] = &fstest.MapFile{Data: []byte("content of " + name), ModTime: built} + } + return folder +} + +// undated returns a folder holding each name with its own name as content, as embedded files carry no date. +func undated(names ...string) fstest.MapFS { + folder := fstest.MapFS{} + for _, name := range names { + folder[name] = &fstest.MapFile{Data: []byte("content of " + name)} + } + return folder +} + +// datedAndUndated returns the folder of names both with dates and without, keyed by which. +func datedAndUndated(names ...string) map[string]fstest.MapFS { + return map[string]fstest.MapFS{"dated": dated(names...), "undated": undated(names...)} +} + +// callersNotFound is a caller's own answer for a path that names no file. +var callersNotFound = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusTeapot) + _, _ = w.Write([]byte("the caller's own answer")) +}) + +// errUnreadable is the error every read of a brokenFS file fails with. +var errUnreadable = errors.New("unreadable") + +// absent reports whether header carries no value at all under key. +func absent(header http.Header, key string) bool { + return len(header.Values(key)) == 0 +} + +// brokenFS wraps a folder whose files cannot seek, and whose reads or details fail when it says so. +type brokenFS struct { + fstest.MapFS + failRead, failStat bool + read *atomic.Int64 +} + +// Open opens name in the wrapped folder as a file that cannot seek. +func (b brokenFS) Open(name string) (fs.File, error) { + file, err := b.MapFS.Open(name) + if err != nil { + return nil, err + } + return brokenFile{file: file, failRead: b.failRead, failStat: b.failStat, read: b.read}, nil +} + +// brokenFile is a file that cannot seek, and whose reads or details fail when it says so. +type brokenFile struct { + file fs.File + failRead, failStat bool + read *atomic.Int64 +} + +// Stat returns the details of the file, or errUnreadable when its details fail. +func (b brokenFile) Stat() (fs.FileInfo, error) { + if b.failStat { + return nil, errUnreadable + } + return b.file.Stat() +} + +// Read reads the file and counts the bytes read, or fails with errUnreadable when its reads fail. +func (b brokenFile) Read(p []byte) (int, error) { + if b.failRead { + return 0, errUnreadable + } + n, err := b.file.Read(p) + if b.read != nil { + b.read.Add(int64(n)) + } + return n, err +} + +// Close closes the file. +func (b brokenFile) Close() error { + return b.file.Close() +} + +// unreadableFS wraps a folder whose files can seek but fail every read. +type unreadableFS struct { + fstest.MapFS +} + +// Open opens name in the wrapped folder as a file that can seek but fails every read. +func (u unreadableFS) Open(name string) (fs.File, error) { + file, err := u.MapFS.Open(name) + if err != nil { + return nil, err + } + return unreadableFile{File: file}, nil +} + +// unreadableFile is a file that can seek but fails every read with errUnreadable. +type unreadableFile struct { + fs.File +} + +// Read fails with errUnreadable. +func (unreadableFile) Read([]byte) (int, error) { + return 0, errUnreadable +} + +// Seek seeks the wrapped file. +func (u unreadableFile) Seek(offset int64, whence int) (int64, error) { + return u.File.(io.Seeker).Seek(offset, whence) +} + +// lenientFS wraps a folder that opens a name with a trailing slash as the name without it. +type lenientFS struct { + fstest.MapFS +} + +// Open opens name without its trailing slash. +func (l lenientFS) Open(name string) (fs.File, error) { + return l.MapFS.Open(strings.TrimSuffix(name, "/")) +} diff --git a/gospa/serve.go b/gospa/serve.go new file mode 100644 index 0000000..92fe900 --- /dev/null +++ b/gospa/serve.go @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "crypto/sha256" + "encoding/hex" + "io" + "io/fs" + "net/http" + "strings" + "time" +) + +// noCache lets a browser keep an answer but check it with the server on every load. +const noCache = "no-cache" + +// folder sends the regular files of one fs.FS, tagging by content each file that carries no date and can seek. +type folder struct { + fsys fs.FS +} + +// openFile is a regular file of a folder, open to be sent. +type openFile struct { + name string + file fs.File + info fs.FileInfo +} + +// open returns the regular file at name, or false when name names none. +func (f *folder) open(name string) (openFile, bool) { + if !fs.ValidPath(name) { + return openFile{}, false + } + file, err := f.fsys.Open(name) + if err != nil { + return openFile{}, false + } + info, err := file.Stat() + if err != nil || !info.Mode().IsRegular() { + _ = file.Close() + return openFile{}, false + } + return openFile{name: name, file: file, info: info}, true +} + +// send writes open with the type of its name and control as its Cache-Control, answering ranges and checks. +func (f *folder) send(w http.ResponseWriter, r *http.Request, open openFile, control string) { + defer func() { _ = open.file.Close() }() + content, tag, err := sendable(open) + if err != nil { + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + header := w.Header() + if tag != "" { + header.Set("ETag", tag) + } + describe(header, open.name, control) + http.ServeContent(w, ranged(r, content), "", open.info.ModTime(), content) +} + +// describe sets the type of name, control as the Cache-Control, and nosniff. +func describe(header http.Header, name, control string) { + header.Set("Content-Type", typeOf(name)) + header.Set("Cache-Control", control) + header.Set("X-Content-Type-Options", "nosniff") +} + +// sendable returns a seekable reader over open and, when open carries no date and can seek, the tag of its bytes. +func sendable(open openFile) (io.ReadSeeker, string, error) { + seeker, ok := open.file.(io.ReadSeeker) + if !ok { + return &forward{Reader: open.file, size: open.info.Size()}, "", nil + } + if dated(open.info.ModTime()) { + return seeker, "", nil + } + sum := sha256.New() + if _, err := io.Copy(sum, seeker); err != nil { + return nil, "", err + } + return seeker, tagFrom(sum.Sum(nil)), nil +} + +// dated reports whether changed is a date http.ServeContent sends, as neither the zero time nor the Unix epoch is. +func dated(changed time.Time) bool { + return !changed.IsZero() && !changed.Equal(time.Unix(0, 0)) +} + +// tagFrom returns the strong entity tag of a sha256 sum. +func tagFrom(sum []byte) string { + return `"` + hex.EncodeToString(sum[:16]) + `"` +} + +// readable reports whether r asks to read, answering 405 when it does not. +func readable(w http.ResponseWriter, r *http.Request) bool { + if r.Method == http.MethodGet || r.Method == http.MethodHead { + return true + } + w.Header().Set("Allow", "GET, HEAD") + http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + return false +} + +// fileName returns the file name a URL path asks for, or false when one of its segments may not stand in a path. +func fileName(urlPath string) (string, bool) { + name := strings.TrimPrefix(urlPath, "/") + segments := strings.Split(name, "/") + for i, segment := range segments { + if !allowed(segment, i == len(segments)-1) { + return "", false + } + } + return name, true +} + +// allowed reports whether segment may stand in a path, last saying whether it ends the path. +func allowed(segment string, last bool) bool { + switch { + case segment == "": + return last + case strings.HasPrefix(segment, "."): + return segment == ".well-known" + } + return !strings.ContainsRune(segment, '~') && strings.TrimRight(segment, ". ") == segment +} + +// orNotFound returns handler, or http.NotFound when handler is nil. +func orNotFound(handler http.Handler) http.Handler { + if handler == nil { + return http.HandlerFunc(http.NotFound) + } + return handler +} diff --git a/gospa/types.go b/gospa/types.go new file mode 100644 index 0000000..0c0f085 --- /dev/null +++ b/gospa/types.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "path" + "strings" +) + +// types maps a lower case file extension to the Content-Type sent for it. +var types = map[string]string{ + ".html": "text/html; charset=utf-8", + ".htm": "text/html; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".mjs": "text/javascript; charset=utf-8", + ".json": "application/json", + ".map": "application/json", + ".webmanifest": "application/manifest+json", + ".txt": "text/plain; charset=utf-8", + ".xml": "text/xml; charset=utf-8", + ".svg": "image/svg+xml", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".webp": "image/webp", + ".avif": "image/avif", + ".ico": "image/vnd.microsoft.icon", + ".woff": "font/woff", + ".woff2": "font/woff2", + ".ttf": "font/ttf", + ".otf": "font/otf", + ".wasm": "application/wasm", + ".pdf": "application/pdf", + ".zip": "application/zip", + ".mp3": "audio/mpeg", + ".m4a": "audio/mp4", + ".wav": "audio/wav", + ".ogg": "audio/ogg", + ".flac": "audio/flac", + ".mp4": "video/mp4", + ".webm": "video/webm", +} + +// typeOf returns the Content-Type of name by its extension, application/octet-stream when types lacks it. +func typeOf(name string) string { + if kind, ok := types[strings.ToLower(path.Ext(name))]; ok { + return kind + } + return "application/octet-stream" +}