From 802572bae97b51ce56740247fb22b418b60dc579 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 12:28:02 +0000 Subject: [PATCH] feat(pages): build and publish bb sites on push Add a Gotea Pages prototype: a pages branch is checked out with got, built with the vendored bb, swapped atomically into a pages root, and served only on a separate host from an allowlist. A post-receive hook installer wires the flow through Gitea delegate hooks. The CGI pages mode isolates the host and contains paths with realpath. Assisted-by: OpenCode:DeepSeek-V4.1-Flash --- AGENTS.md | 36 ++-- README.md | 51 ++++- cgi/Makefile | 6 +- cgi/gotea.c | 425 ++++++++++++++++++++++++++++++++++++-- cgi/pages/install-hook.sh | 62 ++++++ cgi/pages/post-receive.sh | 44 ++++ cgi/pages/publish.sh | 112 ++++++++++ cgi/tests/run.sh | 76 +++++++ 8 files changed, 783 insertions(+), 29 deletions(-) create mode 100755 cgi/pages/install-hook.sh create mode 100755 cgi/pages/post-receive.sh create mode 100755 cgi/pages/publish.sh diff --git a/AGENTS.md b/AGENTS.md index c6786dacb7..ea9a223e7e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,8 @@ storage. backend task. Do not claim it is finished. - `cgi/gotea-cgi` is the read-only old-browser frontend. It browses bare repositories with `got`; it does not authenticate and has no write path. -- Gotea Pages is planned, not implemented. +- Gotea Pages is a prototype: a `pages` branch is checked out with got, built + with the vendored `bb` at `third_party/bb`, and served from a separate host. ## Architecture rules @@ -71,7 +72,8 @@ storage. make gotea # Go backend binary make build # full Gitea build (frontend needs pnpm/Node) make -C cgi # CGI binary -make -C cgi check # CGI tests +make -C cgi check # CGI + pages tests, including a real bb build +make bb # vendored bb static site generator make fmt # after .go edits make tidy # after go.mod edits make lint # or lint-backend / lint-frontend @@ -117,27 +119,37 @@ make test-migration # after modelmigration changes ## Gotea Pages -- Publish a configured branch and directory (GitHub Pages model), materialized - from the committed tree with got — never from an editor's live working copy. +- A `pages` branch is a bb project. `cgi/pages/publish.sh` checks it out with + `got`, runs `third_party/bb/bb build`, and swaps `dist/` into + `GOTEA_PAGES_ROOT///` atomically. +- The push path is `cgi/pages/install-hook.sh` -> `hooks/post-receive.d/gotea-pages` + -> `publish.sh`. Keep the hook non-fatal by default; `GOTEA_PAGES_STRICT=1` + makes publish failures fail the push. - **Never serve user HTML on the main app origin.** Pages content is attacker-controlled; same-origin means stored XSS against sessions and CSRF - tokens. Use a dedicated pages hostname, send `X-Content-Type-Options: nosniff`, - and resolve paths safely (reject `..` and symlink escapes). + tokens. Serve only when `GOTEA_PAGES_HOST` matches `HTTP_HOST`, with + `X-Content-Type-Options: nosniff` and `realpath` containment under + `GOTEA_PAGES_ROOT//`. - Pages inherit repository visibility: a private repository's site must not be - readable anonymously, even via a guessed URL. -- Config and state belong in `models/` with a `modelmigration/` migration; published - files belong in the storage layer, never `public/` or `custom/public/`. + readable anonymously, even via a guessed URL. The current publisher has no + visibility check, so only public repos may be allowlisted. +- `GOTEA_PAGES_ALLOW` is the serving allowlist; `install-hook.sh` appends the + repo to it. Do not serve a built tree that is not in it. - Publishing must be atomic and idempotent: stage aside, swap in, keep the last - good version on failure. + good version when a build or swap fails. +- bb is vendored under `third_party/bb`; do not shell out to a system bb or edit + the vendored copy in place. Update it from upstream deliberately and keep + `third_party/bb/NOTICE` current. ## Layout - Backend: `routers/` (HTTP), `services/` (logic), `models/` + `modelmigration/` (DB), `modules/` (infrastructure), `templates/`. - Frontend: `web_src/` (Vue + Vite) for the Gitea UI; `cgi/` for the HTML 4.01 - frontend. + frontend; `cgi/pages/` for publish/hook scripts. +- Vendored: `third_party/bb` (MIT static site generator). - Tests: `*_test.go` beside code, `tests/integration/`, `_mock_data/` recordings; - CGI tests in `cgi/tests/`. + CGI and pages tests in `cgi/tests/`. - In `options/locale`, edit only `locale_en-US.json`; other locales are synced automatically. diff --git a/README.md b/README.md index 28e29e8baf..3621f2ec7b 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ This tree is at the bootstrap milestone: | --- | --- | | Go backend | Imported and building as `gotea` (module `gotea.dev`). Still uses `git` internally; the got migration is in progress. | | Legacy frontend | `cgi/gotea-cgi`: read-only browser over `got`, HTML 4.01 Transitional, no JavaScript, CDE palette. | -| Pages | Planned. | +| Pages | Prototype: a `pages` branch is checked out with got, built with vendored `bb`, and served on a separate host. | | Auth and writes | Not yet implemented in the CGI frontend. | ## Build @@ -27,7 +27,8 @@ This tree is at the bootstrap milestone: make gotea # Go backend binary make build # full Gitea build; needs pnpm and Node make -C cgi # C99 CGI binary -make -C cgi check # CGI tests (git is used only to create fixtures) +make -C cgi check # CGI + pages tests (git is used only for fixtures) +make bb # vendored bb static site generator ``` ## Run the CGI @@ -71,11 +72,57 @@ auth layer lands. | `GOTEA_PALETTE` | built-in CDE palette | `key=value` colour file | | `GOTEA_DEBUG` | unset | Show `got` stderr on error pages | | `SCRIPT_NAME` | `/cgi-bin/gotea` | CGI mount point, set by the web server | +| `GOTEA_PAGES_HOST` | unset | Serve pages only when `HTTP_HOST` matches this | +| `GOTEA_PAGES_ROOT` | unset | Root of the built project sites | +| `GOTEA_PAGES_ALLOW` | unset | File listing `owner/repo` sites that may be served | Palette keys: `base`, `light`, `white`, `dark`, `shadow`, `text`, `link`, `visited`, `title_bg`, `title_fg`. Values must be `#rgb` or `#rrggbb`. See `cgi/palettes/cde-default.palette`. +## Pages + +A `pages` branch is a [bb](https://git.hiddenbox.org/lotherk/bb) project. On push, +the post-receive hook checks the branch out with `got`, runs `bb build`, and +atomically swaps the built `dist/` into +`GOTEA_PAGES_ROOT///`. + +```sh +make bb +cgi/pages/install-hook.sh [bb] [branch] +``` + +The installer adds `owner/repo` to the allowlist and writes +`hooks/gotea-pages.env`; Gitea's delegate hook runs `hooks/post-receive.d/*`. +Manual publish: + +```sh +GOTEA_PAGES_ROOT=/var/lib/gotea/pages \ +GOTEA_BB=third_party/bb/bb \ +cgi/pages/publish.sh owner/repo +``` + +Serve the built output on a **separate host**: + +```sh +GOTEA_PAGES_HOST=pages.example.com \ +GOTEA_PAGES_ROOT=/var/lib/gotea/pages \ +GOTEA_PAGES_ALLOW=/etc/gotea/pages.allow \ +./cgi/gotea-cgi +``` + +`GOTEA_PAGES_HOST` must match `HTTP_HOST` exactly; other hosts get 404. Only +allowlisted repositories are served, and the pages host never exposes the main +UI. Keep private repositories out of the allowlist: the publisher has no +visibility check. Optional publisher settings are `GOTEA_PAGES_BRANCH` (default +`pages`), `GOTEA_PAGES_THEME`, `GOTEA_PAGES_SUBDIR`, and `GOTEA_PAGES_STRICT=1` +to fail the push when publishing fails. + +bb is vendored under `third_party/bb` (MIT, upstream commit in +`third_party/bb/NOTICE`), so a checkout builds without an installed bb. +`make bb-check` runs bb's own suite; it currently reports 20 upstream theme +contrast failures (925/945 pass), which do not affect the build path. + ## Design notes - HTML 4.01 Transitional, CSS1, table layout, no JavaScript, no external assets. diff --git a/cgi/Makefile b/cgi/Makefile index a2819138c3..9aaa81c191 100644 --- a/cgi/Makefile +++ b/cgi/Makefile @@ -6,13 +6,17 @@ LDFLAGS ?= PREFIX ?= /usr/local LIBEXECDIR ?= $(PREFIX)/libexec +BB := ../third_party/bb/bb all: gotea-cgi gotea-cgi: gotea.c $(CC) $(CPPFLAGS) $(CFLAGS) -o $@ gotea.c $(LDFLAGS) -check: gotea-cgi +$(BB): + $(MAKE) -C ../third_party/bb + +check: gotea-cgi $(BB) ./tests/run.sh install: gotea-cgi diff --git a/cgi/gotea.c b/cgi/gotea.c index dd9190f2bf..95214ebc08 100644 --- a/cgi/gotea.c +++ b/cgi/gotea.c @@ -9,6 +9,7 @@ * JavaScript, so it works in text and pre-CSS browsers. */ +#define _XOPEN_SOURCE 700 #define _POSIX_C_SOURCE 200809L #include @@ -26,6 +27,7 @@ #include #include #include +#include #include #include @@ -69,6 +71,7 @@ static const char *g_script; static const char *g_root; static const char *g_got; static int g_head_only; +static int g_pages_mode; static const struct palette *g_pal; static void * @@ -782,7 +785,7 @@ static void page_begin(struct buf *b, const char *title) { b_puts(b, "\n\n\n"); + "\"http://www.w3.org/TR/html4/loose.dtd\">\n\n\n"); b_puts(b, "\n"); b_html(b, title); @@ -802,6 +805,18 @@ page_begin(struct buf *b, const char *title) static void page_banner(struct buf *b) { + if (g_pages_mode) { + b_puts(b, "<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" " + "border=\"0\" summary=\"Site banner\" bgcolor=\""); + b_html(b, g_pal->title_bg); + b_puts(b, "\"><tr><td><font color=\""); + b_html(b, g_pal->title_fg); + b_puts(b, "\" size=\"+1\"><b>GOTEA PAGES</b></font> " + "<font color=\""); + b_html(b, g_pal->title_fg); + b_puts(b, "\">project sites</font></td></tr></table>\n"); + return; + } b_puts(b, "<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" " "border=\"0\" summary=\"Site banner\" bgcolor=\""); b_html(b, g_pal->title_bg); @@ -1105,7 +1120,9 @@ page_tree(struct buf *b, const char *repo, const char *repo_path, panel_begin(b, path != NULL && *path != '\0' ? path : repo); b_puts(b, "<p>"); breadcrumb(b, repo, path); - b_puts(b, "</p>\n"); + b_puts(b, "   "); + href_repo(b, "log", repo, NULL); + b_puts(b, "[history]</a></p>\n"); if (out.len == 0) { b_puts(b, "<p><i>empty directory</i></p>\n"); } else { @@ -1201,8 +1218,8 @@ page_tree(struct buf *b, const char *repo, const char *repo_path, } static int -got_cat(const char *repo_path, const char *path, struct buf *out, - struct buf *err) +got_cat_ref(const char *repo_path, const char *ref, const char *path, + struct buf *out, struct buf *err) { char *args[9]; @@ -1211,13 +1228,20 @@ got_cat(const char *repo_path, const char *path, struct buf *out, args[2] = (char *)"-r"; args[3] = (char *)repo_path; args[4] = (char *)"-c"; - args[5] = (char *)"HEAD"; + args[5] = (char *)ref; args[6] = (char *)path; args[7] = NULL; return run_got(args, out, err); } -static void +static int +got_cat(const char *repo_path, const char *path, struct buf *out, + struct buf *err) +{ + return got_cat_ref(repo_path, "HEAD", path, out, err); +} + +static int page_blob(struct buf *b, const char *repo, const char *repo_path, const char *path, struct repo *repos, size_t nrepos) { @@ -1233,7 +1257,7 @@ page_blob(struct buf *b, const char *repo, const char *repo_path, env_or("GOTEA_DEBUG", NULL) ? err.p : NULL); b_free(&out); b_free(&err); - return; + return 0; } if (out.len > 0 && memchr(out.p, '\0', out.len) != NULL) binary = 1; @@ -1245,7 +1269,9 @@ page_blob(struct buf *b, const char *repo, const char *repo_path, breadcrumb(b, repo, path); b_puts(b, "   "); href_repo(b, "raw", repo, path); - b_puts(b, "[raw]</a></p>\n"); + b_puts(b, "[raw]</a> "); + href_repo(b, "log", repo, NULL); + b_puts(b, "[history]</a></p>\n"); if (binary) { b_printf(b, "<p><i>Binary file, %lu bytes.</i></p>\n", (unsigned long)out.len); @@ -1264,6 +1290,7 @@ page_blob(struct buf *b, const char *repo, const char *repo_path, page_end(b); b_free(&out); b_free(&err); + return 1; } static void @@ -1300,7 +1327,9 @@ page_log(struct buf *b, const char *repo, const char *repo_path, b_puts(b, "<p>"); href_repo(b, "tree", repo, NULL); b_html(b, repo); - b_puts(b, "</a> / history</p>\n<pre>"); + b_puts(b, "</a> / history   "); + href_repo(b, "tree", repo, NULL); + b_puts(b, "[files]</a></p>\n<pre>"); line = out.p; while (line != NULL && *line != '\0') { size_t len; @@ -1406,6 +1435,7 @@ reason(int status) case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 500: return "Internal Server Error"; + case 503: return "Service Unavailable"; default: return "Error"; } } @@ -1426,7 +1456,6 @@ send_buf(int status, const char *ctype, struct buf *body, int head_only) static void send_raw(const char *ctype, const struct buf *body, int head_only) { - printf("Status: 200 OK\r\n"); printf("Content-Type: %s\r\n", ctype); printf("Content-Length: %lu\r\n", (unsigned long)body->len); printf("Cache-Control: no-cache\r\n"); @@ -1485,6 +1514,354 @@ page_about(struct buf *b, struct repo *repos, size_t nrepos) page_end(b); } +static const char * +content_type_for(const char *path) +{ + const char *dot = strrchr(path, '.'); + + if (dot == NULL) + return "application/octet-stream"; + if (!strcasecmp(dot, ".html") || !strcasecmp(dot, ".htm")) + return "text/html; charset=UTF-8"; + if (!strcasecmp(dot, ".css")) + return "text/css; charset=UTF-8"; + if (!strcasecmp(dot, ".txt") || !strcasecmp(dot, ".md")) + return "text/plain; charset=UTF-8"; + if (!strcasecmp(dot, ".js")) + return "application/javascript; charset=UTF-8"; + if (!strcasecmp(dot, ".json")) + return "application/json; charset=UTF-8"; + if (!strcasecmp(dot, ".xml")) + return "application/xml; charset=UTF-8"; + if (!strcasecmp(dot, ".svg")) + return "image/svg+xml"; + if (!strcasecmp(dot, ".png")) + return "image/png"; + if (!strcasecmp(dot, ".jpg") || !strcasecmp(dot, ".jpeg")) + return "image/jpeg"; + if (!strcasecmp(dot, ".gif")) + return "image/gif"; + if (!strcasecmp(dot, ".ico")) + return "image/x-icon"; + if (!strcasecmp(dot, ".webp")) + return "image/webp"; + if (!strcasecmp(dot, ".woff2")) + return "font/woff2"; + if (!strcasecmp(dot, ".woff")) + return "font/woff"; + if (!strcasecmp(dot, ".ttf")) + return "font/ttf"; + if (!strcasecmp(dot, ".otf")) + return "font/otf"; + if (!strcasecmp(dot, ".pdf")) + return "application/pdf"; + return "application/octet-stream"; +} + +static int +path_hidden(const char *path) +{ + const char *p = path; + + while (*p) { + if (*p == '.') + return 1; + p = strchr(p, '/'); + if (p == NULL) + break; + p++; + } + return 0; +} + +static int +path_under(const char *path, const char *prefix) +{ + size_t n = strlen(prefix); + + if (strncmp(path, prefix, n) != 0) + return 0; + return path[n] == '\0' || path[n] == '/'; +} + +static int +pages_allowed(const char *repo) +{ + const char *file = getenv("GOTEA_PAGES_ALLOW"); + FILE *f; + char line[PATHBUF]; + + if (file == NULL || *file == '\0') + return 0; + f = fopen(file, "r"); + if (f == NULL) + return 0; + while (fgets(line, sizeof(line), f) != NULL) { + char *p = line, *end; + + while (*p == ' ' || *p == '\t') + p++; + if (*p == '#' || *p == '\n' || *p == '\0') + continue; + end = p + strlen(p); + while (end > p && (end[-1] == '\n' || end[-1] == '\r' || + end[-1] == ' ' || end[-1] == '\t')) + *--end = '\0'; + if (strcmp(p, repo) == 0) { + fclose(f); + return 1; + } + } + fclose(f); + return 0; +} + +static void +pages_index(struct buf *b) +{ + const char *file = getenv("GOTEA_PAGES_ALLOW"); + FILE *f; + char line[PATHBUF]; + + page_begin(b, "Project sites"); + page_banner(b); + panel_begin(b, "Project sites"); + f = file != NULL ? fopen(file, "r") : NULL; + if (f == NULL) { + b_puts(b, "<p><i>No project sites published.</i></p>\n"); + } else { + b_puts(b, "<ul>\n"); + while (fgets(line, sizeof(line), f) != NULL) { + char *p = line, *end; + + while (*p == ' ' || *p == '\t') + p++; + if (*p == '#' || *p == '\n' || *p == '\0') + continue; + end = p + strlen(p); + while (end > p && (end[-1] == '\n' || + end[-1] == '\r' || end[-1] == ' ' || + end[-1] == '\t')) + *--end = '\0'; + if (!valid_repo_name(p)) + continue; + b_puts(b, "<li>"); + b_puts(b, "<a href=\""); + b_url_path(b, g_script); + b_putc(b, '/'); + b_url_path(b, p); + b_puts(b, "/\">"); + b_html(b, p); + b_puts(b, "</a></li>\n"); + } + fclose(f); + b_puts(b, "</ul>\n"); + } + panel_end(b); + page_end(b); +} + +static int +read_file(const char *path, struct buf *out) +{ + int fd; + struct stat st; + ssize_t n; + + fd = open(path, O_RDONLY); + if (fd < 0) + return 0; + if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size < 0 || + (uintmax_t)st.st_size > 16 * 1024 * 1024) { + close(fd); + return 0; + } + b_reserve(out, (size_t)st.st_size); + while (out->len < (size_t)st.st_size) { + n = read(fd, out->p + out->len, + (size_t)st.st_size - out->len); + if (n < 0) { + if (errno == EINTR) + continue; + close(fd); + return 0; + } + if (n == 0) + break; + out->len += (size_t)n; + out->p[out->len] = '\0'; + } + close(fd); + return 1; +} + +static void +send_redirect(const char *repo, const char *rel) +{ + struct buf loc; + + b_init(&loc); + b_url_path(&loc, g_script); + b_putc(&loc, '/'); + b_url_path(&loc, repo); + if (rel != NULL && *rel != '\0') { + b_putc(&loc, '/'); + b_url_path(&loc, rel); + } + b_putc(&loc, '/'); + printf("Status: 301 Moved Permanently\r\n"); + printf("Location: %s\r\n", loc.p); + printf("Content-Type: text/html; charset=UTF-8\r\n"); + printf("\r\n"); + b_free(&loc); +} + +/* + * Pages are built by bb in a separate root and served on their own host, + * never from the main application origin. + */ +static int +serve_pages(void) +{ + const char *root_env = getenv("GOTEA_PAGES_ROOT"); + const char *allow = getenv("GOTEA_PAGES_ALLOW"); + char *decoded = NULL, *repo = NULL, *rel = NULL; + char *root_real = NULL, *repo_real = NULL, *cand = NULL; + char *resolved = NULL; + struct path p; + struct buf body, out; + struct stat st; + int status = 200, trailing; + + g_pages_mode = 1; + b_init(&body); + b_init(&out); + memset(&p, 0, sizeof(p)); + + decoded = url_decode(env_or("PATH_INFO", "/")); + if (decoded == NULL) { + page_error_body(&body, "Bad request", + "Malformed URL escape in PATH_INFO.", NULL); + status = 400; + goto done; + } + if (split_path(&p, decoded) != 0) { + page_error_body(&body, "Bad request", "Invalid path.", NULL); + status = 400; + goto done; + } + if (root_env == NULL || *root_env == '\0' || + allow == NULL || *allow == '\0') { + page_error_body(&body, "Pages unavailable", + "Set GOTEA_PAGES_ROOT and GOTEA_PAGES_ALLOW.", NULL); + status = 503; + goto done; + } + root_real = realpath(root_env, NULL); + if (root_real == NULL) { + page_error_body(&body, "Pages unavailable", + "The pages root does not exist.", NULL); + status = 503; + goto done; + } + if (p.n == 0) { + pages_index(&body); + status = 200; + goto done; + } + if (p.n < 2) { + page_error_body(&body, "Not found", "Unknown project.", NULL); + status = 404; + goto done; + } + + repo = xmalloc(strlen(p.seg[0]) + strlen(p.seg[1]) + 2); + sprintf(repo, "%s/%s", p.seg[0], p.seg[1]); + if (!valid_repo_name(repo) || !pages_allowed(repo)) { + page_error_body(&body, "Not found", + "No published site with that name.", NULL); + status = 404; + goto done; + } + { + char dir[PATHBUF]; + if (snprintf(dir, sizeof(dir), "%s/%s", root_real, repo) >= + (int)sizeof(dir)) { + page_error_body(&body, "Not found", "Path too long.", + NULL); + status = 404; + goto done; + } + repo_real = realpath(dir, NULL); + } + if (repo_real == NULL) { + page_error_body(&body, "Not found", + "That project has not been published yet.", NULL); + status = 404; + goto done; + } + + trailing = decoded[0] != '\0' && + decoded[strlen(decoded) - 1] == '/'; + if (p.n == 2) { + if (!trailing) { + send_redirect(repo, NULL); + status = -1; + goto done; + } + rel = xstrdup("index.html"); + } else { + rel = join_segs(&p, 2); + if (path_hidden(rel)) { + page_error_body(&body, "Not found", "Invalid path.", + NULL); + status = 404; + goto done; + } + } + + cand = xmalloc(strlen(repo_real) + strlen(rel) + 2); + sprintf(cand, "%s/%s", repo_real, rel); + if (stat(cand, &st) == 0 && S_ISDIR(st.st_mode)) { + if (!trailing) { + send_redirect(repo, rel); + status = -1; + goto done; + } + cand = xrealloc(cand, strlen(cand) + 12); + strcat(cand, "/index.html"); + } + resolved = realpath(cand, NULL); + if (resolved == NULL || !path_under(resolved, repo_real)) { + page_error_body(&body, "Not found", "No such page.", NULL); + status = 404; + goto done; + } + if (!read_file(resolved, &out)) { + page_error_body(&body, "Not found", "No such page.", NULL); + status = 404; + goto done; + } + send_raw(content_type_for(resolved), &out, g_head_only); + status = -1; + +done: + if (status >= 0) + send_buf(status, "text/html; charset=UTF-8", &body, + g_head_only); + b_free(&body); + b_free(&out); + free(decoded); + free(repo); + free(rel); + free(root_real); + free(repo_real); + free(cand); + free(resolved); + free(p.raw); + return 0; +} + static int is_action(const char *s) { @@ -1529,6 +1906,7 @@ int main(void) { const char *method, *decoded_env, *palette_file; + const char *pages_host, *http_host; char *decoded = NULL, *repo_path = NULL, *repo_name = NULL; char *path = NULL; struct path p; @@ -1556,6 +1934,23 @@ main(void) return 0; } + pages_host = getenv("GOTEA_PAGES_HOST"); + if (pages_host != NULL && *pages_host != '\0') { + http_host = env_or("HTTP_HOST", env_or("SERVER_NAME", "")); + if (strcasecmp(http_host, pages_host) != 0) { + b_init(&body); + g_pages_mode = 1; + page_error_body(&body, "Unknown host", + "This CGI serves project pages on its own host.", + NULL); + send_buf(404, "text/html; charset=UTF-8", &body, + g_head_only); + b_free(&body); + return 0; + } + return serve_pages(); + } + decoded_env = env_or("PATH_INFO", "/"); decoded = url_decode(decoded_env); if (decoded == NULL) { @@ -1607,8 +2002,9 @@ main(void) if (!page_tree(&body, repo_name, repo_path, path, repos, nrepos)) { /* A file path may be requested as /tree/... */ - page_blob(&body, repo_name, repo_path, path, - repos, nrepos); + if (!page_blob(&body, repo_name, repo_path, + path, repos, nrepos)) + status = 404; } } else if (strcmp(action, "blob") == 0) { path = join_segs(&p, first); @@ -1617,8 +2013,9 @@ main(void) "A file path is required.", NULL); status = 404; } else { - page_blob(&body, repo_name, repo_path, path, - repos, nrepos); + if (!page_blob(&body, repo_name, repo_path, + path, repos, nrepos)) + status = 404; } } else if (strcmp(action, "raw") == 0) { path = join_segs(&p, first); diff --git a/cgi/pages/install-hook.sh b/cgi/pages/install-hook.sh new file mode 100755 index 0000000000..5f22fd7d27 --- /dev/null +++ b/cgi/pages/install-hook.sh @@ -0,0 +1,62 @@ +#!/bin/sh +# Install the pages post-receive hook in a bare repository. +# +# Usage: install-hook.sh <bare-repo> <pages-root> <allow-file> [bb] [branch] +set -eu + +die() { + echo "gotea-pages: $*" >&2 + exit 1 +} + +repo=${1:-} +root=${2:-} +allow=${3:-} +bb=${4:-} +branch=${5:-pages} +[ -n "$repo" ] && [ -n "$root" ] && [ -n "$allow" ] || + die "usage: install-hook.sh <bare-repo> <pages-root> <allow-file> [bb] [branch]" + +repo=$(CDPATH= cd -- "$repo" && pwd) || die "repository not found: $repo" +[ -f "$repo/HEAD" ] && [ -d "$repo/objects" ] || + die "not a bare repository: $repo" + +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +[ -n "$bb" ] || bb="$here/../../third_party/bb/bb" +bb=$(CDPATH= cd -- "$(dirname -- "$bb")" && pwd)/$(basename -- "$bb") +[ -x "$bb" ] || die "bb binary not executable: $bb (run make bb)" + +case "$root" in +*\'*) die "paths containing a single quote are not supported" ;; +esac +case "$allow" in +*\'*) die "paths containing a single quote are not supported" ;; +esac +case "$repo" in +*\'*) die "paths containing a single quote are not supported" ;; +esac + +base=$(basename "$repo") +base=${base%.git} +owner=$(basename "$(dirname "$repo")") +name="$owner/$base" + +mkdir -p "$repo/hooks/post-receive.d" +cp "$here/post-receive.sh" "$repo/hooks/post-receive.d/gotea-pages" +chmod 0755 "$repo/hooks/post-receive.d/gotea-pages" +cat > "$repo/hooks/gotea-pages.env" <<EOF +GOTEA_PAGES_ROOT='$root' +GOTEA_PAGES_PUBLISH='$here/publish.sh' +GOTEA_BB='$bb' +GOTEA_PAGES_BRANCH='$branch' +EOF +chmod 0644 "$repo/hooks/gotea-pages.env" + +mkdir -p "$(dirname "$allow")" +if ! grep -qxF "$name" "$allow" 2>/dev/null; then + echo "$name" >> "$allow" +fi + +echo "installed pages hook for $name" +echo "serve with:" +echo " GOTEA_PAGES_HOST=<pages-host> GOTEA_PAGES_ROOT='$root' GOTEA_PAGES_ALLOW='$allow'" diff --git a/cgi/pages/post-receive.sh b/cgi/pages/post-receive.sh new file mode 100755 index 0000000000..f2f61519d1 --- /dev/null +++ b/cgi/pages/post-receive.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# post-receive hook: rebuild a pages branch with bb after a push. +# +# Install with install-hook.sh; Gitea runs this from +# <repo>/hooks/post-receive.d/gotea-pages. +set -eu + +repo=$(CDPATH= cd -- "${GIT_DIR:-.}" && pwd) +base=$(basename "$repo") +base=${base%.git} +owner=$(basename "$(dirname "$repo")") +name="$owner/$base" + +envfile="$repo/hooks/gotea-pages.env" +if [ -f "$envfile" ]; then + set -a + . "$envfile" + set +a +fi + +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +publish=${GOTEA_PAGES_PUBLISH:-"$here/publish.sh"} +branch=${GOTEA_PAGES_BRANCH:-pages} +status=0 + +if [ -z "${GOTEA_PAGES_ROOT:-}" ]; then + echo "gotea-pages: GOTEA_PAGES_ROOT is not set, skipping $name" >&2 + exit 0 +fi + +while read -r _old new ref; do + [ "$ref" = "refs/heads/$branch" ] || continue + if ! "$publish" "$repo" "$name" "$new"; then + status=1 + fi +done + +if [ "$status" -ne 0 ]; then + echo "gotea-pages: publish failed for $name" >&2 + if [ "${GOTEA_PAGES_STRICT:-0}" = "1" ]; then + exit 1 + fi +fi +exit 0 diff --git a/cgi/pages/publish.sh b/cgi/pages/publish.sh new file mode 100755 index 0000000000..790d081499 --- /dev/null +++ b/cgi/pages/publish.sh @@ -0,0 +1,112 @@ +#!/bin/sh +# Build a pages branch with bb and publish it atomically. +# +# Usage: publish.sh <bare-repo> <owner/repo> <commit> +# Env: GOTEA_PAGES_ROOT (required), GOTEA_BB, GOTEA_PAGES_BRANCH, +# GOTEA_PAGES_SUBDIR, GOTEA_PAGES_THEME +set -eu + +die() { + echo "gotea-pages: $*" >&2 + exit 1 +} + +repo=${1:-} +name=${2:-} +rev=${3:-} +[ -n "$repo" ] && [ -n "$name" ] && [ -n "$rev" ] || + die "usage: publish.sh <bare-repo> <owner/repo> <commit>" + +case "$name" in +*/*/*|/*|*/|*..*) die "invalid repository name: $name" ;; +esac +owner=${name%%/*} +project=${name#*/} +[ "$owner" != "$name" ] && [ -n "$owner" ] && [ -n "$project" ] || + die "repository name must be owner/repo" +for part in "$owner" "$project"; do + case "$part" in + .*|*[!A-Za-z0-9._-]*) die "invalid repository name: $name" ;; + esac +done + +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +bb=${GOTEA_BB:-"$here/../../third_party/bb/bb"} +[ -x "$bb" ] || die "bb binary not executable: $bb (run make bb)" + +[ -n "${GOTEA_PAGES_ROOT:-}" ] || die "GOTEA_PAGES_ROOT is not set" +root=$(CDPATH= cd -- "$GOTEA_PAGES_ROOT" 2>/dev/null && pwd) || + die "pages root does not exist: $GOTEA_PAGES_ROOT" + +branch=${GOTEA_PAGES_BRANCH:-pages} +subdir=${GOTEA_PAGES_SUBDIR:-.} +theme=${GOTEA_PAGES_THEME:-} + +case "$subdir" in +/*|..|../*|*/../*|*/..) die "invalid GOTEA_PAGES_SUBDIR: $subdir" ;; +esac +case "$rev" in +*[!0-9a-fA-F]*) die "invalid commit: $rev" ;; +esac +[ ${#rev} -eq 40 ] || [ ${#rev} -eq 64 ] || die "invalid commit: $rev" + +repo=$(CDPATH= cd -- "$repo" && pwd) || die "repository not found" +base=$(basename "$repo") +base=${base%.git} +parent=$(basename "$(dirname "$repo")") +[ "$parent/$base" = "$name" ] || die "repository path does not match $name" + +tmp="" +lock="" +cleanup() { + [ -n "$tmp" ] && rm -rf "$tmp" + [ -n "$lock" ] && rmdir "$lock" 2>/dev/null || true +} +trap cleanup EXIT HUP INT TERM + +mkdir -p "$root/$owner" +lock="$root/.lock.$owner.$project" +i=0 +while ! mkdir "$lock" 2>/dev/null; do + i=$((i + 1)) + [ "$i" -lt 30 ] || die "another publish is running for $name" + sleep 1 +done + +tmp=$(mktemp -d "$root/.build.XXXXXX") || die "cannot create build directory" +wt="$tmp/wt" + +got checkout -q -b "$branch" "$repo" "$wt" || + die "got checkout of $branch failed" +actual=$(cd "$wt" && got log -l 1 | awk '/^commit /{print $2; exit}') +if [ "$actual" != "$rev" ]; then + (cd "$wt" && got update -q -c "$rev") || + die "got update to $rev failed" +fi + +site="$wt/$subdir" +[ -f "$site/site.conf" ] || die "no site.conf in $subdir" +if [ -n "$theme" ]; then + (cd "$site" && "$bb" build --theme "$theme") || + die "bb build failed for $name" +else + (cd "$site" && "$bb" build) || die "bb build failed for $name" +fi +[ -f "$site/dist/index.html" ] || die "bb produced no dist/index.html" + +stage="$root/.stage.$$" +rm -rf "$stage" +cp -R "$site/dist" "$stage" || die "cannot stage $name" +dest="$root/$owner/$project" +old="$root/.old.$$" +rm -rf "$old" +if [ -e "$dest" ]; then + mv "$dest" "$old" || die "cannot move old $name aside" +fi +if ! mv "$stage" "$dest"; then + [ -e "$old" ] && mv "$old" "$dest" + die "cannot publish $name" +fi +rm -rf "$old" + +echo "gotea-pages: published $name from $rev" diff --git a/cgi/tests/run.sh b/cgi/tests/run.sh index ffcf6305ba..ef0f558081 100755 --- a/cgi/tests/run.sh +++ b/cgi/tests/run.sh @@ -74,6 +74,7 @@ tree=$(run /repo/owner/demo/tree) expect_contains "$tree" 'README.md' "tree: README" expect_contains "$tree" '[src]' "tree: directory link" expect_contains "$tree" '/repo/owner/demo/blob/README.md' "tree: blob link" +expect_contains "$tree" '[history]' "tree: history link" echo "PASS tree" sub=$(run /repo/owner/demo/tree/src) @@ -84,6 +85,7 @@ echo "PASS subtree" blob=$(run /repo/owner/demo/blob/README.md) expect_contains "$blob" '<pre>hello gotea' "blob: content" expect_contains "$blob" '/raw/README.md' "blob: raw link" +expect_contains "$blob" '[history]' "blob: history link" echo "PASS blob" raw=$(run /repo/owner/demo/raw/README.md) @@ -110,6 +112,10 @@ notfound=$(run /repo/nope/tree) expect_contains "$notfound" 'Status: 404' "missing repo: 404" echo "PASS 404" +missingfile=$(run /repo/owner/demo/blob/nope.txt) +expect_contains "$missingfile" 'Status: 404' "missing file: 404" +echo "PASS missing file" + badpath=$(run /repo/../tree) expect_contains "$badpath" 'Status: 400' "traversal: 400" echo "PASS traversal" @@ -129,4 +135,74 @@ flat=$(run /repo/flat/tree) expect_contains "$flat" 'README.md' "flat: tree" echo "PASS flat" +bb="$cgi/../third_party/bb/bb" +"$bb" init "$tmp/bb-src" >/dev/null +cd "$tmp/bb-src" +rm -rf dist build +git init -q -b main +git add . +GIT_AUTHOR_NAME='Test User' GIT_AUTHOR_EMAIL='test@example.com' \ +GIT_COMMITTER_NAME='Test User' GIT_COMMITTER_EMAIL='test@example.com' \ + git commit -qm 'pages site' +git branch pages +git clone -q --bare . "$tmp/repos/owner/site.git" +bb_rev=$(git rev-parse pages) +mkdir -p "$tmp/pages" +printf 'owner/site\n' > "$tmp/allow" + +GOTEA_PAGES_ROOT="$tmp/pages" GOTEA_BB="$bb" \ + "$cgi/pages/publish.sh" "$tmp/repos/owner/site.git" owner/site \ + "$bb_rev" >/dev/null +[ -f "$tmp/pages/owner/site/index.html" ] || + fail "publish: no index.html" +expect_contains "$(cat "$tmp/pages/owner/site/index.html")" \ + '<!DOCTYPE HTML PUBLIC' "publish: bb output" +echo "PASS publish" + +pages_run() { + env -i PATH=/usr/bin:/bin HOME="$tmp" \ + GOTEA_PAGES_HOST=pages.test HTTP_HOST="${2:-pages.test}" \ + GOTEA_PAGES_ROOT="$tmp/pages" GOTEA_PAGES_ALLOW="$tmp/allow" \ + SCRIPT_NAME=/cgi-bin/gotea REQUEST_METHOD=GET PATH_INFO="$1" "$bin" +} + +pages_home=$(pages_run /) +expect_contains "$pages_home" 'GOTEA PAGES' "pages: index banner" +expect_contains "$pages_home" 'owner/site' "pages: allowlisted site" +echo "PASS pages index" + +pages_site=$(pages_run /owner/site/) +expect_contains "$pages_site" 'Content-Type: text/html; charset=UTF-8' \ + "pages: html content type" +expect_contains "$pages_site" '<!DOCTYPE HTML PUBLIC' "pages: site html" +echo "PASS pages site" + +pages_css=$(pages_run /owner/site/css/style.css) +expect_contains "$pages_css" 'Content-Type: text/css; charset=UTF-8' \ + "pages: css content type" +echo "PASS pages css" + +pages_redirect=$(pages_run /owner/site) +expect_contains "$pages_redirect" 'Status: 301 Moved Permanently' \ + "pages: trailing slash redirect" +expect_contains "$pages_redirect" 'Location: /cgi-bin/gotea/owner/site/' \ + "pages: redirect target" +echo "PASS pages redirect" + +pages_unknown=$(pages_run /owner/nope/) +expect_contains "$pages_unknown" 'Status: 404' "pages: unknown site" +echo "PASS pages 404" + +pages_host=$(pages_run / wrong.test) +expect_contains "$pages_host" 'Status: 404' "pages: host isolation" +echo "PASS pages host" + +"$cgi/pages/install-hook.sh" "$tmp/repos/owner/site.git" "$tmp/pages" \ + "$tmp/allow" "$bb" pages >/dev/null +hookout=$(printf '%040d %s refs/heads/pages\n' 0 "$bb_rev" | + env -i PATH=/usr/bin:/bin GIT_DIR="$tmp/repos/owner/site.git" \ + "$tmp/repos/owner/site.git/hooks/post-receive.d/gotea-pages" 2>&1) +expect_contains "$hookout" "published owner/site" "hook: publish output" +echo "PASS post-receive hook" + echo "all gotea-cgi tests passed"