okami.mom/web-extract-go

git clone https://git.nkp.pet/okami.mom/web-extract-go

nekomimi.petadmin: show what each request's decisions would cost on Jev8af1784

main
7.2 KiB224 linesraw
1package app
2
3import (
4	"context"
5	"crypto/sha256"
6	"crypto/subtle"
7	"io/fs"
8	"log/slog"
9	"mime"
10	"net/http"
11	"strconv"
12	"strings"
13	"sync"
14	"time"
15
16	adminui "web-extract/web"
17)
18
19const adminCookie = "web_extract_admin"
20const adminSessionTTL = 12 * time.Hour
21
22// Sessions are bounded and process-local: logout revokes them and restart clears them.
23type adminAuth struct {
24	mu       sync.Mutex
25	sessions map[string]time.Time
26	failures int
27	window   time.Time
28}
29
30func (s *Service) handler() http.Handler {
31	api := s.apiHandler()
32	mux := http.NewServeMux()
33	admin := s.adminHandler(api)
34	mux.Handle("/admin", admin)
35	mux.Handle("/admin/", admin)
36	mux.Handle("/", api)
37	return mux
38}
39
40func (s *Service) adminHandler(api http.Handler) http.Handler {
41	auth := &adminAuth{sessions: make(map[string]time.Time)}
42	assets, err := fs.Sub(adminui.Files, "dist")
43	if err != nil {
44		panic(err)
45	}
46	files := http.StripPrefix("/admin/", http.FileServer(http.FS(assets)))
47	routes := http.NewServeMux()
48	routes.HandleFunc("POST /admin/api/login", func(w http.ResponseWriter, r *http.Request) {
49		var input struct {
50			Password string `json:"password"`
51		}
52		body, err := readBounded(r.Body, 4096)
53		if err != nil || strictJSON(body, &input) != nil {
54			adminError(w, 400, "provide a password as json")
55			return
56		}
57		auth.mu.Lock()
58		defer auth.mu.Unlock()
59		now := time.Now()
60		if now.Sub(auth.window) >= time.Minute {
61			auth.window, auth.failures = now, 0
62		}
63		if auth.failures >= 10 {
64			w.Header().Set("Retry-After", "60")
65			adminError(w, 429, "too many login attempts; try again in a minute")
66			return
67		}
68		got, want := sha256.Sum256([]byte(input.Password)), sha256.Sum256([]byte(s.cfg.AdminPassword))
69		if subtle.ConstantTimeCompare(got[:], want[:]) != 1 {
70			auth.failures++
71			adminError(w, 401, "incorrect password")
72			return
73		}
74		for token, expiry := range auth.sessions {
75			if !expiry.After(now) {
76				delete(auth.sessions, token)
77			}
78		}
79		if len(auth.sessions) >= 128 {
80			adminError(w, 429, "too many active sessions; sign out of another browser")
81			return
82		}
83		token := newID() + newID()
84		auth.sessions[token] = now.Add(adminSessionTTL)
85		s.adminSetCookie(w, r, token, int(adminSessionTTL.Seconds()))
86		writeJSON(w, 200, map[string]bool{"authenticated": true})
87	})
88
89	protected := http.NewServeMux()
90	protected.HandleFunc("GET /admin/api/session", func(w http.ResponseWriter, r *http.Request) {
91		writeJSON(w, 200, map[string]bool{"authenticated": true})
92	})
93	protected.HandleFunc("POST /admin/api/logout", func(w http.ResponseWriter, r *http.Request) {
94		cookie, _ := r.Cookie(adminCookie)
95		auth.mu.Lock()
96		delete(auth.sessions, cookie.Value)
97		auth.mu.Unlock()
98		s.adminSetCookie(w, r, "", -1)
99		writeJSON(w, 200, map[string]bool{"authenticated": false})
100	})
101	protected.HandleFunc("GET /admin/api/overview", func(w http.ResponseWriter, r *http.Request) {
102		data, err := s.adminOverview(r.Context())
103		adminRespond(w, data, err)
104	})
105	protected.HandleFunc("GET /admin/api/requests", func(w http.ResponseWriter, r *http.Request) {
106		before := int64(0)
107		if raw := r.URL.Query().Get("before"); raw != "" {
108			var err error
109			before, err = strconv.ParseInt(raw, 10, 64)
110			if err != nil || before < 1 {
111				adminError(w, 400, "invalid pagination cursor")
112				return
113			}
114		}
115		endpoint := r.URL.Query().Get("endpoint")
116		if endpoint != "" && endpoint != "search" && endpoint != "contents" && endpoint != "answer" {
117			adminError(w, 400, "invalid endpoint filter")
118			return
119		}
120		data, err := s.adminRequests(r.Context(), before, endpoint, r.URL.Query().Get("errors") == "true")
121		adminRespond(w, data, err)
122	})
123	protected.HandleFunc("GET /admin/api/requests/{id}", func(w http.ResponseWriter, r *http.Request) {
124		id := r.PathValue("id")
125		if len(id) > 128 {
126			adminError(w, 400, "invalid request id")
127			return
128		}
129		data, err := s.log.adminTrace(r.Context(), id)
130		if err == nil && len(data.Requests) == 0 {
131			adminError(w, 404, "request not found")
132			return
133		}
134		adminRespond(w, data, err)
135	})
136	// Reuse the exact public API validation, execution, response, and training logs.
137	// The API token never travels to the browser, and cookie auth never grants /mcp access.
138	for _, endpoint := range []string{"search", "contents", "answer"} {
139		protected.HandleFunc("POST /admin/api/"+endpoint, func(w http.ResponseWriter, r *http.Request) {
140			r = r.Clone(r.Context())
141			r.URL.Path = "/" + endpoint
142			r.Header.Set("x-api-key", s.cfg.Token)
143			r.Header.Set("x-caller", "admin-dashboard")
144			api.ServeHTTP(w, r)
145		})
146	}
147	protected.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { adminError(w, 404, "unknown admin endpoint") })
148	routes.Handle("/admin/api/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
149		cookie, err := r.Cookie(adminCookie)
150		auth.mu.Lock()
151		valid := err == nil && auth.sessions[cookieValue(cookie)].After(time.Now())
152		auth.mu.Unlock()
153		if !valid {
154			adminError(w, 401, "sign in to continue")
155			return
156		}
157		ctx, cancel := context.WithTimeout(r.Context(), s.cfg.RequestTimeout)
158		defer cancel()
159		protected.ServeHTTP(w, r.WithContext(ctx))
160	}))
161	routes.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) {
162		http.Redirect(w, r, "/admin/", http.StatusTemporaryRedirect)
163	})
164	routes.HandleFunc("/admin/", func(w http.ResponseWriter, r *http.Request) {
165		if r.Method != "GET" && r.Method != "HEAD" {
166			w.Header().Set("Allow", "GET, HEAD")
167			adminError(w, 405, "use get")
168			return
169		}
170		if r.URL.Path != "/admin/" && !strings.HasPrefix(r.URL.Path, "/admin/assets/") {
171			http.NotFound(w, r)
172			return
173		}
174		files.ServeHTTP(w, r)
175	})
176	csrf := http.NewCrossOriginProtection()
177	csrf.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
178		adminError(w, 403, "cross-origin requests are not allowed")
179	}))
180	handler := csrf.Handler(routes)
181	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
182		if s.cfg.AdminPassword == "" {
183			http.NotFound(w, r)
184			return
185		}
186		w.Header().Set("Cache-Control", "no-store")
187		w.Header().Set("X-Content-Type-Options", "nosniff")
188		w.Header().Set("X-Frame-Options", "DENY")
189		w.Header().Set("Referrer-Policy", "no-referrer")
190		w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'")
191		if r.Method == "POST" {
192			media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
193			if media != "application/json" {
194				adminError(w, 415, "use application/json")
195				return
196			}
197		}
198		handler.ServeHTTP(w, r)
199	})
200}
201
202func cookieValue(c *http.Cookie) string {
203	if c == nil {
204		return ""
205	}
206	return c.Value
207}
208
209func (s *Service) adminSetCookie(w http.ResponseWriter, r *http.Request, value string, age int) {
210	http.SetCookie(w, &http.Cookie{Name: adminCookie, Value: value, Path: "/admin", HttpOnly: true,
211		Secure: s.cfg.AdminCookieSecure || r.TLS != nil, SameSite: http.SameSiteStrictMode, MaxAge: age})
212}
213
214func adminError(w http.ResponseWriter, status int, message string) {
215	writeJSON(w, status, map[string]string{"error": message})
216}
217func adminRespond(w http.ResponseWriter, data any, err error) {
218	if err != nil {
219		slog.Error("admin query failed", "error", err)
220		adminError(w, 500, "could not read the activity log; try refreshing")
221		return
222	}
223	writeJSON(w, 200, data)
224}