Add the website: Go server + Vue SPA in site/, with CI

A standalone container for web_server, shaped like job-tracker: serves
/usaco/ with solved problems public and solving/skipped plus edits
(status, link, notes) for the site admin. Git is the only store: the
server clones adamf/usaco from Gitea, pulls on the push webhook, and
commits edits back. CI builds the image only when site/ changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 21:51:34 +01:00
co-authored by Claude Opus 5.5
parent 440d51caba
commit 6d956f1c76
39 changed files with 6285 additions and 0 deletions
+335
View File
@@ -0,0 +1,335 @@
// Package handlers is the site's REST API: the problem list and pages (public
// for solved problems, everything for the admin), the admin's edits, and the
// Gitea webhook that tells the server to pull.
package handlers
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync/atomic"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/auth"
"adam-french.co.uk/usaco-site/internal/index"
"adam-french.co.uk/usaco-site/internal/repo"
)
// Repo is the part of repo.Repo the handlers use, so tests can fake it.
type Repo interface {
Mutate(ctx context.Context, message string, edit func(dir string) error) error
}
// Server holds the current index and what is needed to change it.
type Server struct {
Repo Repo
Checker auth.Checker
WebhookSecret string
// Pull asks for a sync. It must not block: the webhook answers at once
// and the sync runs in the background.
Pull func()
idx atomic.Pointer[index.Index]
}
// SetIndex swaps in a freshly built index. repo.Repo calls it (through
// Reload) under its lock after every sync and edit.
func (s *Server) SetIndex(idx *index.Index) { s.idx.Store(idx) }
// Reload rebuilds the index from dir. It has repo.Repo's onChange signature.
func (s *Server) Reload(dir string) error {
idx, err := index.Build(dir)
if err != nil {
return err
}
s.SetIndex(idx)
log.Printf("[index] %d problems at %.12s", len(idx.Problems), idx.Head)
return nil
}
// Index is the current snapshot; nil until the first sync has finished.
func (s *Server) Index() *index.Index { return s.idx.Load() }
// Routes registers everything under api.
func (s *Server) Routes(api *gin.RouterGroup) {
admin := api.Group("", auth.Require(s.Checker))
api.GET("/health", s.health)
api.GET("/me", s.me)
api.GET("/problems", s.list)
api.GET("/problems/:name", s.get)
admin.PUT("/problems/:name/meta", s.updateMeta)
admin.POST("/problems/:name/status", s.setStatus)
api.POST("/hooks/gitea", s.webhook)
}
func (s *Server) health(ctx *gin.Context) {
idx := s.Index()
if idx == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"status": "repository not loaded yet"})
return
}
ctx.JSON(http.StatusOK, gin.H{"status": "ok", "head": idx.Head})
}
func (s *Server) me(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"admin": s.isAdmin(ctx)})
}
// visible says whether a problem may be shown to this caller: solved ones
// to anyone, the rest only to the admin.
func visible(p *index.Problem, admin bool) bool {
return admin || p.Status == index.Solved
}
// isAdmin asks the checker. auth.Forward answers a request with no cookies
// (nearly every public visitor) without asking the site backend.
func (s *Server) isAdmin(ctx *gin.Context) bool {
return s.Checker.IsAdmin(ctx.Writer, ctx.Request)
}
func (s *Server) list(ctx *gin.Context) {
idx := s.Index()
if idx == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"})
return
}
admin := s.isAdmin(ctx)
out := []index.Summary{}
for _, p := range idx.Problems {
if visible(p, admin) {
out = append(out, p.Summary)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
ctx.JSON(http.StatusOK, gin.H{"head": idx.Head, "admin": admin, "problems": out})
}
// The CLI's names are slugs. Checking the shape before any lookup keeps
// anything path-like ("..", "a/b") away from the filesystem.
var validName = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`)
// lookup finds a problem the caller may see. A problem the caller may not
// see is a 404 like a missing one, so its existence does not leak.
func (s *Server) lookup(ctx *gin.Context, admin bool) (*index.Problem, bool) {
name := ctx.Param("name")
idx := s.Index()
if idx == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"})
return nil, false
}
if !validName.MatchString(name) {
ctx.JSON(http.StatusNotFound, gin.H{"error": "no such problem"})
return nil, false
}
p, ok := idx.Problems[name]
if !ok || !visible(p, admin) {
ctx.JSON(http.StatusNotFound, gin.H{"error": "no such problem"})
return nil, false
}
return p, true
}
func (s *Server) get(ctx *gin.Context) {
if p, ok := s.lookup(ctx, s.isAdmin(ctx)); ok {
ctx.JSON(http.StatusOK, p)
}
}
// requestError is an edit that cannot be made, with the status to send.
type requestError struct {
status int
msg string
}
func (e *requestError) Error() string { return e.msg }
// mutate runs an edit through the repo and answers with the problem as it
// is afterwards (under its possibly new status).
func (s *Server) mutate(ctx *gin.Context, name, message string, edit func(dir string) error) {
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
defer cancel()
err := s.Repo.Mutate(c, message, edit)
var re *requestError
switch {
case err == nil:
if p, ok := s.Index().Problems[name]; ok {
ctx.JSON(http.StatusOK, p)
} else {
ctx.JSON(http.StatusOK, gin.H{})
}
case errors.As(err, &re):
ctx.JSON(re.status, gin.H{"error": re.msg})
case errors.Is(err, repo.ErrRejected):
ctx.JSON(http.StatusConflict, gin.H{"error": "the repository changed while saving; try again"})
default:
log.Printf("[edit] %s: %v", message, err)
ctx.JSON(http.StatusBadGateway, gin.H{"error": "could not save to git"})
}
}
// findOnDisk locates a problem in the freshly synced clone. Edits decide
// from the disk, not the index, because Mutate may replay them on a newer
// tip than the one the index was built from.
func findOnDisk(dir, name string) (status string, err error) {
for _, st := range index.Statuses {
if info, err := os.Stat(filepath.Join(dir, st, name)); err == nil && info.IsDir() {
return st, nil
}
}
return "", &requestError{http.StatusNotFound, "no such problem"}
}
type metaBody struct {
URL *string `json:"url"`
Notes *string `json:"notes"`
}
const maxNotes = 64 << 10
func (s *Server) updateMeta(ctx *gin.Context) {
p, ok := s.lookup(ctx, true)
if !ok {
return
}
var body metaBody
if err := ctx.ShouldBindJSON(&body); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}
if body.URL != nil {
u := strings.TrimSpace(*body.URL)
if u != "" {
parsed, err := url.Parse(u)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || len(u) > 2048 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an http(s) link"})
return
}
}
body.URL = &u
}
if body.Notes != nil && len(*body.Notes) > maxNotes {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "notes are too long"})
return
}
name := p.Name
s.mutate(ctx, name, "Update "+name, func(dir string) error {
status, err := findOnDisk(dir, name)
if err != nil {
return err
}
pdir := filepath.Join(dir, status, name)
if body.URL != nil {
// Same format `usaco new --url` writes: the link and a newline.
if err := writeOrRemove(filepath.Join(pdir, ".url"), *body.URL); err != nil {
return err
}
}
if body.Notes != nil {
if err := writeOrRemove(filepath.Join(pdir, "notes.md"), *body.Notes); err != nil {
return err
}
}
return nil
})
}
// writeOrRemove writes content plus a trailing newline, or removes the file
// when content is blank, so clearing a field leaves no empty file behind.
func writeOrRemove(path, content string) error {
content = strings.TrimRight(content, " \t\r\n")
if content == "" {
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
return os.WriteFile(path, []byte(content+"\n"), 0o644)
}
type statusBody struct {
To string `json:"to"`
}
// The commit subjects match the CLI's: `usaco done` commits "Solve <name>".
var statusVerb = map[string]string{
index.Solved: "Solve",
index.Skipped: "Skip",
index.Solving: "Reopen",
}
func (s *Server) setStatus(ctx *gin.Context) {
p, ok := s.lookup(ctx, true)
if !ok {
return
}
var body statusBody
if err := ctx.ShouldBindJSON(&body); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}
verb, ok := statusVerb[body.To]
if !ok {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "to must be solving, solved or skipped"})
return
}
name := p.Name
s.mutate(ctx, name, verb+" "+name, func(dir string) error {
from, err := findOnDisk(dir, name)
if err != nil {
return err
}
if from == body.To {
return nil
}
if err := os.MkdirAll(filepath.Join(dir, body.To), 0o755); err != nil {
return err
}
return os.Rename(filepath.Join(dir, from, name), filepath.Join(dir, body.To, name))
})
}
// webhook accepts Gitea's push hook. Gitea signs the body with the shared
// secret (HMAC-SHA256, hex, in X-Gitea-Signature). The body itself is not
// read beyond that: any push to the repo is a reason to pull.
func (s *Server) webhook(ctx *gin.Context) {
if s.WebhookSecret == "" {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "webhook not configured"})
return
}
body, err := io.ReadAll(io.LimitReader(ctx.Request.Body, 5<<20))
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unreadable body"})
return
}
if !validSignature(s.WebhookSecret, body, ctx.GetHeader("X-Gitea-Signature")) {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "bad signature"})
return
}
s.Pull()
ctx.JSON(http.StatusAccepted, gin.H{"status": "pull queued"})
}
func validSignature(secret string, body []byte, sig string) bool {
got, err := hex.DecodeString(strings.TrimPrefix(sig, "sha256="))
if err != nil || len(got) == 0 {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
return hmac.Equal(got, mac.Sum(nil))
}
+210
View File
@@ -0,0 +1,210 @@
package handlers
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
// cookieChecker: the admin is whoever sends the cookie "admin=1".
type cookieChecker struct{}
func (cookieChecker) IsAdmin(_ http.ResponseWriter, r *http.Request) bool {
c, err := r.Cookie("admin")
return err == nil && c.Value == "1"
}
// dirRepo applies edits straight to a work tree and reindexes, standing in
// for repo.Repo without a remote.
type dirRepo struct {
dir string
srv *Server
msg []string
}
func (d *dirRepo) Mutate(_ context.Context, message string, edit func(string) error) error {
if err := edit(d.dir); err != nil {
return err
}
d.msg = append(d.msg, message)
return d.srv.Reload(d.dir)
}
func setup(t *testing.T) (*gin.Engine, *dirRepo, *int) {
t.Helper()
gin.SetMode(gin.TestMode)
dir := t.TempDir()
for _, p := range []string{"solved/moocast/main.cpp", "solving/watermelon/main.cpp"} {
os.MkdirAll(filepath.Join(dir, filepath.Dir(p)), 0o755)
os.WriteFile(filepath.Join(dir, p), []byte("int main() {}\n"), 0o644)
}
for _, args := range [][]string{{"init", "--quiet"}, {"add", "-A"}, {"-c", "user.name=t", "-c", "user.email=t@t", "commit", "--quiet", "-m", "init"}} {
cmd := exec.Command("git", args...)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
pulls := 0
srv := &Server{Checker: cookieChecker{}, WebhookSecret: "s3cret", Pull: func() { pulls++ }}
repo := &dirRepo{dir: dir, srv: srv}
srv.Repo = repo
if err := srv.Reload(dir); err != nil {
t.Fatal(err)
}
r := gin.New()
srv.Routes(r.Group("/usaco/api"))
return r, repo, &pulls
}
func do(r *gin.Engine, method, path, body string, admin bool, headers ...string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
if admin {
req.Header.Set("Cookie", "admin=1")
}
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
return rec
}
func names(t *testing.T, rec *httptest.ResponseRecorder) []string {
t.Helper()
var body struct {
Problems []struct{ Name string } `json:"problems"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
var out []string
for _, p := range body.Problems {
out = append(out, p.Name)
}
return out
}
func TestVisibility(t *testing.T) {
r, _, _ := setup(t)
if got := names(t, do(r, "GET", "/usaco/api/problems", "", false)); len(got) != 1 || got[0] != "moocast" {
t.Fatalf("public list = %v, want only the solved problem", got)
}
if got := names(t, do(r, "GET", "/usaco/api/problems", "", true)); len(got) != 2 {
t.Fatalf("admin list = %v, want both", got)
}
if rec := do(r, "GET", "/usaco/api/problems/watermelon", "", false); rec.Code != 404 {
t.Fatalf("public GET of an unsolved problem = %d, want 404", rec.Code)
}
if rec := do(r, "GET", "/usaco/api/problems/watermelon", "", true); rec.Code != 200 {
t.Fatalf("admin GET of an unsolved problem = %d, want 200", rec.Code)
}
if rec := do(r, "GET", "/usaco/api/problems/moocast", "", false); rec.Code != 200 {
t.Fatalf("public GET of a solved problem = %d, want 200", rec.Code)
}
}
func TestNameValidation(t *testing.T) {
r, _, _ := setup(t)
for _, name := range []string{"..", ".git", "Moocast", "%2e%2e", "a%2Fb"} {
if rec := do(r, "GET", "/usaco/api/problems/"+name, "", true); rec.Code != 404 {
t.Errorf("GET %q = %d, want 404", name, rec.Code)
}
}
}
func TestWritesNeedAdmin(t *testing.T) {
r, repo, _ := setup(t)
if rec := do(r, "POST", "/usaco/api/problems/moocast/status", `{"to":"skipped"}`, false); rec.Code != 401 {
t.Fatalf("anonymous status change = %d, want 401", rec.Code)
}
if rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"notes":"x"}`, false); rec.Code != 401 {
t.Fatalf("anonymous meta edit = %d, want 401", rec.Code)
}
if len(repo.msg) != 0 {
t.Fatalf("refused writes still committed %v", repo.msg)
}
}
func TestStatusChange(t *testing.T) {
r, repo, _ := setup(t)
rec := do(r, "POST", "/usaco/api/problems/watermelon/status", `{"to":"solved"}`, true)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"status":"solved"`) {
t.Fatalf("solve = %d %s", rec.Code, rec.Body)
}
if _, err := os.Stat(filepath.Join(repo.dir, "solved", "watermelon", "main.cpp")); err != nil {
t.Fatal("directory was not moved")
}
if len(repo.msg) != 1 || repo.msg[0] != "Solve watermelon" {
t.Fatalf("commit messages = %v, want the CLI's \"Solve watermelon\"", repo.msg)
}
if rec := do(r, "POST", "/usaco/api/problems/watermelon/status", `{"to":"elsewhere"}`, true); rec.Code != 400 {
t.Fatalf("bad status = %d, want 400", rec.Code)
}
}
func TestMetaEdit(t *testing.T) {
r, repo, _ := setup(t)
pdir := filepath.Join(repo.dir, "solved", "moocast")
rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"url":" https://usaco.org/x ","notes":"# idea\n"}`, true)
if rec.Code != 200 {
t.Fatalf("meta = %d %s", rec.Code, rec.Body)
}
if b, _ := os.ReadFile(filepath.Join(pdir, ".url")); string(b) != "https://usaco.org/x\n" {
t.Fatalf(".url = %q", b)
}
if b, _ := os.ReadFile(filepath.Join(pdir, "notes.md")); string(b) != "# idea\n" {
t.Fatalf("notes.md = %q", b)
}
// Clearing a field removes its file; leaving one out leaves it alone.
do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"notes":""}`, true)
if _, err := os.Stat(filepath.Join(pdir, "notes.md")); err == nil {
t.Fatal("clearing notes left notes.md")
}
if _, err := os.Stat(filepath.Join(pdir, ".url")); err != nil {
t.Fatal("an edit without url removed .url")
}
if rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"url":"javascript:alert(1)"}`, true); rec.Code != 400 {
t.Fatalf("javascript: url = %d, want 400", rec.Code)
}
}
func TestWebhookSignature(t *testing.T) {
r, _, pulls := setup(t)
body := `{"ref":"refs/heads/main"}`
mac := hmac.New(sha256.New, []byte("s3cret"))
mac.Write([]byte(body))
good := hex.EncodeToString(mac.Sum(nil))
if rec := do(r, "POST", "/usaco/api/hooks/gitea", body, false, "X-Gitea-Signature", "00"+good[2:]); rec.Code != 401 {
t.Fatalf("bad signature = %d, want 401", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/hooks/gitea", body, false); rec.Code != 401 {
t.Fatalf("no signature = %d, want 401", rec.Code)
}
if *pulls != 0 {
t.Fatal("an unsigned hook triggered a pull")
}
if rec := do(r, "POST", "/usaco/api/hooks/gitea", body, false, "X-Gitea-Signature", good); rec.Code != 202 {
t.Fatalf("good signature = %d, want 202", rec.Code)
}
if *pulls != 1 {
t.Fatalf("pulls = %d, want 1", *pulls)
}
}
+65
View File
@@ -0,0 +1,65 @@
package handlers
import (
"net/http"
"os"
"path"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
)
// SPA serves the built Vue app from dir for every GET under base that no API
// route claimed. It is installed as gin's NoRoute handler rather than as a
// base+"/*path" route because gin will not let a catch-all sit beside the
// /api routes at the same level.
//
// History-mode routing means a path such as /usaco/p/moocast is a page of the app,
// not a file, so anything that is not a file in dir gets index.html — except
// under /api/ and /assets/, where a miss is a real 404: an API typo should
// not come back as a page of HTML, and neither should a stale asset hash.
//
// Caching: Vite fingerprints everything under assets/, so those are cached
// for a year; index.html is never cached, so a deploy is picked up on the
// next load.
func SPA(dir, base string) gin.HandlerFunc {
return func(ctx *gin.Context) {
p := ctx.Request.URL.Path
if ctx.Request.Method != http.MethodGet && ctx.Request.Method != http.MethodHead {
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
if p == base {
ctx.Redirect(http.StatusMovedPermanently, base+"/")
return
}
rel, ok := strings.CutPrefix(p, base+"/")
if !ok || strings.HasPrefix(rel, "api/") {
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
// path.Clean on a rooted path cannot climb above the root, so the
// result always stays inside dir.
rel = strings.TrimPrefix(path.Clean("/"+rel), "/")
if rel != "" {
file := filepath.Join(dir, filepath.FromSlash(rel))
if info, err := os.Stat(file); err == nil && !info.IsDir() {
if strings.HasPrefix(rel, "assets/") {
ctx.Header("Cache-Control", "public, max-age=31536000, immutable")
} else {
ctx.Header("Cache-Control", "no-cache")
}
ctx.File(file)
return
}
if strings.HasPrefix(rel, "assets/") {
ctx.Status(http.StatusNotFound)
return
}
}
ctx.Header("Cache-Control", "no-cache")
ctx.File(filepath.Join(dir, "index.html"))
}
}
+61
View File
@@ -0,0 +1,61 @@
package handlers
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
)
func TestSPA(t *testing.T) {
gin.SetMode(gin.TestMode)
dir := t.TempDir()
os.MkdirAll(filepath.Join(dir, "assets"), 0o755)
os.WriteFile(filepath.Join(dir, "index.html"), []byte("index"), 0o644)
os.WriteFile(filepath.Join(dir, "assets", "app-1a2b.js"), []byte("js"), 0o644)
os.WriteFile(filepath.Join(dir, "robots.txt"), []byte("robots"), 0o644)
// Outside dir: must never be reachable.
os.WriteFile(filepath.Join(filepath.Dir(dir), "secret"), []byte("secret"), 0o644)
r := gin.New()
r.GET("/usaco/api/health", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
r.NoRoute(SPA(dir, "/usaco"))
cases := []struct {
method, path string
code int
body string
cache string
}{
{"GET", "/usaco/", 200, "index", "no-cache"},
{"GET", "/usaco/p/moocast", 200, "index", "no-cache"},
{"GET", "/usaco/stats/anything", 200, "index", "no-cache"},
{"GET", "/usaco/assets/app-1a2b.js", 200, "js", "public, max-age=31536000, immutable"},
{"GET", "/usaco/robots.txt", 200, "robots", "no-cache"},
{"GET", "/usaco/api/health", 200, "ok", ""},
{"GET", "/usaco/api/nope", 404, `{"error":"not found"}`, ""},
{"GET", "/usaco/assets/gone.js", 404, "404 page not found", ""},
// net/http refuses a path that climbs, before anything is read.
{"GET", "/usaco/../secret", 400, "invalid URL path\n", ""},
{"GET", "/usaco/%2e%2e/secret", 400, "invalid URL path\n", ""},
{"POST", "/usaco/p/moocast", 404, `{"error":"not found"}`, ""},
{"GET", "/elsewhere", 404, `{"error":"not found"}`, ""},
}
for _, c := range cases {
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(c.method, c.path, nil))
if rec.Code != c.code || rec.Body.String() != c.body || rec.Header().Get("Cache-Control") != c.cache {
t.Errorf("%s %s = %d %q (cache %q), want %d %q (cache %q)",
c.method, c.path, rec.Code, rec.Body, rec.Header().Get("Cache-Control"), c.code, c.body, c.cache)
}
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest("GET", "/usaco", nil))
if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/usaco/" {
t.Errorf("GET /usaco = %d to %q, want a redirect to /usaco/", rec.Code, rec.Header().Get("Location"))
}
}