Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

fix(web): the API answers under BASE_PATH

Boris 'B' Kurktchievbc813a61992b
diff --git a/frontend/src/lib/api-base.test.js b/frontend/src/lib/api-base.test.js
index 9944a1a4d..44cfe0c53 100644
--- a/frontend/src/lib/api-base.test.js
+++ b/frontend/src/lib/api-base.test.js
@@ -4,6 +4,10 @@
// answers it. The base is read from where the app is being served.
import { describe, it, expect, vi, afterEach } from 'vitest'
import { appBase, beacon } from './api.js'
+import { readFileSync } from 'node:fs'
+import { spawnSync } from 'node:child_process'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
const at = pathname => appBase({ pathname })
@@ -50,3 +54,173 @@ describe('the "left" beacon of the web app', () => {
expect(beacon('/api/activity', { active: false })).toBe(false)
})
})
+
+// What the web container does with a request, read off web/nginx.conf.template itself.
+// A path, not a URL: under happy-dom `URL` is the DOM's, which node:fs will not take.
+const NGINX = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '../../../web/nginx.conf.template'), 'utf8')
+
+// Each { } block's own directives, its nested blocks left out. Comments go first, and so do
+// ${VAR} placeholders, whose braces are envsubst's, not nginx's.
+function blocksOf(conf) {
+ const out = [], stack = ['']
+ for (const ch of conf.replace(/#.*$/gm, '').replace(/\$\{\w+\}/g, 'X')) {
+ if (ch === '{') stack.push('')
+ else if (ch === '}') out.push(stack.pop())
+ else stack[stack.length - 1] += ch
+ }
+ return out
+}
+
+// An image keeps for 30 days, said by one Cache-Control: the one that can carry `immutable`.
+// `expires` adds a Cache-Control of its own (and an Expires header) beside it.
+describe('the cache lifetime nginx gives an image', () => {
+ it('is said once, by the explicit header, with no expires beside it', () => {
+ expect(NGINX.replace(/#.*$/gm, '')).not.toMatch(/\bexpires\b/)
+ const media = blocksOf(NGINX).filter(b => /\bimmutable\b/.test(b))
+ expect(media.length).toBe(1)
+ expect(media[0]).toMatch(/\badd_header\s+Cache-Control\s+"public, max-age=2592000, immutable"\s*;/)
+ })
+})
+
+// The template as nginx gets it for a given BASE_PATH, comments left out. Its PCRE patterns are
+// valid JavaScript too, apart from \Q…\E (PCRE's quotes for literal text), which `quoted` turns
+// into the same text escaped. Otherwise they run here the way nginx runs them.
+const render = base => NGINX.replace(/#.*$/gm, '').replace(/\$\{BASE_PATH\}/g, base).replace(/\$\{\w+\}/g, 'X')
+const quoted = pattern => pattern.replace(/\\Q([\s\S]*?)(?:\\E|$)/g, (_, text) => text.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&'))
+
+// A proxy that passes its prefix through (BASE_PATH=/gym) has both /api blocks matching
+// /gym/api/..., but the API's routes are /api/... . The prefix used to be forwarded as-is, and
+// every call under the prefix was answered 404. A map takes it off.
+describe('what nginx forwards to the API', () => {
+ const MAP = /\bmap\s+\$request_uri\s+\$(\w+)\s*\{\s*"~([^"]*)"\s+\$(\w+)\s*;\s*\}/
+ // The target the API receives. No match: the map is empty and nginx sends the request's own.
+ function forwarded(base, target) {
+ const [, , pattern, group] = render(base).match(MAP)
+ const m = new RegExp(quoted(pattern)).exec(target)
+ return m ? m.groups[group] : target
+ }
+
+ it('both /api blocks send the mapped target, photo and video uploads included', () => {
+ for (const base of ['', '/gym']) {
+ const conf = render(base)
+ for (const prefix of ['/api/', '/api/media/']) {
+ const block = conf.match(new RegExp('location \\^~ ' + base + prefix + ' \\{([^}]*)\\}'))
+ expect(block).toBeTruthy()
+ expect(block[1]).toMatch(new RegExp('\\bproxy_pass\\s+\\$api_upstream\\$' + conf.match(MAP)[1] + ';'))
+ }
+ }
+ })
+
+ it('no block hands the API the target as it came in', () => {
+ const passes = [...render('/gym').matchAll(/\bproxy_pass\s+([^;]+);/g)].map(m => m[1])
+ .filter(to => to.startsWith('$api_upstream'))
+ expect(passes.length).toBe(2)
+ for (const to of passes) expect(to).toBe('$api_upstream$api_request_uri')
+ })
+
+ it('takes a passed-through prefix off, query and all', () => {
+ expect(forwarded('/gym', '/gym/api/health')).toBe('/api/health')
+ expect(forwarded('/gym', '/gym/api/login/options?x=1')).toBe('/api/login/options?x=1')
+ expect(forwarded('/gym', '/gym//api/health')).toBe('//api/health')
+ expect(forwarded('/gym', '/gym/api/media/missing')).toBe('/api/media/missing')
+ expect(forwarded('/gym', '/gym/api/media/' + 'a'.repeat(64))).toBe('/api/media/' + 'a'.repeat(64))
+ // Not the prefix as sent: forwarded untouched, and the API 404s it as before.
+ expect(forwarded('/gym', '/%67ym/api/health')).toBe('/%67ym/api/health')
+ })
+
+ it('changes nothing at the site root', () => {
+ for (const t of ['/api/health', '/api/health?x=1', '//api/health', '/api/%68ealth', '/api/../api/me'])
+ expect(forwarded('', t)).toBe(t)
+ })
+
+ it('reads BASE_PATH as text, not as a pattern', () => {
+ expect(forwarded('/g.ym', '/g.ym/api/health')).toBe('/api/health')
+ // As a pattern, "." matched the X and /gXym was taken off as if it were the prefix.
+ expect(forwarded('/g.ym', '/gXym/../g.ym/api/health')).toBe('/gXym/../g.ym/api/health')
+ // As a pattern, "g+" never matched the "+" itself, and the prefix was left on.
+ expect(forwarded('/g+ym', '/g+ym/api/health')).toBe('/api/health')
+ expect(forwarded('/a/b', '/a/b/api/x?q=1')).toBe('/api/x?q=1')
+ // A longer first segment is not the prefix.
+ expect(forwarded('/gym', '/gymnasium/../gym/api/health')).toBe('/gymnasium/../gym/api/health')
+ })
+})
+
+// Under BASE_PATH every static location takes the prefix off with a rewrite before it looks on
+// disk. Read as a pattern, BASE_PATH=/g+ym never matched /g+ym itself: /g+ym/ was not found, went
+// to @root, and @root sent it back to /g+ym/, forever; the assets and images 404'd.
+describe('the file nginx looks for under BASE_PATH', () => {
+ const REWRITE = /\brewrite\s+(\S+)\s+(\S+)\s+break\s*;/g
+ // All three rewrites (the app's prefix block and the two cache blocks) give the same answer.
+ function onDisk(base, uri) {
+ const got = [...render(base).matchAll(REWRITE)].map(([, pattern, to]) => {
+ const m = new RegExp(quoted(pattern)).exec(uri)
+ return m ? to.replace(/\$(\d)/g, (_, i) => m[i]) : uri
+ })
+ expect(got.length).toBe(3)
+ expect(new Set(got).size).toBe(1)
+ return got[0]
+ }
+
+ it('takes the prefix off, so the shell at the prefix is found rather than redirected to itself', () => {
+ expect(onDisk('/g+ym', '/g+ym/')).toBe('/')
+ expect(onDisk('/g+ym', '/g+ym/assets/index.js')).toBe('/assets/index.js')
+ expect(onDisk('/g+ym', '/g+ym/icon-180.png')).toBe('/icon-180.png')
+ expect(onDisk('/gym', '/gym/icon-180.png')).toBe('/icon-180.png')
+ expect(onDisk('/a/b', '/a/b/index.html')).toBe('/index.html')
+ })
+
+ it('reads BASE_PATH as text, not as a pattern', () => {
+ expect(onDisk('/g.ym', '/g.ym/assets/index.js')).toBe('/assets/index.js')
+ expect(onDisk('/g.ym', '/gXym/assets/index.js')).toBe('/gXym/assets/index.js')
+ expect(onDisk('/gym', '/gymnasium/index.js')).toBe('/gymnasium/index.js')
+ })
+
+ it('changes nothing at the site root', () => {
+ for (const uri of ['/', '/index.html', '/assets/index.js', '/icon-180.png', '//x.js'])
+ expect(onDisk('', uri)).toBe(uri)
+ })
+})
+
+// nginx's automatic /api -> /api/ redirect was absolute, built from its own scheme and port:
+// http://host:8080/api/, unreachable behind an https proxy. Relative is set once for the whole
+// server, so no location can leave it out.
+describe('the redirects nginx sends', () => {
+ it('carry a relative Location, for every location', () => {
+ const [server] = blocksOf(NGINX).filter(b => /\blisten\b/.test(b))
+ expect(server).toMatch(/\babsolute_redirect\s+off\s*;/)
+ expect(NGINX.replace(/#.*$/gm, '')).not.toMatch(/\babsolute_redirect\s+on\b/)
+ })
+})
+
+// A BASE_PATH of "/gym/" or "gym" renders location prefixes nginx never matches: the container
+// came up and 404'd under the prefix, silently. The web image now refuses to start on one, from a
+// script nginx's entrypoint runs before it renders the template. Run here with sh, as it is there.
+describe('the web container refuses a BASE_PATH it cannot serve', () => {
+ const WEB = join(dirname(fileURLToPath(import.meta.url)), '../../../web')
+ const check = value => {
+ const env = { PATH: process.env.PATH }
+ if (value !== undefined) env.BASE_PATH = value
+ return spawnSync('sh', [join(WEB, '05-check-base-path.sh')], { env, encoding: 'utf8' })
+ }
+
+ it.each([[undefined], [''], ['/gym'], ['/a/b'], ['/g+ym']])('starts with BASE_PATH=%s', value => {
+ const r = check(value)
+ expect(r.status).toBe(0)
+ expect(r.stderr).toBe('')
+ })
+
+ it.each([['/gym/', 'ends with "/"'], ['/', 'ends with "/"'], ['gym', 'does not start with "/"'], ['gym/', 'ends with "/"']])(
+ 'refuses BASE_PATH=%s, and says why', (value, why) => {
+ const r = check(value)
+ expect(r.status).toBe(1)
+ expect(r.stderr).toContain(`BASE_PATH="${value}" ${why}`)
+ expect(r.stderr).toContain('BASE_PATH=/gym')
+ })
+
+ it('is installed where the entrypoint runs it, and executable', () => {
+ // Not executable, the entrypoint skips it with a log line and nginx starts anyway. Its 05
+ // sorts before 20-envsubst-on-templates.sh, nginx's own step that renders the template.
+ const dockerfile = readFileSync(join(WEB, 'Dockerfile'), 'utf8')
+ expect(dockerfile).toMatch(/^COPY --chmod=755 web\/05-check-base-path\.sh \/docker-entrypoint\.d\/$/m)
+ })
+})
diff --git a/web/05-check-base-path.sh b/web/05-check-base-path.sh
new file mode 100755
index 000000000..50cd5c20d
--- /dev/null
+++ b/web/05-check-base-path.sh
@@ -0,0 +1,19 @@
+#!/bin/sh
+# Refuses to start on a BASE_PATH the nginx config cannot serve. The value is pasted into the
+# location prefixes as-is: "/gym/" renders `location ^~ /gym//api/`, "gym" renders
+# `location ^~ gym/api/`, and nginx matches neither, so the container came up and answered 404
+# under the prefix with nothing in the log to say why. Empty (the default) serves the app at
+# the site root.
+#
+# nginx's entrypoint runs /docker-entrypoint.d/*.sh in order and stops at the first that fails,
+# so this one (05) runs before the template is rendered (20) and nginx never starts.
+set -eu
+
+case "${BASE_PATH:-}" in
+ '') exit 0 ;;
+ */) problem='ends with "/"' ;;
+ /*) exit 0 ;;
+ *) problem='does not start with "/"' ;;
+esac
+echo "$0: BASE_PATH=\"$BASE_PATH\" $problem. Set it to the prefix with one leading slash and no trailing one (BASE_PATH=/gym), or leave it empty to serve at the site root." >&2
+exit 1
diff --git a/web/Dockerfile b/web/Dockerfile
index aebb56066..79303ea27 100644
--- a/web/Dockerfile
+++ b/web/Dockerfile
@@ -45,6 +45,10 @@ LABEL maintainer="Duarte Santos https://gitlab.com/DuarteSantos8" \
org.opencontainers.image.created=$BUILD_DATE
COPY web/nginx.conf.template /etc/nginx/templates/default.conf.template
+# Stops the container at start-up on a BASE_PATH the config cannot serve ("/gym/", "gym"), instead
+# of a server that 404s under the prefix. nginx's entrypoint runs these scripts in order; 05 is
+# before the template rendering at 20.
+COPY --chmod=755 web/05-check-base-path.sh /docker-entrypoint.d/
COPY --from=build /app/frontend/dist /usr/share/nginx/html
# exercise media (img/gif) is mounted at runtime from the media volume
diff --git a/web/nginx.conf.template b/web/nginx.conf.template
index 2a0d163f1..f369c1dcb 100644
--- a/web/nginx.conf.template
+++ b/web/nginx.conf.template
@@ -1,9 +1,26 @@
# openGym — standalone web server: serves the static app AND proxies /api to the backend,
# so the whole app lives on ONE origin (required for WebAuthn / passkeys).
+
+# What the two /api blocks below forward: the request's own target, path and query exactly as
+# the client sent it, with BASE_PATH taken off the front. The API's routes are /api/... whatever
+# the browser's prefix is, so a subpath deployment forwarded /gym/api/health as-is and got a 404
+# on every call. With BASE_PATH empty the pattern matches the whole target and nothing changes.
+# A target that reached the block without the prefix spelled out as sent (/%67ym/api/...) maps
+# to nothing, so the target goes through unchanged and the API answers it 404, as it always did.
+# BASE_PATH sits between \Q and \E, PCRE's quotes for literal text: a "." or "+" in it is that
+# character, not part of the pattern.
+map $request_uri $api_request_uri {
+ "~^\Q${BASE_PATH}\E(?<api_request_rest>/.*)$" $api_request_rest;
+}
+
server {
listen ${NGINX_PORT};
root /usr/share/nginx/html;
index index.html;
+ # Every redirect nginx sends (the unknown-path one below, and /api to /api/) carries a
+ # relative Location. An absolute one is built from nginx's own scheme and port,
+ # http://host:8080/api/, which is not an address behind an https reverse proxy.
+ absolute_redirect off;
# Sent on every response below. NOTE: an `add_header` inside a location replaces the whole
# inherited set rather than adding to it, so the two locations further down that set their
@@ -36,7 +53,9 @@ server {
# service address (`kubectl -n kube-system get svc kube-dns`, commonly 10.96.0.10).
resolver ${RESOLVER} valid=10s ipv6=off;
set $api_upstream http://${BACKEND}:${PORT};
- proxy_pass $api_upstream;
+ # With a URI after the host, a proxy_pass built from variables sends that URI verbatim;
+ # an empty one (the map's no-match case) sends the request's own target, as before.
+ proxy_pass $api_upstream$api_request_uri;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
@@ -71,7 +90,9 @@ server {
proxy_send_timeout 300s;
resolver ${RESOLVER} valid=10s ipv6=off;
set $api_upstream http://${BACKEND}:${PORT};
- proxy_pass $api_upstream;
+ # The same mapped target as the block above: under a prefix the upload has to reach the
+ # API's /api/media/... route too.
+ proxy_pass $api_upstream$api_request_uri;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
@@ -95,11 +116,12 @@ server {
# `rewrite ... break` rather than `alias`: try_files inside an aliased prefix location is
# a long-standing nginx trap (it still resolves the untranslated URI). With BASE_PATH
# empty this rewrite is an identity and the block behaves exactly as it always has.
- rewrite ^${BASE_PATH}/(.*)$ /$1 break;
+ # \Q...\E makes BASE_PATH literal text here too, as in the map at the top: read as a
+ # pattern, /g+ym never matched itself and /g+ym/ redirected to /g+ym/ forever.
+ rewrite ^\Q${BASE_PATH}\E/(.*)$ /$1 break;
try_files $uri $uri/ @root;
}
location @root {
- absolute_redirect off;
return 302 ${BASE_PATH}/$is_args$args;
}
@@ -107,7 +129,7 @@ server {
location ~* \.(js|css|json|html)$ {
# A regex location wins over the prefix block above, so it never saw its rewrite and
# looked for the file under the prefix on disk. Same identity-when-empty rewrite here.
- rewrite ^${BASE_PATH}/(.*)$ /$1 break;
+ rewrite ^\Q${BASE_PATH}\E/(.*)$ /$1 break;
add_header Cache-Control "no-cache, must-revalidate";
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
@@ -115,12 +137,13 @@ server {
add_header Content-Security-Policy "frame-ancestors 'none'" always;
}
- # Exercise images/GIFs never change → cache hard
+ # Exercise images/GIFs never change → cache hard.
+ # `expires` would add a second Cache-Control of its own (plus an Expires header) on top of the
+ # explicit one below, so the header is set once, here, where `immutable` can be part of it.
location ~* \.(png|jpg|jpeg|gif|ico|svg|woff|woff2|webp|avif)$ {
# A regex location wins over the prefix block above, so it never saw its rewrite and
# looked for the file under the prefix on disk. Same identity-when-empty rewrite here.
- rewrite ^${BASE_PATH}/(.*)$ /$1 break;
- expires 30d;
+ rewrite ^\Q${BASE_PATH}\E/(.*)$ /$1 break;
add_header Cache-Control "public, max-age=2592000, immutable";
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;