仰望星辰工作室

miaopanel

miaopanel/ internal/httpapi/middleware.go 10.1 KB · 341 行 原始文件
1package httpapi
2
3import (
4 "bufio"
5 "context"
6 "errors"
7 "fmt"
8 "io/fs"
9 "net"
10 "net/http"
11 "path"
12 "runtime/debug"
13 "strings"
14 "time"
15
16 "github.com/miaopanel/miaopanel/internal/security"
17 "github.com/miaopanel/miaopanel/internal/store"
18)
19
20const sessionCookie = "mp_sess"
21
22type ctxKey int
23
24const (
25 ctxKeySession ctxKey = iota
26 ctxKeyUser
27)
28
29var publicAPIPaths = map[string]bool{
30 "/api/v1/health": true,
31 "/api/v1/auth/login": true,
32 "/api/v1/auth/otp": true,
33 "/api/v1/auth/qr/create": true,
34 "/api/v1/auth/qr/status": true,
35 "/api/v1/auth/qr/exchange": true,
36}
37
38func isPublicAPI(p string) bool { return publicAPIPaths[p] }
39
40func (s *Server) recoverer(next http.Handler) http.Handler {
41 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
42 defer func() {
43 if rec := recover(); rec != nil {
44 s.log.Error("panic recovered", "path", r.URL.Path, "panic", rec,
45 "stack", string(debug.Stack()))
46 if strings.HasPrefix(r.URL.Path, "/api/") {
47 writeJSON(w, http.StatusInternalServerError,
48 Envelope{Code: 500, Msg: "服务器内部错误"})
49 } else {
50 http.Error(w, "internal error", http.StatusInternalServerError)
51 }
52 }
53 }()
54 next.ServeHTTP(w, r)
55 })
56}
57
58type statusWriter struct {
59 http.ResponseWriter
60 status int
61 bytes int
62}
63
64func (w *statusWriter) WriteHeader(code int) {
65 w.status = code
66 w.ResponseWriter.WriteHeader(code)
67}
68
69func (w *statusWriter) Write(b []byte) (int, error) {
70 if w.status == 0 {
71 w.status = http.StatusOK
72 }
73 n, err := w.ResponseWriter.Write(b)
74 w.bytes += n
75 return n, err
76}
77
78// Hijack keeps WebSocket upgrades working: gorilla/websocket needs the
79// underlying connection, and a plain wrapper would break the handshake.
80func (w *statusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
81 hijacker, ok := w.ResponseWriter.(http.Hijacker)
82 if !ok {
83 return nil, nil, fmt.Errorf("底层连接不支持 Hijack")
84 }
85 w.status = http.StatusSwitchingProtocols
86 return hijacker.Hijack()
87}
88
89func (w *statusWriter) Flush() {
90 if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
91 flusher.Flush()
92 }
93}
94
95func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
96
97func (s *Server) accessLog(next http.Handler) http.Handler {
98 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
99 start := time.Now()
100 sw := &statusWriter{ResponseWriter: w}
101 next.ServeHTTP(sw, r)
102 if strings.HasPrefix(r.URL.Path, "/api/") {
103 s.log.Info("request", "method", r.Method, "path", r.URL.Path,
104 "status", sw.status, "ms", time.Since(start).Milliseconds(),
105 "ip", clientIP(r, s.cfg.TrustProxy))
106 }
107 })
108}
109
110func (s *Server) headers(next http.Handler) http.Handler {
111 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
112 h := w.Header()
113 h.Set("X-Content-Type-Options", "nosniff")
114 h.Set("X-Frame-Options", "DENY")
115 h.Set("Referrer-Policy", "no-referrer")
116 h.Set("X-Robots-Tag", "noindex, nofollow")
117 h.Set("Content-Security-Policy",
118 "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; "+
119 "script-src 'self'; connect-src 'self'; font-src 'self' data:; frame-ancestors 'none'")
120 if r.URL.Path == "/" || strings.HasPrefix(r.URL.Path, "/assets/") {
121 h.Set("Cache-Control", "no-cache")
122 }
123 next.ServeHTTP(w, r)
124 })
125}
126
127// entryGuard adds response hardening for API traffic. Path level entry checks
128// happen in Handler before the mux is reached.
129func (s *Server) entryGuard(next http.Handler) http.Handler {
130 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
131 if strings.HasPrefix(r.URL.Path, "/api/") {
132 w.Header().Set("Cache-Control", "no-store")
133 }
134 next.ServeHTTP(w, r)
135 })
136}
137
138func (s *Server) authenticate(next http.Handler) http.Handler {
139 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
140 if !strings.HasPrefix(r.URL.Path, "/api/") {
141 next.ServeHTTP(w, r)
142 return
143 }
144 if isPublicAPI(r.URL.Path) {
145 if isMutating(r.Method) && !s.originAllowed(r) {
146 writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "来源校验失败"})
147 return
148 }
149 next.ServeHTTP(w, r)
150 return
151 }
152 token, viaBearer := s.requestToken(r)
153 if token == "" {
154 writeJSON(w, http.StatusUnauthorized, Envelope{Code: 401, Msg: "未登录或会话已过期"})
155 return
156 }
157 ctx := r.Context()
158 // Cookies carry the plain token; only its hash is persisted.
159 sess, err := s.db.SessionByID(ctx, security.HashToken(token))
160 if err != nil {
161 s.clearCookie(w, r)
162 writeJSON(w, http.StatusUnauthorized, Envelope{Code: 401, Msg: "未登录或会话已过期"})
163 return
164 }
165 now := time.Now().Unix()
166 if sess.ExpiresAt < now {
167 _ = s.db.DeleteSession(ctx, sess.ID)
168 s.clearCookie(w, r)
169 writeJSON(w, http.StatusUnauthorized, Envelope{Code: 401, Msg: "会话已过期,请重新登录"})
170 return
171 }
172 user, err := s.db.UserByID(ctx, sess.UserID)
173 if err != nil || user.Status != 1 {
174 writeJSON(w, http.StatusUnauthorized, Envelope{Code: 401, Msg: "账号不可用"})
175 return
176 }
177 // Bearer tokens are only used by the native app, which cannot be the
178 // target of a browser driven CSRF attack: such a credential is never
179 // attached automatically by the client.
180 if isMutating(r.Method) && !viaBearer {
181 csrf := r.Header.Get("X-CSRF-Token")
182 if csrf == "" || csrf != sess.CSRF {
183 writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "CSRF 校验失败,请刷新页面"})
184 return
185 }
186 if !s.originAllowed(r) {
187 writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "来源校验失败"})
188 return
189 }
190 }
191 // Sliding expiry: activity extends the session.
192 _ = s.db.TouchSession(ctx, sess.ID, now+int64(s.cfg.SessionTTL()))
193 ctx = context.WithValue(ctx, ctxKeySession, sess)
194 ctx = context.WithValue(ctx, ctxKeyUser, user)
195 next.ServeHTTP(w, r.WithContext(ctx))
196 })
197}
198
199// requestToken extracts the session token from the HttpOnly cookie, or from
200// the Authorization header for native clients that cannot store cookies. The
201// second return value reports the bearer path so CSRF checks can be skipped.
202func (s *Server) requestToken(r *http.Request) (string, bool) {
203 if c, err := r.Cookie(sessionCookie); err == nil && c.Value != "" {
204 return c.Value, false
205 }
206 const prefix = "bearer "
207 h := strings.TrimSpace(r.Header.Get("Authorization"))
208 if len(h) > len(prefix) && strings.EqualFold(h[:len(prefix)], prefix) {
209 return strings.TrimSpace(h[len(prefix):]), true
210 }
211 return "", false
212}
213
214func isMutating(method string) bool {
215 switch method {
216 case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
217 return true
218 }
219 return false
220}
221
222func (s *Server) originAllowed(r *http.Request) bool {
223 origin := r.Header.Get("Origin")
224 if origin == "" {
225 return true // non browser client; CSRF token still required
226 }
227 if origin == "null" {
228 return false
229 }
230 host := r.Host
231 for _, prefix := range []string{"http://", "https://"} {
232 if strings.HasPrefix(origin, prefix) {
233 return strings.TrimSuffix(strings.TrimPrefix(origin, prefix), "/") == host
234 }
235 }
236 return false
237}
238
239func (s *Server) setCookie(w http.ResponseWriter, r *http.Request, token string) {
240 http.SetCookie(w, &http.Cookie{
241 Name: sessionCookie,
242 Value: token,
243 Path: "/" + strings.Trim(s.cfg.Entry, "/"),
244 HttpOnly: true,
245 // The panel serves both schemes on one port, so the flag follows the
246 // request: an https login never leaks the cookie over plain HTTP.
247 Secure: s.cfg.SecureCookie || r.TLS != nil,
248 SameSite: http.SameSiteStrictMode,
249 MaxAge: s.cfg.SessionTTL(),
250 })
251}
252
253func (s *Server) clearCookie(w http.ResponseWriter, r *http.Request) {
254 http.SetCookie(w, &http.Cookie{
255 Name: sessionCookie,
256 Value: "",
257 Path: "/" + strings.Trim(s.cfg.Entry, "/"),
258 HttpOnly: true,
259 Secure: s.cfg.SecureCookie || r.TLS != nil,
260 SameSite: http.SameSiteStrictMode,
261 MaxAge: -1,
262 })
263}
264
265func sessionFrom(r *http.Request) (*store.Session, *store.User, bool) {
266 sess, ok := r.Context().Value(ctxKeySession).(*store.Session)
267 if !ok {
268 return nil, nil, false
269 }
270 user, ok := r.Context().Value(ctxKeyUser).(*store.User)
271 if !ok {
272 return nil, nil, false
273 }
274 return sess, user, true
275}
276
277// camouflage mimics a stock nginx 404 so the panel is invisible to scanners.
278func (s *Server) camouflage(w http.ResponseWriter, r *http.Request) {
279 w.Header().Set("Content-Type", "text/html; charset=utf-8")
280 w.Header().Set("Server", "nginx")
281 w.WriteHeader(http.StatusNotFound)
282 fmt.Fprint(w, `<!doctype html><html><head><title>404 Not Found</title></head><body style="background:#fff;color:#000;font-family:sans-serif">
283<center><h1>404 Not Found</h1></center><hr><center>nginx</center></body></html>`)
284}
285
286func (s *Server) staticHandler() http.Handler {
287 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
288 if r.Method != http.MethodGet && r.Method != http.MethodHead {
289 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
290 return
291 }
292 if s.web == nil {
293 http.Error(w, "UI 未构建", http.StatusNotFound)
294 return
295 }
296 p := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
297 if p == "" || p == "." {
298 p = "index.html"
299 }
300 if f, err := s.web.Open(p); err == nil {
301 _ = f.Close()
302 http.FileServerFS(s.web).ServeHTTP(w, r)
303 return
304 }
305 // SPA fallback
306 index, err := fs.ReadFile(s.web, "index.html")
307 if err != nil {
308 http.Error(w, "UI 未构建", http.StatusNotFound)
309 return
310 }
311 w.Header().Set("Content-Type", "text/html; charset=utf-8")
312 w.Header().Set("Cache-Control", "no-cache")
313 _, _ = w.Write(index)
314 })
315}
316
317// audit records a mutating operation; it never fails the request.
318func (s *Server) audit(r *http.Request, module, action, target, result string, started time.Time) {
319 sess, user, ok := sessionFrom(r)
320 if !ok {
321 return
322 }
323 _ = s.db.Audit(r.Context(), store.AuditEntry{
324 UserID: user.ID, Username: user.Username,
325 IP: clientIP(r, s.cfg.TrustProxy), UA: r.UserAgent(),
326 Module: module, Action: action, Target: target, Result: result,
327 CostMS: time.Since(started).Milliseconds(),
328 })
329 _ = sess
330}
331
332// requireUser fetches the authenticated user or returns an APIError.
333func requireUser(r *http.Request) (*store.User, error) {
334 _, user, ok := sessionFrom(r)
335 if !ok {
336 return nil, Errorf(http.StatusUnauthorized, "未登录")
337 }
338 return user, nil
339}
340
341var errNotFound = errors.New("not found")