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]>
136 lines
4.2 KiB
Go
136 lines
4.2 KiB
Go
// Package auth decides whether a request comes from the site's admin.
|
|
//
|
|
// Copied from the job tracker (adamf/job-tracker, internal/auth), which has
|
|
// the same arrangement: no users or passwords here. The site runs behind the
|
|
// main site's nginx and borrows that site's session: the browser already
|
|
// carries the site's HTTP-only auth cookies on every request to /usaco/, so
|
|
// the Cookie header is forwarded to the site backend's
|
|
// GET /auth/validate-admin and a 2xx means "admin". Logging in and out happen
|
|
// on the main site; this only ever asks.
|
|
//
|
|
// Unlike the tracker, most of this site is public: the verdict decides what a
|
|
// visitor sees (solved problems only, or everything) as well as guarding the
|
|
// edit routes.
|
|
//
|
|
// Two consequences worth knowing:
|
|
// - validate-admin falls back to the refresh token when the access token has
|
|
// expired, and answers with fresh cookies. Those Set-Cookie headers are
|
|
// relayed onto this response, or the browser would keep presenting the
|
|
// expired token and every request would refresh again.
|
|
// - The answer is cached for a short while per cookie. Only "yes" is
|
|
// cached: a refusal is re-asked, so logging in takes effect at once.
|
|
// Logging out takes up to cacheTTL to reach this site.
|
|
//
|
|
// Mode "dev" admits everyone. It exists for the standalone docker-compose,
|
|
// which has no site backend to ask, and main refuses it unless DEV_MODE=true.
|
|
package auth
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"log"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// cacheTTL is how long a "yes" from the site backend is trusted.
|
|
const cacheTTL = 30 * time.Second
|
|
|
|
// Checker answers whether the request is the admin's. It may write headers
|
|
// (the relayed Set-Cookie) onto w, which is why it gets the writer.
|
|
type Checker interface {
|
|
IsAdmin(w http.ResponseWriter, r *http.Request) bool
|
|
}
|
|
|
|
// AllowAll is the "dev" mode checker.
|
|
type AllowAll struct{}
|
|
|
|
func (AllowAll) IsAdmin(http.ResponseWriter, *http.Request) bool { return true }
|
|
|
|
// Forward asks the site backend at URL, forwarding the request's cookies.
|
|
type Forward struct {
|
|
URL string
|
|
Client *http.Client
|
|
|
|
mu sync.Mutex
|
|
cache map[string]time.Time // sha256(Cookie header) -> when it was confirmed
|
|
}
|
|
|
|
// NewForward builds a Forward checker for validateURL, normally
|
|
// http://backend:8080/auth/validate-admin on the Docker network.
|
|
func NewForward(validateURL string) *Forward {
|
|
return &Forward{
|
|
URL: validateURL,
|
|
// Short: this sits in front of every request that has cookies, and a
|
|
// backend that does not answer in a few seconds should be a refusal,
|
|
// not a hang.
|
|
Client: &http.Client{Timeout: 5 * time.Second},
|
|
cache: map[string]time.Time{},
|
|
}
|
|
}
|
|
|
|
func (f *Forward) IsAdmin(w http.ResponseWriter, r *http.Request) bool {
|
|
cookie := r.Header.Get("Cookie")
|
|
if cookie == "" {
|
|
return false
|
|
}
|
|
sum := sha256.Sum256([]byte(cookie))
|
|
key := hex.EncodeToString(sum[:])
|
|
|
|
f.mu.Lock()
|
|
confirmed, ok := f.cache[key]
|
|
f.mu.Unlock()
|
|
if ok && time.Since(confirmed) < cacheTTL {
|
|
return true
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, f.URL, nil)
|
|
if err != nil {
|
|
log.Printf("[auth] building validate request: %v", err)
|
|
return false
|
|
}
|
|
req.Header.Set("Cookie", cookie)
|
|
resp, err := f.Client.Do(req)
|
|
if err != nil {
|
|
log.Printf("[auth] site backend unreachable: %v", err)
|
|
return false
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
// Relayed whatever the verdict: a refresh that rotated the cookies is
|
|
// worth keeping even on a 403.
|
|
for _, c := range resp.Header.Values("Set-Cookie") {
|
|
w.Header().Add("Set-Cookie", c)
|
|
}
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
|
return false
|
|
}
|
|
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
// Pruned on the way through; the map only grows with distinct admin
|
|
// sessions, so this is plenty.
|
|
for k, t := range f.cache {
|
|
if time.Since(t) >= cacheTTL {
|
|
delete(f.cache, k)
|
|
}
|
|
}
|
|
f.cache[key] = time.Now()
|
|
return true
|
|
}
|
|
|
|
// Require refuses a non-admin with 401. It guards the REST admin routes.
|
|
func Require(c Checker) gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
if !c.IsAdmin(ctx.Writer, ctx.Request) {
|
|
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "admin access required"})
|
|
return
|
|
}
|
|
ctx.Next()
|
|
}
|
|
}
|