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..2dcaea7 --- /dev/null +++ b/gospa/CHANGELOG.md @@ -0,0 +1,29 @@ +# 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 or folder GoSPA may not read answers 403, and a file that fails to open for another reason answers 500, never the page. +- 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..cc3c9a5 --- /dev/null +++ b/gospa/README.md @@ -0,0 +1,143 @@ +# 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 build read from +disk with `os.DirFS` shows a new build without a restart. An embedded +build, as above, changes only when the program is built again and +restarted. + +### 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. +- A file or folder GoSPA may not read answers 403, and a file that is + there but fails to open for another reason answers 500. Neither gets + the page. +- 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..8bd3dcd --- /dev/null +++ b/gospa/app.go @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "bytes" + "crypto/sha256" + "errors" + "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" + +// hashedNamePattern matches an assets name ending in a dash, 8 letters, digits, dashes or underscores and an extension. +var hashedNamePattern = 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 + metaHTML []byte + hashedFileCacheControl 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) + } + metaHTML, err := metaElements(opts.Meta) + if err != nil { + return nil, err + } + hashedFileCacheControl, err := hashedCacheControl(opts.HashedMaxAge) + if err != nil { + return nil, err + } + return &app{ + folder: folder{fsys: fsys}, + metaHTML: metaHTML, + hashedFileCacheControl: hashedFileCacheControl, + notFound: handlerOrNotFound(opts.NotFound), + }, nil +} + +// hashedCacheControl returns the Cache-Control of a hashed file kept for maxAge, DefaultHashedMaxAge when zero. +func hashedCacheControl(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 !acceptReadMethod(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, the error opening it gave, the not found answer under assets, or else the page. +func (a *app) sendFile(w http.ResponseWriter, r *http.Request, name string) { + file, err := a.folder.open(name) + switch { + case err == nil: + a.folder.send(w, r, file, a.cacheControlOf(name)) + case !errors.Is(err, errNoFile): + sendOpenError(w, err) + case name == assetsDir || strings.HasPrefix(name, assetsDir+"/"): + a.notFound.ServeHTTP(w, r) + default: + a.sendPage(w, r) + } +} + +// cacheControlOf returns the Cache-Control of the file at name. +func (a *app) cacheControlOf(name string) string { + if hashedNamePattern.MatchString(name) { + return a.hashedFileCacheControl + } + 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.metaHTML != nil { + page = pageWithHead(page, a.metaHTML) + } + header := w.Header() + header.Set("ETag", tagOf(page)) + setFileHeaders(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 tagOfSum(sum[:]) +} diff --git a/gospa/app_test.go b/gospa/app_test.go new file mode 100644 index 0000000..694bc1b --- /dev/null +++ b/gospa/app_test.go @@ -0,0 +1,389 @@ +// 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
` + +// newAppBuild returns a build with dates holding the page and each name with its own name as content. +func newAppBuild(names ...string) fstest.MapFS { + build := folderWithDates(names...) + build["index.html"] = &fstest.MapFile{Data: []byte(page), ModTime: buildTime} + return build +} + +// caseInsensitiveFS wraps a folder that opens a name in any case, as on macOS and Windows. +type caseInsensitiveFS struct { + fstest.MapFS +} + +// Open opens name in lower case. +func (c caseInsensitiveFS) 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 fs.FS, opts gospa.AppOptions) http.Handler { + t.Helper() + handler, err := gospa.App(build, opts) + if err != nil { + t.Fatalf("App() = %v", err) + } + return handler +} + +// checkPageAnswer checks that answer sends want as the page, checked on every load and dated by nothing. +func checkPageAnswer(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 !hasNoValue(header, "Last-Modified") { + t.Errorf("GET %s Last-Modified = %q, want none", target, header.Values("Last-Modified")) + } + if tag := header.Get("Etag"); !strongTagPattern.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, newAppBuild("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 := answerTo(handler, http.MethodGet, target) + checkPageAnswer(t, target, answer, page) + } +} + +func TestAppSendsThePageWithItsValuesForIndexHTMLInAnyCase(t *testing.T) { + t.Parallel() + + build := caseInsensitiveFS{MapFS: newAppBuild()} + 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"} { + checkPageAnswer(t, target, answerTo(handler, http.MethodGet, target), want) + } +} + +func TestAppSendsThePageForAnEmptyPath(t *testing.T) { + t.Parallel() + + handler := newApp(t, newAppBuild(), gospa.AppOptions{}) + answer := answerTo(http.StripPrefix("/admin", handler), http.MethodGet, "/admin") + checkPageAnswer(t, "/admin", answer, page) +} + +func TestAppSendsAFileTheBuildWrote(t *testing.T) { + t.Parallel() + + handler := newApp(t, newAppBuild("images/logo.png", "docs/index.html", ".well-known/security.txt"), gospa.AppOptions{}) + for target, contentType := 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 := answerTo(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 != contentType { + t.Errorf("GET %s Content-Type = %q, want %q", target, got, contentType) + } + 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, newAppBuild("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 := answerTo(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 := newAppBuild( + "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 maxAge, hashedCacheControl := range cases { + handler := newApp(t, build, gospa.AppOptions{HashedMaxAge: maxAge}) + for target, want := range map[string]string{ + "/assets/index-DWLUpakq.js": hashedCacheControl, + "/assets/vendor-a_B-9xYz.js": hashedCacheControl, + "/assets/chunks/posts-0ldHa5h1.js": hashedCacheControl, + "/assets/index-DWLUpakq.js.map": hashedCacheControl, + "/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 := answerTo(handler, http.MethodGet, target).Header().Get("Cache-Control"); got != want { + t.Errorf("GET %s with the window %v Cache-Control = %q, want %q", target, maxAge, 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 := newAppBuild() + handler := newApp(t, build, gospa.AppOptions{}) + firstAnswer := answerTo(handler, http.MethodGet, "/posts/42") + build["index.html"] = &fstest.MapFile{Data: []byte(`Rebuilt`), ModTime: buildTime} + secondAnswer := answerTo(handler, http.MethodGet, "/posts/42", "If-None-Match", firstAnswer.Header().Get("Etag")) + checkPageAnswer(t, "/posts/42", secondAnswer, `Rebuilt`) +} + +func TestAppAnswersAServerErrorWhenThePageIsGone(t *testing.T) { + t.Parallel() + + build := newAppBuild() + handler := newApp(t, build, gospa.AppOptions{}) + delete(build, "index.html") + answer := answerTo(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 TestAppAnswersForbiddenAndNeverThePageForAFileItMayNotOpen(t *testing.T) { + t.Parallel() + + deniedNames := []string{"images/logo.png", "assets/index-DWLUpakq.js"} + deniedBuild := permissionDeniedFS{MapFS: newAppBuild(deniedNames...), deniedNames: deniedNames} + handler := newApp(t, deniedBuild, gospa.AppOptions{NotFound: callersNotFound}) + for _, target := range []string{"/images/logo.png", "/assets/index-DWLUpakq.js"} { + if answer := answerTo(handler, http.MethodGet, target); answer.Code != http.StatusForbidden { + t.Errorf("GET %s it may not open = %d %q, want 403", target, answer.Code, answer.Body) + } + } +} + +func TestAppAnswersForbiddenAndNeverThePageForAFileInAFolderItMayNotLookInto(t *testing.T) { + t.Parallel() + + build := lookupDeniedFS{folder: newAppBuild("private/logo.png"), deniedNames: []string{"private/logo.png"}} + handler := newApp(t, build, gospa.AppOptions{}) + if answer := answerTo(handler, http.MethodGet, "/private/logo.png"); answer.Code != http.StatusForbidden { + t.Errorf("GET /private/logo.png in a folder it may not look into = %d %q, want 403", answer.Code, answer.Body) + } +} + +func TestAppAnswersAServerErrorAndNeverThePageForAFileWithoutDetails(t *testing.T) { + t.Parallel() + + handler := newApp(t, unseekableFS{MapFS: newAppBuild("images/logo.png"), doesStatFail: true}, gospa.AppOptions{}) + answer := answerTo(handler, http.MethodGet, "/images/logo.png") + if answer.Code != http.StatusInternalServerError || answer.Body.String() == page { + t.Errorf("GET /images/logo.png without details = %d %q, want 500", answer.Code, answer.Body) + } +} + +func TestAppChecksThePageByATagOfTheBytesSentAndNeverByItsDate(t *testing.T) { + t.Parallel() + + handler := newApp(t, newAppBuild(), gospa.AppOptions{}) + firstAnswer := answerTo(handler, http.MethodGet, "/posts/42") + tag := firstAnswer.Header().Get("Etag") + tagCheckAnswer := answerTo(handler, http.MethodGet, "/posts/42", "If-None-Match", tag) + if tagCheckAnswer.Code != http.StatusNotModified || tagCheckAnswer.Body.Len() != 0 { + t.Errorf("GET /posts/42 with its tag = %d %q, want 304 with no body", tagCheckAnswer.Code, tagCheckAnswer.Body) + } + laterDate := buildTime.Add(time.Hour).Format(http.TimeFormat) + dateCheckAnswer := answerTo(handler, http.MethodGet, "/posts/42", "If-Modified-Since", laterDate) + checkPageAnswer(t, "/posts/42", dateCheckAnswer, page) +} + +func TestAppWritesItsValuesIntoThePage(t *testing.T) { + t.Parallel() + + values := []gospa.Meta{{Name: "api-root", Content: "/api/"}, {Name: "write-timeout", Content: "30"}} + handler := newApp(t, newAppBuild("help.html"), gospa.AppOptions{Meta: values}) + want := `` + + `App
` + for _, target := range []string{"/", "/posts/42", "/index.html"} { + answer := answerTo(handler, http.MethodGet, target) + checkPageAnswer(t, target, answer, want) + } + if got := answerTo(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 TestAppGivesThePageANewTagWhenItsValuesChange(t *testing.T) { + t.Parallel() + + build := newAppBuild() + oldValueHandler := newApp(t, build, gospa.AppOptions{Meta: []gospa.Meta{{Name: "write-timeout", Content: "30"}}}) + tag := answerTo(oldValueHandler, http.MethodGet, "/").Header().Get("Etag") + newValueHandler := newApp(t, build, gospa.AppOptions{Meta: []gospa.Meta{{Name: "write-timeout", Content: "60"}}}) + answer := answerTo(newValueHandler, http.MethodGet, "/", "If-None-Match", tag) + want := strings.Replace(page, "", ``, 1) + checkPageAnswer(t, "/", answer, want) +} + +func TestAppAnswersHeadWithTheHeadersOfThePage(t *testing.T) { + t.Parallel() + + handler := newApp(t, newAppBuild(), gospa.AppOptions{}) + answer := answerTo(handler, http.MethodHead, "/posts/42") + checkPageAnswer(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, newAppBuild("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 := answerTo(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 := newAppBuild(".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 := answerTo(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, newAppBuild(".env"), gospa.AppOptions{NotFound: callersNotFound}) + for _, target := range []string{"/assets/index-0ldHa5h1.js", "/assets/", "/.env", "/posts//42"} { + answer := answerTo(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() + + buildWithAFolderPage := newAppBuild() + buildWithAFolderPage["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: folderWithDates("favicon.svg"), want: "index.html"}, + {name: "a page that is a folder", build: buildWithAFolderPage, 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 = newAppBuild() + } + 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/errors_test.go b/gospa/errors_test.go new file mode 100644 index 0000000..84518ba --- /dev/null +++ b/gospa/errors_test.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa_test + +import ( + "io/fs" + "net/http" + "strconv" + "strings" + "testing" + + "github.com/gopherium/framework/gospa" +) + +func TestFilesAnswersAServerErrorForAFileWithNoDateItCannotRead(t *testing.T) { + t.Parallel() + + handler := gospa.Files(unreadableFS{MapFS: folderWithoutDates("logo.png")}, gospa.FilesOptions{}) + answer := answerTo(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(unseekableFS{MapFS: folderWithDates("logo.png"), doesReadFail: true}, gospa.FilesOptions{}) + answer := answerTo(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 TestFilesAnswersAServerErrorForAFileWithoutDetails(t *testing.T) { + t.Parallel() + + folder := unseekableFS{MapFS: folderWithDates("logo.png"), doesStatFail: true} + handler := gospa.Files(folder, gospa.FilesOptions{NotFound: callersNotFound}) + answer := answerTo(handler, http.MethodGet, "/logo.png") + if answer.Code != http.StatusInternalServerError || strings.Contains(answer.Body.String(), "unreadable") { + t.Errorf("GET /logo.png without details = %d %q, want 500 naming no cause", answer.Code, answer.Body) + } +} + +func TestFilesAnswersForbiddenForAFileItMayNotOpen(t *testing.T) { + t.Parallel() + + folder := permissionDeniedFS{MapFS: folderWithDates("logo.png"), deniedNames: []string{"logo.png"}} + handler := gospa.Files(folder, gospa.FilesOptions{NotFound: callersNotFound}) + answer := answerTo(handler, http.MethodGet, "/logo.png") + if answer.Code != http.StatusForbidden || answer.Body.String() != "Forbidden\n" { + t.Errorf("GET /logo.png it may not open = %d %q, want 403 Forbidden", answer.Code, answer.Body) + } + if got := answer.Header().Get("X-Content-Type-Options"); got != "nosniff" { + t.Errorf("GET /logo.png it may not open X-Content-Type-Options = %q, want nosniff", got) + } +} + +func TestFilesAnswersForbiddenForAFileInAFolderItMayNotLookInto(t *testing.T) { + t.Parallel() + + folder := lookupDeniedFS{ + folder: folderWithDates("private/logo.png", "public/private/logo.png"), + deniedNames: []string{"private/logo.png", "public/private/logo.png"}, + } + subFolder, err := fs.Sub(folder, "public") + if err != nil { + t.Fatalf("Sub() = %v", err) + } + for name, folderToServe := range map[string]fs.FS{"the folder": folder, "a sub folder": subFolder} { + handler := gospa.Files(folderToServe, gospa.FilesOptions{NotFound: callersNotFound}) + if answer := answerTo(handler, http.MethodGet, "/private/logo.png"); answer.Code != http.StatusForbidden { + t.Errorf("GET /private/logo.png from %s = %d %q, want 403", name, answer.Code, answer.Body) + } + } +} 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..1b6e27d --- /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 )?)+)$`, aBuiltAppOrPublicFolderThatHolds) + sc.Step(`^a public folder that holds "([^"]*)" that reads:$`, aPublicFolderThatHoldsAFileThatReads) + sc.Step(`^a built app whose page reads:$`, aBuiltAppWhosePageReads) + sc.Step(`^the build holds no "([^"]*)"$`, theBuildHoldsNoFile) + sc.Step(`^the build writes "([^"]*)"(?: again)? as:$`, theBuildWritesTheFileAs) + sc.Step(`^the window for hashed files is (\d+) hours?$`, theWindowForHashedFilesIsHours) + sc.Step(`^the files were last changed at "([^"]*)"$`, theFilesWereLastChangedAt) + sc.Step(`^the files carry no date, as embedded files do$`, theFilesCarryNoDate) + sc.Step(`^the app carries the value "([^"]*)" set to "([^"]*)"$`, theAppCarriesTheValueSetTo) + sc.Step(`^the app carries the value "([^"]*)" set to:$`, theAppCarriesTheValueSetToTheDocString) + sc.Step(`^the caller answers not found in its own way$`, theCallerAnswersNotFoundInItsOwnWay) +} + +// bindRequestSteps binds the steps in which a browser asks and the program starts. +func bindRequestSteps(sc *godog.ScenarioContext) { + sc.Step(`^a browser asks for "([^"]*)"$`, aBrowserAsksFor) + sc.Step(`^the browser asks for "([^"]*)" again with the (tag|date) it got$`, theBrowserAsksAgainWithTheTagOrDateItGot) + sc.Step(`^a browser asks for "([^"]*)" with the method "([^"]*)"$`, aBrowserAsksForAPathWithTheMethod) + sc.Step(`^a browser asks for "([^"]*)" with the range "([^"]*)"$`, aBrowserAsksForAPathWithTheRange) + sc.Step(`^the program starts again with the value "([^"]*)" set to "([^"]*)"$`, theProgramStartsAgainWithTheValueSetTo) + sc.Step(`^the app is set up$`, theAppIsSetUp) +} + +// bindAnswerSteps binds the steps that check the answer. +func bindAnswerSteps(sc *godog.ScenarioContext) { + sc.Step(`^the answer is the page$`, theAnswerIsThePage) + sc.Step(`^the answer is the file "([^"]*)" with the type "([^"]*)"$`, theAnswerIsTheFileWithTheType) + sc.Step(`^the answer is not found$`, theAnswerIsNotFound) + sc.Step(`^the answer reads:$`, theAnswerReads) + sc.Step(`^the answer holds:$`, theAnswerHolds) + sc.Step(`^the answer carries "([^":]+): ([^"]*)"$`, theAnswerCarriesTheHeader) + sc.Step(`^the answer carries a tag$`, theAnswerCarriesATag) + sc.Step(`^the answer carries no date$`, theAnswerCarriesNoDate) + sc.Step(`^the answer is 304 with no body$`, theAnswerIs304WithNoBody) + sc.Step(`^the answer is 405 allowing "([^"]*)"$`, theAnswerIs405Allowing) + sc.Step(`^the answer is 206 holding the first (\d+) bytes of "([^"]*)"$`, theAnswerIs206HoldingTheFirstBytesOf) + sc.Step(`^the answer carries the length of the page$`, theAnswerCarriesTheLengthOfThePage) + sc.Step(`^the answer has no body$`, theAnswerHasNoBody) + sc.Step(`^setting it up fails naming "([^"]*)"$`, settingItUpFailsNaming) + sc.Step(`^the caller's own answer is sent$`, theCallersOwnAnswerIsSent) +} + +// aBuiltAppOrPublicFolderThatHolds puts each name of quotedList in a folder served as folderKind, index.html as a page. +func aBuiltAppOrPublicFolderThatHolds(ctx context.Context, folderKind, quotedList string) { + w := worldOf(ctx) + w.isApp = folderKind == "built app" + for _, name := range quotedNames(quotedList) { + content := "content of " + name + if name == "index.html" { + content = defaultPage + } + w.write(name, content) + } +} + +// aPublicFolderThatHoldsAFileThatReads puts name in a public folder with the doc string as its content. +func aPublicFolderThatHoldsAFileThatReads(ctx context.Context, name string, docString *godog.DocString) { + worldOf(ctx).write(name, docString.Content) +} + +// aBuiltAppWhosePageReads makes the scenario a built app whose page is the doc string. +func aBuiltAppWhosePageReads(ctx context.Context, docString *godog.DocString) { + w := worldOf(ctx) + w.isApp = true + w.write("index.html", docString.Content) +} + +// theBuildHoldsNoFile takes name out of the build. +func theBuildHoldsNoFile(ctx context.Context, name string) { + delete(worldOf(ctx).folder, name) +} + +// theBuildWritesTheFileAs puts name in the build with the doc string as its content. +func theBuildWritesTheFileAs(ctx context.Context, name string, docString *godog.DocString) { + worldOf(ctx).write(name, docString.Content) +} + +// theWindowForHashedFilesIsHours sets how many hours a browser keeps a hashed file. +func theWindowForHashedFilesIsHours(ctx context.Context, hours int) { + worldOf(ctx).opts.HashedMaxAge = time.Duration(hours) * time.Hour +} + +// theFilesWereLastChangedAt makes every file carry the date modTimeText gives in RFC 3339. +func theFilesWereLastChangedAt(ctx context.Context, modTimeText string) error { + modTime, err := time.Parse(time.RFC3339, modTimeText) + if err != nil { + return err + } + worldOf(ctx).setModTime(modTime) + return nil +} + +// theFilesCarryNoDate makes every file carry no date. +func theFilesCarryNoDate(ctx context.Context) { + worldOf(ctx).setModTime(time.Time{}) +} + +// theAppCarriesTheValueSetTo makes the page carry content under name. +func theAppCarriesTheValueSetTo(ctx context.Context, name, content string) { + worldOf(ctx).setValue(name, content) +} + +// theAppCarriesTheValueSetToTheDocString makes the page carry the doc string under name. +func theAppCarriesTheValueSetToTheDocString(ctx context.Context, name string, docString *godog.DocString) { + worldOf(ctx).setValue(name, docString.Content) +} + +// theCallerAnswersNotFoundInItsOwnWay makes the caller answer not found with its own body. +func theCallerAnswersNotFoundInItsOwnWay(ctx context.Context) { + worldOf(ctx).opts.NotFound = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(callersAnswer)) + }) +} + +// aBrowserAsksFor sends a GET for target. +func aBrowserAsksFor(ctx context.Context, target string) error { + return worldOf(ctx).sendRequest(http.MethodGet, target) +} + +// theBrowserAsksAgainWithTheTagOrDateItGot sends a GET for target that checks the tag or the date the last answer gave. +func theBrowserAsksAgainWithTheTagOrDateItGot(ctx context.Context, target, validator string) error { + w := worldOf(ctx) + if validator == "tag" { + return w.sendRequest(http.MethodGet, target, "If-None-Match", w.tag) + } + return w.sendRequest(http.MethodGet, target, "If-Modified-Since", w.lastModified) +} + +// aBrowserAsksForAPathWithTheMethod sends a request for target with method. +func aBrowserAsksForAPathWithTheMethod(ctx context.Context, target, method string) error { + return worldOf(ctx).sendRequest(method, target) +} + +// aBrowserAsksForAPathWithTheRange sends a GET for the part of target that rangeHeader names. +func aBrowserAsksForAPathWithTheRange(ctx context.Context, target, rangeHeader string) error { + return worldOf(ctx).sendRequest(http.MethodGet, target, "Range", rangeHeader) +} + +// theProgramStartsAgainWithTheValueSetTo sets the value under name to content and sets the app up again. +func theProgramStartsAgainWithTheValueSetTo(ctx context.Context, name, content string) { + w := worldOf(ctx) + w.setValue(name, content) + w.handler = nil +} + +// theAppIsSetUp sets the app up and keeps the error App gives. +func theAppIsSetUp(ctx context.Context) { + worldOf(ctx).setUp() +} + +// theAnswerIsThePage checks that the answer is index.html with every value the app carries written in. +func theAnswerIsThePage(ctx context.Context) error { + w := worldOf(ctx) + if err := checkStatusCode(w, http.StatusOK); err != nil { + return err + } + if contentType := w.answer.Header().Get("Content-Type"); contentType != "text/html; charset=utf-8" { + return fmt.Errorf("the answer to %s is typed %q, not as a page", w.path, contentType) + } + body := w.answer.Body.String() + for _, meta := 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 +} + +// theAnswerIsTheFileWithTheType checks that the answer sends the file name typed as contentType. +func theAnswerIsTheFileWithTheType(ctx context.Context, name, contentType string) error { + w := worldOf(ctx) + if err := checkStatusCode(w, http.StatusOK); err != nil { + return err + } + if got := w.answer.Header().Get("Content-Type"); got != contentType { + return fmt.Errorf("the answer to %s is typed %q, not %q", w.path, got, contentType) + } + 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 +} + +// theAnswerIsNotFound checks that the answer is 404. +func theAnswerIsNotFound(ctx context.Context) error { + return checkStatusCode(worldOf(ctx), http.StatusNotFound) +} + +// theAnswerReads checks that the answer reads the doc string exactly. +func theAnswerReads(ctx context.Context, docString *godog.DocString) error { + w := worldOf(ctx) + if body := w.answer.Body.String(); body != docString.Content { + return fmt.Errorf("the answer to %s reads %q, not %q", w.path, body, docString.Content) + } + return nil +} + +// theAnswerHolds checks that the answer holds the doc string. +func theAnswerHolds(ctx context.Context, docString *godog.DocString) error { + w := worldOf(ctx) + if body := w.answer.Body.String(); !strings.Contains(body, docString.Content) { + return fmt.Errorf("the answer to %s reads %q, which does not hold %q", w.path, body, docString.Content) + } + return nil +} + +// theAnswerCarriesTheHeader checks that the answer carries value under key. +func theAnswerCarriesTheHeader(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 +} + +// theAnswerCarriesATag checks that the answer carries an entity tag. +func theAnswerCarriesATag(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 +} + +// theAnswerCarriesNoDate checks that the answer carries no Last-Modified date. +func theAnswerCarriesNoDate(ctx context.Context) error { + w := worldOf(ctx) + if lastModifiedValues := w.answer.Header().Values("Last-Modified"); len(lastModifiedValues) > 0 { + return fmt.Errorf("the answer to %s carries the date %q", w.path, lastModifiedValues) + } + return nil +} + +// theAnswerIs304WithNoBody checks that the answer is 304 with no body. +func theAnswerIs304WithNoBody(ctx context.Context) error { + w := worldOf(ctx) + if err := checkStatusCode(w, http.StatusNotModified); err != nil { + return err + } + return theAnswerHasNoBody(ctx) +} + +// theAnswerIs405Allowing checks that the answer is 405 and allows methods. +func theAnswerIs405Allowing(ctx context.Context, methods string) error { + w := worldOf(ctx) + if err := checkStatusCode(w, http.StatusMethodNotAllowed); err != nil { + return err + } + return theAnswerCarriesTheHeader(ctx, "Allow", methods) +} + +// theAnswerIs206HoldingTheFirstBytesOf checks that the answer is 206 holding the first byteCount bytes of name. +func theAnswerIs206HoldingTheFirstBytesOf(ctx context.Context, byteCount int, name string) error { + w := worldOf(ctx) + if err := checkStatusCode(w, http.StatusPartialContent); err != nil { + return err + } + if body, want := w.answer.Body.String(), string(w.folder[name].Data[:byteCount]); body != want { + return fmt.Errorf("the answer to %s holds %q, not %q", w.path, body, want) + } + return nil +} + +// theAnswerCarriesTheLengthOfThePage checks that the answer carries the length of the page a GET of its path sends. +func theAnswerCarriesTheLengthOfThePage(ctx context.Context) error { + w := worldOf(ctx) + headAnswer := w.answer + if err := w.sendRequest(http.MethodGet, w.path); err != nil { + return err + } + contentLength, want := headAnswer.Header().Get("Content-Length"), strconv.Itoa(w.answer.Body.Len()) + w.answer = headAnswer + if contentLength != want { + return fmt.Errorf("the answer to HEAD %s carries the length %q, not %s", w.path, contentLength, want) + } + return nil +} + +// theAnswerHasNoBody checks that the answer has no body. +func theAnswerHasNoBody(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 +} + +// settingItUpFailsNaming checks that App failed with an error naming name. +func settingItUpFailsNaming(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 +} + +// theCallersOwnAnswerIsSent checks that the answer is the caller's own not found answer. +func theCallersOwnAnswerIsSent(ctx context.Context) error { + w := worldOf(ctx) + if err := checkStatusCode(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 +} + +// checkStatusCode checks that the answer has the status code. +func checkStatusCode(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..3931f14 --- /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" +) + +// buildTime is the date every file of a scenario was last changed, unless the scenario says otherwise. +var buildTime = 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" + +// quotedNamePattern matches each quoted name of a list such as "a", "b" and "c". +var quotedNamePattern = regexp.MustCompile(`"([^"]*)"`) + +// world is the state of one scenario. +type world struct { + isApp bool + folder fstest.MapFS + modTime time.Time + opts gospa.AppOptions + handler http.Handler + setupErr error + path string + answer *httptest.ResponseRecorder + tag string + lastModified 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 new 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{}, modTime: buildTime}), nil + }) + bindBuildSteps(sc) + bindRequestSteps(sc) + bindAnswerSteps(sc) +} + +// quotedNames returns the quoted names of list in order. +func quotedNames(list string) []string { + var names []string + for _, match := range quotedNamePattern.FindAllStringSubmatch(list, -1) { + names = append(names, match[1]) + } + return names +} + +// write puts name in the folder with content, dated as the scenario's files are. +func (w *world) write(name, content string) { + w.folder[name] = &fstest.MapFile{Data: []byte(content), ModTime: w.modTime} +} + +// setModTime makes every file of the folder carry modTime as its date. +func (w *world) setModTime(modTime time.Time) { + w.modTime = modTime + for _, file := range w.folder { + file.ModTime = modTime + } +} + +// 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.isApp { + w.handler = gospa.Files(w.folder, gospa.FilesOptions{NotFound: w.opts.NotFound}) + return + } + w.handler, w.setupErr = gospa.App(w.folder, w.opts) +} + +// sendRequest sends one request for target with the given header pairs and keeps the answer, its tag and its date. +func (w *world) sendRequest(method, target string, headerPairs ...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(headerPairs); i += 2 { + request.Header.Set(headerPairs[i], headerPairs[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 lastModified := w.answer.Header().Get("Last-Modified"); lastModified != "" { + w.lastModified = lastModified + } + return nil +} diff --git a/gospa/files.go b/gospa/files.go new file mode 100644 index 0000000..f39ce99 --- /dev/null +++ b/gospa/files.go @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "errors" + "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: handlerOrNotFound(opts.NotFound)} +} + +// ServeHTTP sends the file r names, the not found answer when it names none it may send, or the error opening it gave. +func (h *files) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if !acceptReadMethod(w, r) { + return + } + name, ok := fileName(r.URL.Path) + if !ok { + h.notFound.ServeHTTP(w, r) + return + } + file, err := h.folder.open(name) + if errors.Is(err, errNoFile) { + h.notFound.ServeHTTP(w, r) + return + } + if err != nil { + sendOpenError(w, err) + return + } + h.folder.send(w, r, file, noCache) +} diff --git a/gospa/files_test.go b/gospa/files_test.go new file mode 100644 index 0000000..7acbae5 --- /dev/null +++ b/gospa/files_test.go @@ -0,0 +1,524 @@ +// 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(folderWithDates("images/logo.png"), gospa.FilesOptions{}) + answer := answerTo(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 !hasNoValue(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: buildTime}, + "device": {Mode: fs.ModeDevice, ModTime: buildTime}, + "pipe": {Mode: fs.ModeNamedPipe, ModTime: buildTime}, + "socket": {Mode: fs.ModeSocket, ModTime: buildTime}, + } + handler := gospa.Files(folder, gospa.FilesOptions{}) + for _, target := range []string{"/link.png", "/device", "/pipe", "/socket"} { + if answer := answerTo(handler, http.MethodGet, target); answer.Code != http.StatusNotFound { + t.Errorf("GET %s = %d %q, want 404", target, answer.Code, answer.Body) + } + } +} + +func TestFilesSendsOnlyRegularFilesOfAFolderThatOnlyOpensNames(t *testing.T) { + t.Parallel() + + handler := gospa.Files(openOnlyFS{folder: folderWithDates("logo.png", "docs/guide.pdf")}, gospa.FilesOptions{}) + if answer := answerTo(handler, http.MethodGet, "/logo.png"); answer.Code != http.StatusOK { + t.Errorf("GET /logo.png = %d %q, want 200 with the file", answer.Code, answer.Body) + } + for _, target := range []string{"/docs", "/missing.png"} { + if answer := answerTo(handler, http.MethodGet, target); answer.Code != http.StatusNotFound { + t.Errorf("GET %s = %d %q, want 404", target, answer.Code, answer.Body) + } + } +} + +func TestFilesSendsTheFilesAndLinksOfASubFolderAndNothingElse(t *testing.T) { + t.Parallel() + + folder := folderWithDates("public/logo.png", "public/docs/guide.pdf") + folder["public/link.png"] = &fstest.MapFile{Data: []byte("logo.png"), Mode: fs.ModeSymlink, ModTime: buildTime} + subFolder, err := fs.Sub(folder, "public") + if err != nil { + t.Fatalf("Sub() = %v", err) + } + handler := gospa.Files(subFolder, gospa.FilesOptions{}) + for _, target := range []string{"/logo.png", "/link.png"} { + if answer := answerTo(handler, http.MethodGet, target); answer.Code != http.StatusOK { + t.Errorf("GET %s = %d %q, want 200 with the file", target, answer.Code, answer.Body) + } + } + for _, target := range []string{"/docs", "/missing.png"} { + if answer := answerTo(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(trailingSlashFS{MapFS: folderWithDates("logo.png")}, gospa.FilesOptions{}) + if answer := answerTo(handler, http.MethodGet, "/logo.png/"); answer.Code != http.StatusNotFound { + t.Errorf("GET /logo.png/ from a folder that drops a trailing slash = %d %q, want 404", answer.Code, answer.Body) + } +} + +func TestFilesAnswersNotFoundForAPathThatNamesNoFile(t *testing.T) { + t.Parallel() + + handler := gospa.Files(folderWithDates("logo.png", "docs/index.html"), gospa.FilesOptions{}) + for _, target := range []string{"/missing.png", "/", "/docs", "/docs/", "/logo.png/", "/index.html"} { + answer := answerTo(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(folderWithDates("logo.png"), gospa.FilesOptions{}) + answer := answerTo(http.StripPrefix("/media", handler), http.MethodGet, "/media") + if answer.Code != http.StatusNotFound { + t.Errorf("GET /media under /media = %d, want 404", answer.Code) + } +} + +func TestFilesNeverSendsAHiddenFile(t *testing.T) { + t.Parallel() + + folder := folderWithDates( + ".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 := answerTo(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 := folderWithDates( + "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 := answerTo(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() + + folder := folderWithDates(".well-known/security.txt", "site/.well-known/assetlinks.json") + handler := gospa.Files(folder, gospa.FilesOptions{}) + for target, contentType := range map[string]string{ + "/.well-known/security.txt": "text/plain; charset=utf-8", + "/site/.well-known/assetlinks.json": "application/json", + } { + answer := answerTo(handler, http.MethodGet, target) + if answer.Code != http.StatusOK || answer.Header().Get("Content-Type") != contentType { + t.Errorf("GET %s = %d %q, want 200 as %s", target, answer.Code, answer.Header().Get("Content-Type"), contentType) + } + } +} + +func TestFilesAnswersNotFoundForAnEmptySegment(t *testing.T) { + t.Parallel() + + handler := gospa.Files(folderWithDates("logo.png", "docs/guide.pdf"), gospa.FilesOptions{}) + for _, target := range []string{"//logo.png", "/docs//guide.pdf", "//"} { + if answer := answerTo(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(folderWithDates("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 := answerTo(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(folderWithDates("logo.png"), gospa.FilesOptions{}) + answer := answerTo(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() + + contentTypes := 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 contentTypes { + folder[name] = &fstest.MapFile{ + Data: []byte(""), + ModTime: buildTime, + } + } + handler := gospa.Files(folder, gospa.FilesOptions{}) + for name, contentType := range contentTypes { + if got := answerTo(handler, http.MethodGet, "/"+name).Header().Get("Content-Type"); got != contentType { + t.Errorf("GET /%s Content-Type = %q, want %q", name, got, contentType) + } + } +} + +func TestFilesChecksADatedFileByItsDate(t *testing.T) { + t.Parallel() + + handler := gospa.Files(folderWithDates("logo.png"), gospa.FilesOptions{}) + answer := answerTo(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(folderWithoutDates("logo.png"), gospa.FilesOptions{}) + tag := contentTag(t, answerTo(handler, http.MethodGet, "/logo.png")) + tagCheckAnswer := answerTo(handler, http.MethodGet, "/logo.png", "If-None-Match", tag) + if tagCheckAnswer.Code != http.StatusNotModified || tagCheckAnswer.Body.Len() != 0 { + t.Errorf("GET /logo.png with its tag = %d %q, want 304 with no body", tagCheckAnswer.Code, tagCheckAnswer.Body) + } +} + +func TestFilesTagsAFileWithNoDateTheSameEachTimeAndApartFromOtherContent(t *testing.T) { + t.Parallel() + + handler := gospa.Files(folderWithoutDates("logo.png", "icon.png"), gospa.FilesOptions{}) + tag := contentTag(t, answerTo(handler, http.MethodGet, "/logo.png")) + if secondTag := contentTag(t, answerTo(handler, http.MethodGet, "/logo.png")); secondTag != tag { + t.Errorf("GET /logo.png again tagged %q, want %q", secondTag, tag) + } + if otherFileTag := contentTag(t, answerTo(handler, http.MethodGet, "/icon.png")); otherFileTag == tag { + t.Errorf("GET /icon.png tagged %q, the same as another content", otherFileTag) + } +} + +// 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 !strongTagPattern.MatchString(tag) { + t.Fatalf("the answer is tagged %q, want 32 hex digits in quotes", tag) + } + if !hasNoValue(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, answerTo(handler, http.MethodGet, "/robots.txt")) + tagCheckAnswer := answerTo(handler, http.MethodGet, "/robots.txt", "If-None-Match", tag) + if tagCheckAnswer.Code != http.StatusNotModified { + t.Errorf("GET /robots.txt dated at the epoch with its tag = %d %q, want 304", + tagCheckAnswer.Code, tagCheckAnswer.Body) + } +} + +func TestFilesSendsAPartOfAFile(t *testing.T) { + t.Parallel() + + for name, folder := range foldersWithAndWithoutDates("docs/guide.pdf") { + handler := gospa.Files(folder, gospa.FilesOptions{}) + answer := answerTo(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 foldersWithAndWithoutDates("logo.png") { + handler := gospa.Files(unseekableFS{MapFS: folder}, gospa.FilesOptions{}) + for range 2 { + answer := answerTo(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: buildTime}} + cases := []struct { + method, rangeHeader string + maxBytesRead int64 + }{ + {method: http.MethodHead, maxBytesRead: 0}, + {method: http.MethodGet, rangeHeader: "bytes=0-0", maxBytesRead: 1}, + {method: http.MethodGet, rangeHeader: "bytes=0-99", maxBytesRead: 100}, + } + for _, tc := range cases { + bytesRead := &atomic.Int64{} + handler := gospa.Files(unseekableFS{MapFS: folder, bytesRead: bytesRead}, gospa.FilesOptions{}) + answer := answerTo(handler, tc.method, "/clip.mp4", "Range", tc.rangeHeader) + if got := bytesRead.Load(); got > tc.maxBytesRead { + t.Errorf("%s /clip.mp4 %s read %d bytes, want at most %d", tc.method, tc.rangeHeader, got, tc.maxBytesRead) + } + if got := answer.Header().Get("Content-Length"); tc.rangeHeader == "" && 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(unseekableFS{MapFS: folderWithDates("logo.png")}, gospa.FilesOptions{}) + for _, rangeHeader := 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", rangeHeader) + 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", + rangeHeader, answer.Code, answer.Body) + } + if got := request.Header.Get("Range"); got != rangeHeader { + t.Errorf("GET %s of /logo.png left the request Range %q, want it as sent", rangeHeader, got) + } + } +} + +func TestFilesSendsSeveralRangesOfAFileThatCanSeek(t *testing.T) { + t.Parallel() + + handler := gospa.Files(folderWithDates("logo.png"), gospa.FilesOptions{}) + answer := answerTo(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 := folderWithoutDates("logo.png") + handler := gospa.Files(folder, gospa.FilesOptions{}) + oldTag := contentTag(t, answerTo(handler, http.MethodGet, "/logo.png")) + folder["logo.png"].Data = []byte("a new logo") + answer := answerTo(handler, http.MethodGet, "/logo.png", "If-None-Match", oldTag) + 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 newTag := contentTag(t, answer); newTag == oldTag { + t.Errorf("GET the changed /logo.png tagged %q, the tag of its old content", newTag) + } +} + +func TestFilesTagsAFileWithNoDateByTheBytesItSends(t *testing.T) { + t.Parallel() + + handler := gospa.Files(folderWithoutDates("docs/guide.pdf"), gospa.FilesOptions{}) + answer := answerTo(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(unseekableFS{MapFS: folderWithoutDates("logo.png")}, gospa.FilesOptions{}) + answer := answerTo(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 !hasNoValue(answer.Header(), key) { + t.Errorf("GET an undated /logo.png that cannot seek %s = %q, want none", key, answer.Header().Values(key)) + } + } +} + +func TestFilesFollowsTheLinksOfASubFolderOnlyInsideIt(t *testing.T) { + t.Parallel() + + folder := folderWithDates("public/logo.png", "public/docs/guide.pdf", "private.png") + for name, target := range map[string]string{ + "public/link.png": "logo.png", + "public/docs/up.png": "../logo.png", + "public/chain.png": "link.png", + "public/docs-link": "docs", + "public/outside.png": "../private.png", + "public/absolute.png": "/logo.png", + "public/loop.png": "loop.png", + "public/dangling.png": "missing.png", + } { + folder[name] = &fstest.MapFile{Data: []byte(target), Mode: fs.ModeSymlink, ModTime: buildTime} + } + subFolder, err := fs.Sub(folder, "public") + if err != nil { + t.Fatalf("Sub() = %v", err) + } + handler := gospa.Files(subFolder, gospa.FilesOptions{}) + for target, want := range map[string]int{ + "/link.png": http.StatusOK, + "/docs/up.png": http.StatusOK, + "/chain.png": http.StatusOK, + "/docs-link": http.StatusNotFound, + "/outside.png": http.StatusNotFound, + "/absolute.png": http.StatusNotFound, + "/loop.png": http.StatusNotFound, + "/dangling.png": http.StatusNotFound, + } { + if answer := answerTo(handler, http.MethodGet, target); answer.Code != want { + t.Errorf("GET %s = %d %q, want %d", target, answer.Code, answer.Body, want) + } + } +} + +func TestFilesSendsTheCallersNotFound(t *testing.T) { + t.Parallel() + + handler := gospa.Files(folderWithDates("logo.png", "docs/guide.pdf"), gospa.FilesOptions{NotFound: callersNotFound}) + for _, target := range []string{"/missing.png", "/docs/", "/.env", "//logo.png"} { + answer := answerTo(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..031b711 --- /dev/null +++ b/gospa/forward.go @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "io" + "net/http" + "strings" +) + +// forwardOnlyReader reads a file that cannot seek as an io.ReadSeeker that seeks only before its first read. +type forwardOnlyReader struct { + io.Reader + size int64 +} + +// Seek tells the size for a seek to the end, and otherwise skips to offset. +func (f *forwardOnlyReader) Seek(offset int64, whence int) (int64, error) { + if whence == io.SeekEnd { + return f.size, nil + } + return io.CopyN(io.Discard, f.Reader, offset) +} + +// requestToServe returns r, or r without its Range header when content only moves ahead and r asks for several ranges. +func requestToServe(r *http.Request, content io.ReadSeeker) *http.Request { + if _, isForwardOnly := content.(*forwardOnlyReader); !isForwardOnly || !strings.Contains(r.Header.Get("Range"), ",") { + return r + } + requestWithoutRange := r.Clone(r.Context()) + requestWithoutRange.Header.Del("Range") + return requestWithoutRange +} 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..c506a47 --- /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 + isNameGiven := 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 isNameGiven[value.Name] { + return nil, fmt.Errorf("gospa: page value %q is given twice", value.Name) + } + isNameGiven[value.Name] = true + elements = fmt.Appendf(elements, ``, + html.EscapeString(value.Name), html.EscapeString(value.Content)) + } + return elements, nil +} + +// pageWithHead returns page with metaHTML written just after the doctype, html and head tags it opens with. +func pageWithHead(page, metaHTML []byte) []byte { + offset := headOffset(page) + return slices.Concat(page[:offset], metaHTML, page[offset:]) +} + +// 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) + } + tokenizer := html.NewTokenizer(bytes.NewReader(page[start:])) + tokenEnd, insertOffset := start, start + for kind := tokenizer.Next(); kind != html.ErrorToken; kind = tokenizer.Next() { + tokenEnd += len(tokenizer.Raw()) + switch { + case isPageOpeningToken(tokenizer, kind): + insertOffset = tokenEnd + case !isBlankToken(tokenizer, kind): + return insertOffset + } + } + return insertOffset +} + +// isPageOpeningToken reports whether the current token is a closed doctype or an html or head start tag. +func isPageOpeningToken(tokenizer *html.Tokenizer, kind html.TokenType) bool { + switch kind { + case html.DoctypeToken: + return bytes.HasSuffix(tokenizer.Raw(), []byte(">")) + case html.StartTagToken, html.SelfClosingTagToken: + name, _ := tokenizer.TagName() + return string(name) == "html" || string(name) == "head" + } + return false +} + +// isBlankToken reports whether the current token is a comment or text holding only HTML white space. +func isBlankToken(tokenizer *html.Tokenizer, kind html.TokenType) bool { + if kind == html.TextToken { + return len(bytes.Trim(tokenizer.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..b89ac20 --- /dev/null +++ b/gospa/head_test.go @@ -0,0 +1,269 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "slices" + "strings" + "testing" + + "golang.org/x/net/html" + "golang.org/x/net/html/atom" +) + +// apiRootMeta is the meta element the page shapes are written with. +const apiRootMeta = `` + +// pageShapes are pages of every shape, each with the page pageWithHead makes of it. +var pageShapes = []struct { + name, page, want string +}{ + { + name: "a doctype, an html tag and a head tag", + page: `App`, + want: `` + apiRootMeta + `App`, + }, + { + name: "space and a comment between the opening tags", + page: "\n\n\n \n App", + want: "\n\n\n " + apiRootMeta + "\n App", + }, + { + name: "an upper case doctype and head", + page: `App`, + want: `` + apiRootMeta + `App`, + }, + { + name: "no doctype", + page: ``, + want: `` + apiRootMeta + ``, + }, + { + name: "no opening tag before the content", + page: `App`, + want: apiRootMeta + `App`, + }, + { + name: "an empty page", + page: ``, + want: apiRootMeta, + }, + { + name: "a head written inside a title", + page: `<head>`, + want: `` + apiRootMeta + `<head>`, + }, + { + name: "a head written inside a script", + page: ``, + want: `` + apiRootMeta + ``, + }, + { + name: "a head written inside a template", + page: `App`, + want: `` + apiRootMeta + `App`, + }, + { + name: "an html tag with attributes and no head", + page: `App`, + want: `` + apiRootMeta + `App`, + }, + { + name: "a head written inside an attribute", + page: ``, + want: `` + apiRootMeta + ``, + }, + { + name: "a self-closing head", + page: `App`, + want: `` + apiRootMeta + `App`, + }, + { + name: "an empty comment closed at once", + page: ``, + want: `` + apiRootMeta + ``, + }, + { + name: "a processing instruction before the doctype", + page: `App`, + want: `` + apiRootMeta + `App`, + }, + { + name: "a doctype that never closes", + page: `App`, + want: byteOrderMark + `` + apiRootMeta + `App`, + }, + { + name: "a byte order mark alone", + page: byteOrderMark, + want: byteOrderMark + apiRootMeta, + }, + { + name: "a no-break space before the head", + page: " App", + want: "" + apiRootMeta + " App", + }, + { + name: "a vertical tab before the head", + page: "\vApp", + want: "" + apiRootMeta + "\vApp", + }, + { + name: "every HTML white space before the head", + page: " \t\n\r\fApp", + want: " \t\n\r\f" + apiRootMeta + "App", + }, + { + name: "a body as the first tag", + page: `
`, + want: `` + apiRootMeta + `
`, + }, + { + name: "a byte order mark after the doctype", + page: `` + byteOrderMark + `App`, + want: `` + apiRootMeta + byteOrderMark + `App`, + }, +} + +func TestPageWithHeadWritesTheValuesWhereThePageOpens(t *testing.T) { + t.Parallel() + + for _, tc := range pageShapes { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + got := string(pageWithHead([]byte(tc.page), []byte(apiRootMeta))) + if got != tc.want { + t.Errorf("pageWithHead(%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 FuzzPageWithHeadPutsTheValuesInTheHead(f *testing.F) { + for _, page := range []string{ + ``, + `App`, + "\n\n\n \n App", + `App`, + `App`, + `App`, + `` + byteOrderMark + `App`, + ``, + "\x00", + " App", + "\vApp", + `
`, + } { + f.Add(page) + } + fuzzMetaElements := `` + f.Fuzz(func(t *testing.T, page string) { + if len(fuzzValues(t, page)) > 0 { + t.Skip("the page already holds the values") + } + pageWithValues := string(pageWithHead([]byte(page), []byte(fuzzMetaElements))) + if strings.Replace(pageWithValues, fuzzMetaElements, "", 1) != page { + t.Fatalf("pageWithHead(%q) = %q, which is not the page with the values added", page, pageWithValues) + } + if got := fuzzValues(t, pageWithValues); !slices.Equal(got, []string{"1", "2"}) { + t.Errorf("pageWithHead(%q) = %q, whose head holds the values %q, want [1 2]", page, pageWithValues, 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 || attributeValue(node, "name") != "gospa-fuzz" { + continue + } + if node.Parent == nil || node.Parent.DataAtom != atom.Head { + values = append(values, "outside the head") + continue + } + values = append(values, attributeValue(node, "content")) + } + return values +} + +// attributeValue returns the value of the attribute key on node, or an empty string when node has none. +func attributeValue(node *html.Node, key string) string { + for _, attr := range node.Attr { + if attr.Key == key { + return attr.Val + } + } + return "" +} diff --git a/gospa/pipe_test.go b/gospa/pipe_test.go new file mode 100644 index 0000000..6f1afba --- /dev/null +++ b/gospa/pipe_test.go @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || darwin + +package gospa_test + +import ( + "io/fs" + "net/http" + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/gopherium/framework/gospa" +) + +func TestFilesAnswersNotFoundForANamedPipeWithoutWaitingOnIt(t *testing.T) { + t.Parallel() + + for name, folder := range foldersWithANamedPipe(t) { + for _, target := range []string{"/pipe", "/link"} { + statusCodes := make(chan int, 1) + go func() { + statusCodes <- answerTo(gospa.Files(folder, gospa.FilesOptions{}), http.MethodGet, target).Code + }() + select { + case code := <-statusCodes: + if code != http.StatusNotFound { + t.Errorf("GET %s from %s = %d, want 404", target, name, code) + } + case <-time.After(5 * time.Second): + t.Errorf("GET %s from %s still waits on the pipe after 5s, want 404", target, name) + } + } + } +} + +// foldersWithANamedPipe returns a folder holding "pipe" and a link to it as os.DirFS, os.OpenRoot and fs.Sub serve it. +func foldersWithANamedPipe(t *testing.T) map[string]fs.FS { + t.Helper() + dir := t.TempDir() + publicDir := filepath.Join(dir, "public") + if err := os.Mkdir(publicDir, 0o700); err != nil { + t.Fatalf("Mkdir() = %v", err) + } + if err := syscall.Mkfifo(filepath.Join(publicDir, "pipe"), 0o600); err != nil { + t.Fatalf("Mkfifo() = %v", err) + } + if err := os.Symlink("pipe", filepath.Join(publicDir, "link")); err != nil { + t.Fatalf("Symlink() = %v", err) + } + root, err := os.OpenRoot(publicDir) + if err != nil { + t.Fatalf("OpenRoot() = %v", err) + } + t.Cleanup(func() { _ = root.Close() }) + subFolder, err := fs.Sub(os.DirFS(dir), "public") + if err != nil { + t.Fatalf("Sub() = %v", err) + } + return map[string]fs.FS{"os.DirFS": os.DirFS(publicDir), "os.OpenRoot": root.FS(), "fs.Sub": subFolder} +} diff --git a/gospa/request_test.go b/gospa/request_test.go new file mode 100644 index 0000000..4d31e12 --- /dev/null +++ b/gospa/request_test.go @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa_test + +import ( + "errors" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "regexp" + "slices" + "strings" + "sync/atomic" + "testing/fstest" + "time" +) + +// strongTagPattern matches the strong entity tag GoSPA gives, 32 hex digits in quotes. +var strongTagPattern = regexp.MustCompile(`^"[0-9a-f]{32}"$`) + +// buildTime is the date the test files with dates were last changed. +var buildTime = time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC) + +// answerTo returns the answer handler gives to one request for target with the given header pairs. +func answerTo(handler http.Handler, method, target string, headerPairs ...string) *httptest.ResponseRecorder { + request := httptest.NewRequest(method, target, nil) + for i := 0; i+1 < len(headerPairs); i += 2 { + request.Header.Set(headerPairs[i], headerPairs[i+1]) + } + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + return recorder +} + +// folderWithDates returns a folder holding each name with its own name as content, every file changed at buildTime. +func folderWithDates(names ...string) fstest.MapFS { + folder := fstest.MapFS{} + for _, name := range names { + folder[name] = &fstest.MapFile{Data: []byte("content of " + name), ModTime: buildTime} + } + return folder +} + +// folderWithoutDates returns a folder holding each name with its own name as content, as embedded files carry no date. +func folderWithoutDates(names ...string) fstest.MapFS { + folder := fstest.MapFS{} + for _, name := range names { + folder[name] = &fstest.MapFile{Data: []byte("content of " + name)} + } + return folder +} + +// foldersWithAndWithoutDates returns the folder of names both with dates and without, keyed by which. +func foldersWithAndWithoutDates(names ...string) map[string]fstest.MapFS { + return map[string]fstest.MapFS{"dated": folderWithDates(names...), "undated": folderWithoutDates(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 a test file returns when its reads or details fail. +var errUnreadable = errors.New("unreadable") + +// hasNoValue reports whether header carries no value at all under key. +func hasNoValue(header http.Header, key string) bool { + return len(header.Values(key)) == 0 +} + +// unseekableFS wraps a folder whose files cannot seek, and whose reads or details fail when it says so. +type unseekableFS struct { + fstest.MapFS + doesReadFail, doesStatFail bool + bytesRead *atomic.Int64 +} + +// Open opens name in the wrapped folder as a file that cannot seek. +func (u unseekableFS) Open(name string) (fs.File, error) { + file, err := u.MapFS.Open(name) + if err != nil { + return nil, err + } + return unseekableFile{ + file: file, + doesReadFail: u.doesReadFail, + doesStatFail: u.doesStatFail, + bytesRead: u.bytesRead, + }, nil +} + +// unseekableFile is a file that cannot seek, and whose reads or details fail when it says so. +type unseekableFile struct { + file fs.File + doesReadFail, doesStatFail bool + bytesRead *atomic.Int64 +} + +// Stat returns the details of the file, or errUnreadable when its details fail. +func (u unseekableFile) Stat() (fs.FileInfo, error) { + if u.doesStatFail { + return nil, errUnreadable + } + return u.file.Stat() +} + +// Read reads the file and counts the bytes read, or fails with errUnreadable when its reads fail. +func (u unseekableFile) Read(p []byte) (int, error) { + if u.doesReadFail { + return 0, errUnreadable + } + n, err := u.file.Read(p) + if u.bytesRead != nil { + u.bytesRead.Add(int64(n)) + } + return n, err +} + +// Close closes the file. +func (u unseekableFile) Close() error { + return u.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) +} + +// openOnlyFS wraps a folder that opens names and tells no file's details by name, as embed.FS does. +type openOnlyFS struct { + folder fs.FS +} + +// Open opens name in the wrapped folder. +func (o openOnlyFS) Open(name string) (fs.File, error) { + return o.folder.Open(name) +} + +// permissionDeniedFS wraps a folder that tells the details of every file but fails to open each of deniedNames. +type permissionDeniedFS struct { + fstest.MapFS + deniedNames []string +} + +// Open opens name in the wrapped folder, or fails with fs.ErrPermission when name is one of deniedNames. +func (p permissionDeniedFS) Open(name string) (fs.File, error) { + if slices.Contains(p.deniedNames, name) { + return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrPermission} + } + return p.MapFS.Open(name) +} + +// lookupDeniedFS wraps a folder that fails with fs.ErrPermission to tell the details of each of deniedNames. +type lookupDeniedFS struct { + folder fstest.MapFS + deniedNames []string +} + +// Open opens name in the wrapped folder. +func (l lookupDeniedFS) Open(name string) (fs.File, error) { + return l.folder.Open(name) +} + +// Stat returns the details of name, or fails with fs.ErrPermission when name is one of deniedNames. +func (l lookupDeniedFS) Stat(name string) (fs.FileInfo, error) { + if err := l.checkNameAllowed("stat", name); err != nil { + return nil, err + } + return l.folder.Stat(name) +} + +// Lstat returns the details of name without following a link, or fails with fs.ErrPermission when name is denied. +func (l lookupDeniedFS) Lstat(name string) (fs.FileInfo, error) { + if err := l.checkNameAllowed("lstat", name); err != nil { + return nil, err + } + return l.folder.Lstat(name) +} + +// ReadLink returns the target of the link name in the wrapped folder. +func (l lookupDeniedFS) ReadLink(name string) (string, error) { + return l.folder.ReadLink(name) +} + +// checkNameAllowed returns an fs.ErrPermission error for op when name is one of deniedNames. +func (l lookupDeniedFS) checkNameAllowed(op, name string) error { + if slices.Contains(l.deniedNames, name) { + return &fs.PathError{Op: op, Path: name, Err: fs.ErrPermission} + } + return nil +} + +// trailingSlashFS wraps a folder that opens a name with a trailing slash as the name without it. +type trailingSlashFS struct { + fstest.MapFS +} + +// Open opens name without its trailing slash. +func (s trailingSlashFS) Open(name string) (fs.File, error) { + return s.MapFS.Open(strings.TrimSuffix(name, "/")) +} diff --git a/gospa/serve.go b/gospa/serve.go new file mode 100644 index 0000000..462d178 --- /dev/null +++ b/gospa/serve.go @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "io/fs" + "net/http" + "path" + "path/filepath" + "strings" + "time" +) + +// noCache lets a browser keep an answer but check it with the server on every load. +const noCache = "no-cache" + +// maxLinksToFollow is the most links in a row a name may pass through on its way to a file. +const maxLinksToFollow = 40 + +// errNoFile is the error of a name that names no regular file a folder may send. +var errNoFile = errors.New("gospa: no regular file") + +// 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 +} + +// fileToSend is a regular file of a folder, open to be sent. +type fileToSend struct { + name string + handle fs.File + info fs.FileInfo +} + +// open returns the regular file at name, errNoFile when name names none, or the error that kept it from opening. +func (f *folder) open(name string) (fileToSend, error) { + if !fs.ValidPath(name) { + return fileToSend{}, errNoFile + } + if err := checkRegularFile(f.fsys, name); err != nil { + return fileToSend{}, err + } + handle, err := f.fsys.Open(name) + if errors.Is(err, fs.ErrNotExist) { + return fileToSend{}, errNoFile + } + if err != nil { + return fileToSend{}, err + } + info, err := handle.Stat() + if err != nil { + _ = handle.Close() + return fileToSend{}, err + } + if !info.Mode().IsRegular() { + _ = handle.Close() + return fileToSend{}, errNoFile + } + return fileToSend{name: name, handle: handle, info: info}, nil +} + +// checkRegularFile returns nil when name may be a regular file of fsys, asking fsys only in ways that open nothing. +func checkRegularFile(fsys fs.FS, name string) error { + if statFS, ok := fsys.(fs.StatFS); ok { + info, err := statFS.Stat(name) + return checkStatResult(info, err) + } + if linkFS, ok := fsys.(fs.ReadLinkFS); ok { + return checkRegularFileThroughLinks(linkFS, name) + } + return nil +} + +// checkRegularFileThroughLinks returns nil when name is a regular file of linkFS, or links inside linkFS ending at one. +func checkRegularFileThroughLinks(linkFS fs.ReadLinkFS, name string) error { + for range maxLinksToFollow { + info, err := linkFS.Lstat(name) + if err != nil || info.Mode()&fs.ModeSymlink == 0 { + return checkStatResult(info, err) + } + target, err := linkFS.ReadLink(name) + slashTarget := filepath.ToSlash(target) + if err != nil || path.IsAbs(slashTarget) { + return errNoFile + } + name = path.Join(path.Dir(name), slashTarget) + } + return errNoFile +} + +// checkStatResult returns nil for the details of a regular file, err when it is a permission error, or else errNoFile. +func checkStatResult(info fs.FileInfo, err error) error { + if errors.Is(err, fs.ErrPermission) { + return err + } + if err != nil || !info.Mode().IsRegular() { + return errNoFile + } + return nil +} + +// sendOpenError answers 403 when err says a file may not be opened, and 500 for any other err. +func sendOpenError(w http.ResponseWriter, err error) { + statusCode := http.StatusInternalServerError + if errors.Is(err, fs.ErrPermission) { + statusCode = http.StatusForbidden + } + http.Error(w, http.StatusText(statusCode), statusCode) +} + +// send writes file with the type of its name and cacheControl as its Cache-Control, answering ranges and checks. +func (f *folder) send(w http.ResponseWriter, r *http.Request, file fileToSend, cacheControl string) { + defer func() { _ = file.handle.Close() }() + content, tag, err := contentAndTag(file) + if err != nil { + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + header := w.Header() + if tag != "" { + header.Set("ETag", tag) + } + setFileHeaders(header, file.name, cacheControl) + http.ServeContent(w, requestToServe(r, content), "", file.info.ModTime(), content) +} + +// setFileHeaders sets the type of name, cacheControl as the Cache-Control, and nosniff. +func setFileHeaders(header http.Header, name, cacheControl string) { + header.Set("Content-Type", contentTypeOf(name)) + header.Set("Cache-Control", cacheControl) + header.Set("X-Content-Type-Options", "nosniff") +} + +// contentAndTag returns a seekable reader over file and, when file carries no date and can seek, the tag of its bytes. +func contentAndTag(file fileToSend) (io.ReadSeeker, string, error) { + seeker, ok := file.handle.(io.ReadSeeker) + if !ok { + return &forwardOnlyReader{Reader: file.handle, size: file.info.Size()}, "", nil + } + if hasDate(file.info.ModTime()) { + return seeker, "", nil + } + hasher := sha256.New() + if _, err := io.Copy(hasher, seeker); err != nil { + return nil, "", err + } + return seeker, tagOfSum(hasher.Sum(nil)), nil +} + +// hasDate reports whether modTime is a date http.ServeContent sends, as neither the zero time nor the Unix epoch is. +func hasDate(modTime time.Time) bool { + return !modTime.IsZero() && !modTime.Equal(time.Unix(0, 0)) +} + +// tagOfSum returns the strong entity tag of a sha256 sum. +func tagOfSum(sum []byte) string { + return `"` + hex.EncodeToString(sum[:16]) + `"` +} + +// acceptReadMethod reports whether r asks to read, answering 405 when it does not. +func acceptReadMethod(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 !isAllowedSegment(segment, i == len(segments)-1) { + return "", false + } + } + return name, true +} + +// isAllowedSegment reports whether segment may stand in a path, isLast saying whether it ends the path. +func isAllowedSegment(segment string, isLast bool) bool { + switch { + case segment == "": + return isLast + case strings.HasPrefix(segment, "."): + return segment == ".well-known" + } + return !strings.ContainsRune(segment, '~') && strings.TrimRight(segment, ". ") == segment +} + +// handlerOrNotFound returns handler, or http.NotFound when handler is nil. +func handlerOrNotFound(handler http.Handler) http.Handler { + if handler == nil { + return http.HandlerFunc(http.NotFound) + } + return handler +} diff --git a/gospa/serve_test.go b/gospa/serve_test.go new file mode 100644 index 0000000..d77e24f --- /dev/null +++ b/gospa/serve_test.go @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "io/fs" + "testing" + "testing/fstest" +) + +func TestCheckRegularFileThroughLinksStopsAtALinkWithAnAbsoluteTarget(t *testing.T) { + t.Parallel() + + folder := fstest.MapFS{ + "logo.png": {Data: []byte("logo")}, + "absolute.png": {Data: []byte("/logo.png"), Mode: fs.ModeSymlink}, + } + if err := checkRegularFileThroughLinks(folder, "absolute.png"); err != errNoFile { + t.Errorf(`checkRegularFileThroughLinks() = %v for a link to "/logo.png", want errNoFile`, err) + } +} diff --git a/gospa/types.go b/gospa/types.go new file mode 100644 index 0000000..7620f0f --- /dev/null +++ b/gospa/types.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gospa + +import ( + "path" + "strings" +) + +// contentTypes maps a lower case file extension to the Content-Type sent for it. +var contentTypes = 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", +} + +// contentTypeOf returns the Content-Type of name by its extension, application/octet-stream when contentTypes lacks it. +func contentTypeOf(name string) string { + if contentType, ok := contentTypes[strings.ToLower(path.Ext(name))]; ok { + return contentType + } + return "application/octet-stream" +}