Split the job tracker out of web_server into its own app
The applications tracker, leads inbox, email pipeline and capture userscript move here from web_server's backend, Python service and Vue app, as one Go binary that serves its own Vue SPA under /jobs/. - The Go services, resolvers and tests move over almost unchanged. - The three Claude calls are ported from Python to Go (internal/claude), with the same prompts, per-model request shaping and error messages. - There is no login: internal/auth asks the site backend's /auth/validate-admin with the visitor's cookies, and relays refreshed cookies back. - A Settings page replaces the admin-panel capture token card and adds the Microsoft sign-in link and a manual email sync. - The userscript is 2.0.0, at /jobs/, and migrates a saved API base. - Dockerfile, a standalone compose with Postgres, Makefile, and a Gitea CI workflow that tests and publishes the image. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
// Package auth decides whether a request comes from the site's admin.
|
||||
//
|
||||
// The job tracker has no users or passwords of its own. It 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 /jobs/, so
|
||||
// the tracker forwards the Cookie header to the site backend's
|
||||
// GET /auth/validate-admin — the same check nginx's auth_request uses for
|
||||
// /radio/admin and /sb — and treats a 2xx as "admin". Logging in and out
|
||||
// therefore happen on the main site; the tracker only ever asks.
|
||||
//
|
||||
// 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, so a page that fires
|
||||
// several GraphQL queries costs one round trip. Only "yes" is cached: a
|
||||
// refusal is re-asked, so logging in takes effect at once. Logging out
|
||||
// takes up to cacheTTL to reach the tracker, which is the price of the
|
||||
// cache.
|
||||
//
|
||||
// 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 (
|
||||
"context"
|
||||
"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 admin request, 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
|
||||
}
|
||||
|
||||
type contextKey struct{}
|
||||
|
||||
// WithAdmin records the verdict on a context, for the GraphQL @admin
|
||||
// directive to read.
|
||||
func WithAdmin(ctx context.Context, admin bool) context.Context {
|
||||
return context.WithValue(ctx, contextKey{}, admin)
|
||||
}
|
||||
|
||||
// IsAdminFromCtx reads what WithAdmin stored; false when nothing was stored.
|
||||
func IsAdminFromCtx(ctx context.Context) bool {
|
||||
admin, _ := ctx.Value(contextKey{}).(bool)
|
||||
return admin
|
||||
}
|
||||
|
||||
// Annotate runs the check and records the verdict on the request context
|
||||
// without refusing anything. It goes in front of GraphQL, where the refusal
|
||||
// is the @admin directive's job so that the client gets the usual GraphQL
|
||||
// error rather than a bare 401.
|
||||
func Annotate(c Checker) gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
admin := c.IsAdmin(ctx.Writer, ctx.Request)
|
||||
ctx.Request = ctx.Request.WithContext(WithAdmin(ctx.Request.Context(), admin))
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// site fakes the backend's validate-admin: 200 for the "admin" session,
|
||||
// 403 for any other cookie, 401 for none, and a rotated cookie on "stale".
|
||||
func site(t *testing.T, calls *atomic.Int32) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
c, err := r.Cookie("access_token")
|
||||
switch {
|
||||
case err != nil:
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
case c.Value == "admin":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case c.Value == "stale":
|
||||
http.SetCookie(w, &http.Cookie{Name: "access_token", Value: "fresh"})
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func ask(f *Forward, cookie string) (bool, *httptest.ResponseRecorder) {
|
||||
r := httptest.NewRequest(http.MethodPost, "/jobs/api/graphql", nil)
|
||||
if cookie != "" {
|
||||
r.Header.Set("Cookie", cookie)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
return f.IsAdmin(w, r), w
|
||||
}
|
||||
|
||||
func TestForwardVerdicts(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
f := NewForward(site(t, &calls).URL)
|
||||
|
||||
cases := []struct {
|
||||
name, cookie string
|
||||
want bool
|
||||
}{
|
||||
{"admin session", "access_token=admin", true},
|
||||
{"signed in, not admin", "access_token=someone", false},
|
||||
{"cookies but no session", "theme=dark", false},
|
||||
{"no cookies at all", "", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got, _ := ask(f, c.cookie); got != c.want {
|
||||
t.Fatalf("IsAdmin = %v, want %v", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardCachesOnlyYes(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
f := NewForward(site(t, &calls).URL)
|
||||
|
||||
ask(f, "access_token=admin")
|
||||
ask(f, "access_token=admin")
|
||||
if n := calls.Load(); n != 1 {
|
||||
t.Fatalf("admin checked %d times, want 1 (second answer from cache)", n)
|
||||
}
|
||||
|
||||
calls.Store(0)
|
||||
ask(f, "access_token=someone")
|
||||
ask(f, "access_token=someone")
|
||||
if n := calls.Load(); n != 2 {
|
||||
t.Fatalf("refusal checked %d times, want 2 (refusals are not cached)", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardRelaysRefreshedCookies(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
f := NewForward(site(t, &calls).URL)
|
||||
|
||||
ok, w := ask(f, "access_token=stale")
|
||||
if !ok {
|
||||
t.Fatal("refreshed session refused")
|
||||
}
|
||||
if got := w.Header().Get("Set-Cookie"); got != "access_token=fresh" {
|
||||
t.Fatalf("Set-Cookie = %q, want the backend's rotated cookie", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardBackendDownRefuses(t *testing.T) {
|
||||
f := NewForward("http://127.0.0.1:1/auth/validate-admin")
|
||||
if ok, _ := ask(f, "access_token=admin"); ok {
|
||||
t.Fatal("admitted while the site backend was unreachable")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user