安全加固 + 结构清理:修注入/串写/竞态,DOMPurify 上线,后端补事务与 handler 测试
后端: - ORDER BY 白名单(sanitizeOrder)堵住 ?order= SQL 注入,补回归测试 - 登录限速(每 IP 10 次失败/10 分钟 429)、TLS/反代下 Secure cookie、NewAPI 构造器 - Delete/setTags/MergeTags/DeleteTag 包事务;Archive 去 500 篇上限 - 列表接口裁剪:不传 content_md,长文 content_html 截 600,新增 content_len;health 探 DB 前端: - EditorView 路由复用串写修复(RouterView :key + sync watch 回写原文章) - v-html 出口统一过 DOMPurify(sanitizeHtml),stripTags 改 DOMParser - 列表竞态防护(Home/Tag/Posts 请求序号)、TagView 分页修复 - 侧栏接口 30s 缓存去重;one:unauthorized 监听器泄漏修复 - 删 styles.css 498 行重复块;移除 tailwind/marked/vue-tsc 死依赖;CommandPalette a11y 语义
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"oneblog/internal/config"
|
||||
"oneblog/internal/httpx"
|
||||
@@ -19,6 +20,25 @@ type API struct {
|
||||
Store *store.Store
|
||||
Cfg *config.Config
|
||||
Sessions *Sessions
|
||||
|
||||
loginOnce sync.Once
|
||||
logins *loginLimiter
|
||||
}
|
||||
|
||||
func NewAPI(st *store.Store, cfg *config.Config, sessions *Sessions) *API {
|
||||
a := &API{Store: st, Cfg: cfg, Sessions: sessions}
|
||||
a.limiter()
|
||||
return a
|
||||
}
|
||||
|
||||
// limiter 惰性初始化,兼容测试里的 &API{...} 零值构造。
|
||||
func (a *API) limiter() *loginLimiter {
|
||||
a.loginOnce.Do(func() {
|
||||
if a.logins == nil {
|
||||
a.logins = newLoginLimiter()
|
||||
}
|
||||
})
|
||||
return a.logins
|
||||
}
|
||||
|
||||
const cookieName = "one_session"
|
||||
@@ -81,6 +101,11 @@ func (a *API) login(w http.ResponseWriter, r *http.Request) {
|
||||
httpx.Error(w, http.StatusMethodNotAllowed, "POST required")
|
||||
return
|
||||
}
|
||||
key := sourceKey(r)
|
||||
if a.limiter().blocked(key) {
|
||||
httpx.Error(w, http.StatusTooManyRequests, "失败次数过多,请 10 分钟后再试")
|
||||
return
|
||||
}
|
||||
var in loginRequest
|
||||
if err := httpx.Decode(r, &in); err != nil {
|
||||
httpx.BadRequest(w, "invalid body")
|
||||
@@ -89,15 +114,18 @@ func (a *API) login(w http.ResponseWriter, r *http.Request) {
|
||||
userOK := subtle.ConstantTimeCompare([]byte(in.Username), []byte(a.Cfg.AdminUser)) == 1
|
||||
passOK := subtle.ConstantTimeCompare([]byte(in.Password), []byte(a.Cfg.AdminPass)) == 1
|
||||
if !userOK || !passOK {
|
||||
a.limiter().fail(key)
|
||||
httpx.Unauthorized(w)
|
||||
return
|
||||
}
|
||||
a.limiter().reset(key)
|
||||
token, exp := a.Sessions.Issue(a.Cfg.AdminUser)
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: isTLS(r),
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Expires: exp,
|
||||
MaxAge: a.Sessions.TTL(),
|
||||
@@ -113,6 +141,7 @@ func (a *API) logout(w http.ResponseWriter, r *http.Request) {
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: isTLS(r),
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: -1,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"oneblog/internal/config"
|
||||
"oneblog/internal/db"
|
||||
"oneblog/internal/model"
|
||||
"oneblog/internal/store"
|
||||
)
|
||||
|
||||
func newTestAPI(t *testing.T) (*API, http.Handler) {
|
||||
t.Helper()
|
||||
d, err := db.Open("sqlite", ":memory:")
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
st, err := store.New(d)
|
||||
if err != nil {
|
||||
t.Fatalf("store: %v", err)
|
||||
}
|
||||
cfg := &config.Config{AdminUser: "admin", AdminPass: "s3cret"}
|
||||
a := NewAPI(st, cfg, NewSessions("test-secret", time.Hour))
|
||||
return a, a.Routes()
|
||||
}
|
||||
|
||||
func login(t *testing.T, h http.Handler, user, pass string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body, _ := json.Marshal(loginRequest{Username: user, Password: pass})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/login", strings.NewReader(string(body)))
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestGuardRejectsAnonymous(t *testing.T) {
|
||||
_, h := newTestAPI(t)
|
||||
for _, path := range []string{"/api/admin/posts", "/api/admin/settings", "/api/admin/dashboard"} {
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s: got %d, want 401", path, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginIssuesUsableSession(t *testing.T) {
|
||||
_, h := newTestAPI(t)
|
||||
rec := login(t, h, "admin", "wrong")
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("wrong password: got %d, want 401", rec.Code)
|
||||
}
|
||||
rec = login(t, h, "admin", "s3cret")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("login: got %d, want 200", rec.Code)
|
||||
}
|
||||
var out struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.NewDecoder(rec.Body).Decode(&out); err != nil || out.Token == "" {
|
||||
t.Fatalf("no token in response: %v", err)
|
||||
}
|
||||
// Bearer 通道
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/admin/posts", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+out.Token)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req)
|
||||
if rec2.Code != http.StatusOK {
|
||||
t.Fatalf("bearer posts: got %d, want 200", rec2.Code)
|
||||
}
|
||||
// cookie 通道
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/admin/posts", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "one_session", Value: out.Token})
|
||||
rec3 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec3, req)
|
||||
if rec3.Code != http.StatusOK {
|
||||
t.Fatalf("cookie posts: got %d, want 200", rec3.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRateLimitedAfterRepeatedFailures(t *testing.T) {
|
||||
_, h := newTestAPI(t)
|
||||
var rec *httptest.ResponseRecorder
|
||||
for i := 0; i < maxLoginFails+1; i++ {
|
||||
rec = login(t, h, "admin", "bad")
|
||||
}
|
||||
if rec.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("after %d failures: got %d, want 429", maxLoginFails+1, rec.Code)
|
||||
}
|
||||
// 限速期间即使口令正确也被拒
|
||||
rec = login(t, h, "admin", "s3cret")
|
||||
if rec.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("locked out login: got %d, want 429", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecureCookieBehindTLSProxy(t *testing.T) {
|
||||
_, h := newTestAPI(t)
|
||||
body, _ := json.Marshal(loginRequest{Username: "admin", Password: "s3cret"})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/login", strings.NewReader(string(body)))
|
||||
req.Header.Set("X-Forwarded-Proto", "https")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("login: %d", rec.Code)
|
||||
}
|
||||
cookie := rec.Header().Get("Set-Cookie")
|
||||
if !strings.Contains(cookie, "Secure") {
|
||||
t.Fatalf("expected Secure flag over https proxy, got: %s", cookie)
|
||||
}
|
||||
}
|
||||
|
||||
// ?order= 直接来自查询串并拼进 SQL,注入串必须被白名单挡掉且不影响数据。
|
||||
func TestOrderParamInjectionIsNeutralized(t *testing.T) {
|
||||
a, h := newTestAPI(t)
|
||||
if _, err := a.Store.Create(model.PostInput{Title: "one", ContentMd: "a", Status: model.StatusPublished}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token := login(t, h, "admin", "s3cret")
|
||||
var out struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
_ = json.NewDecoder(token.Body).Decode(&out)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/admin/posts?order="+
|
||||
strings.ReplaceAll("published_at DESC; DROP TABLE posts; --", " ", "%20"), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+out.Token)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("injected order: got %d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// 表若被 DROP,这条查询会报错
|
||||
if _, err := a.Store.List(store.ListOptions{Status: "any"}); err != nil {
|
||||
t.Fatalf("posts table damaged: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// loginLimiter 限制每个来源 IP 的登录失败次数(滑动窗口),
|
||||
// 防止默认/弱口令被在线暴力破解。成功登录后计数清零。
|
||||
type loginLimiter struct {
|
||||
mu sync.Mutex
|
||||
hits map[string][]time.Time
|
||||
}
|
||||
|
||||
const (
|
||||
maxLoginFails = 10
|
||||
loginWindow = 10 * time.Minute
|
||||
)
|
||||
|
||||
func newLoginLimiter() *loginLimiter {
|
||||
return &loginLimiter{hits: make(map[string][]time.Time)}
|
||||
}
|
||||
|
||||
func (l *loginLimiter) blocked(key string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return len(l.recent(key, time.Now())) >= maxLoginFails
|
||||
}
|
||||
|
||||
func (l *loginLimiter) fail(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
now := time.Now()
|
||||
l.hits[key] = append(l.recent(key, now), now)
|
||||
}
|
||||
|
||||
func (l *loginLimiter) reset(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
delete(l.hits, key)
|
||||
}
|
||||
|
||||
// recent 返回窗口内的失败时间;调用方必须持有 l.mu。
|
||||
func (l *loginLimiter) recent(key string, now time.Time) []time.Time {
|
||||
hs := l.hits[key]
|
||||
cut := now.Add(-loginWindow)
|
||||
i := 0
|
||||
for ; i < len(hs); i++ {
|
||||
if hs[i].After(cut) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if i > 0 {
|
||||
hs = hs[i:]
|
||||
l.hits[key] = hs
|
||||
}
|
||||
if len(hs) == 0 {
|
||||
delete(l.hits, key)
|
||||
}
|
||||
return hs
|
||||
}
|
||||
|
||||
func sourceKey(r *http.Request) string {
|
||||
// 只信连接层地址;X-Forwarded-For 可被伪造,不作为限速键。
|
||||
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
return host
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
// isTLS 判断最终用户看到的是不是 HTTPS(含反代 X-Forwarded-Proto)。
|
||||
func isTLS(r *http.Request) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
return r.Header.Get("X-Forwarded-Proto") == "https"
|
||||
}
|
||||
Reference in New Issue
Block a user