阶段十:完成 Go 基础包注释基线清零
This commit is contained in:
1 parent
ea1f2ec430
commit
d1a165f897
14 files changed
+135
-924
No files matched your search
@@ -25,6 +25,7 @@ const CookieMaxAge = 24 * 60 * 60
|
||||
// ctxKey 上下文键类型,避免冲突。
|
||||
type ctxKey int
|
||||
|
||||
// ctxKeyUser 保存ctxKey用户,供当前处理流程使用
|
||||
const (
|
||||
ctxKeyUser ctxKey = iota
|
||||
)
|
||||
@@ -45,6 +46,7 @@ type LoginResult struct {
|
||||
|
||||
// Login 用户名密码登录。成功时返回会话 ID(由调用方写入 Cookie)。
|
||||
func (s *Service) Login(ctx context.Context, username, password string) (string, *db.User, error) {
|
||||
// user、ok、err 保存user、ok、err,供当前处理流程使用
|
||||
user, ok, err := s.Store.Users.VerifyAndUpgrade(ctx, username, password)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
@@ -52,6 +54,7 @@ func (s *Service) Login(ctx context.Context, username, password string) (string,
|
||||
if !ok {
|
||||
return "", nil, nil // 密码错误或用户不存在/未激活
|
||||
}
|
||||
// sid、err 保存sid、err,供当前处理流程使用
|
||||
sid, err := s.Store.Sessions.Create(ctx, user)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
@@ -96,10 +99,12 @@ func (s *Service) ClearSessionCookie(w http.ResponseWriter) {
|
||||
|
||||
// SessionFromRequest 从请求 Cookie 取会话。无效返回 nil。
|
||||
func (s *Service) SessionFromRequest(ctx context.Context, r *http.Request) (*db.Session, error) {
|
||||
// c、err 保存c、err,供当前处理流程使用
|
||||
c, err := r.Cookie(CookieName)
|
||||
if err != nil || c.Value == "" {
|
||||
return nil, nil
|
||||
}
|
||||
// sess、err 保存sess、err,供当前处理流程使用
|
||||
sess, err := s.Store.Sessions.Get(ctx, c.Value)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
@@ -113,10 +118,12 @@ func (s *Service) SessionFromRequest(ctx context.Context, r *http.Request) (*db.
|
||||
// Middleware 解析会话并把 *db.Session 放入请求上下文。不强制登录(公开路由也可用)。
|
||||
func (s *Service) Middleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// sess、err 保存sess、err,供当前处理流程使用
|
||||
sess, err := s.SessionFromRequest(r.Context(), r)
|
||||
if err != nil {
|
||||
s.Logger.Warn("读取会话失败", "err", err)
|
||||
}
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := WithSession(r.Context(), sess)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
@@ -136,6 +143,7 @@ func RequireAuth(next http.Handler) http.Handler {
|
||||
// RequireAdmin 要求管理员,否则 403(须在 RequireAuth 之后)。
|
||||
func RequireAdmin(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
sess := SessionFromContext(r.Context())
|
||||
if sess == nil || !sess.IsAdmin {
|
||||
writeAuthError(w, r, http.StatusForbidden, "forbidden", "需要管理员权限")
|
||||
@@ -150,7 +158,9 @@ func WithSession(ctx context.Context, sess *db.Session) context.Context {
|
||||
return context.WithValue(ctx, ctxKeyUser, sess)
|
||||
}
|
||||
|
||||
// SessionFromContext 负责会话From上下文相关处理。
|
||||
func SessionFromContext(ctx context.Context) *db.Session {
|
||||
// v 保存v,供当前处理流程使用
|
||||
v, _ := ctx.Value(ctxKeyUser).(*db.Session)
|
||||
return v
|
||||
}
|
||||
@@ -158,12 +168,15 @@ func SessionFromContext(ctx context.Context) *db.Session {
|
||||
// InitAdmin 创建或重置 admin 管理员账号,是 cmd/server -init-admin 与
|
||||
// cmd/init-admin 共用的公共入口。返回 created=true 表示新建 admin,
|
||||
// false 表示重置已存在 admin 的密码。邮箱仅在新建时使用。
|
||||
// InitAdmin 负责InitAdmin相关处理。
|
||||
func InitAdmin(ctx context.Context, store *db.Store, email, password string) (created bool, err error) {
|
||||
// existing、err 保存existing、err,供当前处理流程使用
|
||||
existing, err := store.Users.GetAdmin(ctx)
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
return false, fmt.Errorf("查询 admin 失败: %w", err)
|
||||
}
|
||||
if existing != nil {
|
||||
// ok、err 保存ok、err,供当前处理流程使用
|
||||
ok, err := store.Users.UpdatePassword(ctx, existing.Username, password)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -173,6 +186,7 @@ func InitAdmin(ctx context.Context, store *db.Store, email, password string) (cr
|
||||
}
|
||||
return false, store.Users.SetAdmin(ctx, existing.Username)
|
||||
}
|
||||
// ok、err 保存ok、err,供当前处理流程使用
|
||||
ok, err := store.Users.Create(ctx, "admin", email, password)
|
||||
if err != nil {
|
||||
return false, err
|
||||
|
||||
@@ -11,28 +11,37 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// newAuth 负责newAuth相关处理。
|
||||
func newAuth(t *testing.T) (*Service, func()) {
|
||||
t.Helper()
|
||||
// dbPath 保存db路径,供当前处理流程使用
|
||||
dbPath := filepath.Join(t.TempDir(), "test.db")
|
||||
// d、err 保存d、err,供当前处理流程使用
|
||||
d, _, err := db.Open(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
// store 保存store,供当前处理流程使用
|
||||
store := db.NewStore(d, db.DialectSQLite)
|
||||
// 初始化 admin。
|
||||
if ok, _ := store.Users.Create(context.Background(), "admin", "[email protected]", "pw"); !ok {
|
||||
t.Fatal("create admin")
|
||||
}
|
||||
store.Users.SetAdmin(context.Background(), "admin")
|
||||
// svc 保存svc,供当前处理流程使用
|
||||
svc := &Service{Store: store, Logger: testLogger()}
|
||||
return svc, func() { d.Close() }
|
||||
}
|
||||
|
||||
// testLogger 负责testLogger相关处理。
|
||||
func testLogger() *slog.Logger { return slog.Default() }
|
||||
|
||||
// TestLoginAndMiddleware 负责Test登录AndMiddleware相关处理。
|
||||
func TestLoginAndMiddleware(t *testing.T) {
|
||||
// svc、cleanup 保存svc、cleanup,供当前处理流程使用
|
||||
svc, cleanup := newAuth(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
|
||||
// 登录。
|
||||
@@ -48,6 +57,7 @@ func TestLoginAndMiddleware(t *testing.T) {
|
||||
|
||||
// 中间件解析会话。
|
||||
chain := svc.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
sess := SessionFromContext(r.Context())
|
||||
if sess == nil || !sess.IsAdmin {
|
||||
t.Errorf("中间件应解析出管理员会话,got=%v", sess)
|
||||
@@ -55,8 +65,10 @@ func TestLoginAndMiddleware(t *testing.T) {
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
|
||||
// req 保存req,供当前处理流程使用
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.AddCookie(&http.Cookie{Name: CookieName, Value: sid})
|
||||
// rec 保存rec,供当前处理流程使用
|
||||
rec := httptest.NewRecorder()
|
||||
chain.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
@@ -64,18 +76,24 @@ func TestLoginAndMiddleware(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRequireAuthAndAdmin 负责TestRequireAuthAndAdmin相关处理。
|
||||
func TestRequireAuthAndAdmin(t *testing.T) {
|
||||
// svc、cleanup 保存svc、cleanup,供当前处理流程使用
|
||||
svc, cleanup := newAuth(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
// sid 保存sid,供当前处理流程使用
|
||||
sid, _, _ := svc.Login(ctx, "admin", "pw")
|
||||
|
||||
// protected 保存protected,供当前处理流程使用
|
||||
protected := svc.Middleware(RequireAuth(RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(200)
|
||||
}))))
|
||||
|
||||
// 无 cookie → 401。
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
// rec 保存rec,供当前处理流程使用
|
||||
rec := httptest.NewRecorder()
|
||||
protected.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
@@ -85,6 +103,7 @@ func TestRequireAuthAndAdmin(t *testing.T) {
|
||||
// 有 admin cookie → 200。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req2.AddCookie(&http.Cookie{Name: CookieName, Value: sid})
|
||||
// rec2 保存rec2,供当前处理流程使用
|
||||
rec2 := httptest.NewRecorder()
|
||||
protected.ServeHTTP(rec2, req2)
|
||||
if rec2.Code != 200 {
|
||||
@@ -92,12 +111,16 @@ func TestRequireAuthAndAdmin(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetAndClearCookie 负责TestSetAndClear登录凭证相关处理。
|
||||
func TestSetAndClearCookie(t *testing.T) {
|
||||
// svc、cleanup 保存svc、cleanup,供当前处理流程使用
|
||||
svc, cleanup := newAuth(t)
|
||||
defer cleanup()
|
||||
|
||||
// rec 保存rec,供当前处理流程使用
|
||||
rec := httptest.NewRecorder()
|
||||
svc.SetSessionCookie(rec, "sid123")
|
||||
// c 保存c,供当前处理流程使用
|
||||
c := rec.Result().Cookies()
|
||||
if len(c) != 1 || c[0].Name != CookieName || c[0].Value != "sid123" || !c[0].HttpOnly {
|
||||
t.Fatalf("SetSessionCookie 异常: %+v", c)
|
||||
@@ -106,8 +129,10 @@ func TestSetAndClearCookie(t *testing.T) {
|
||||
t.Fatalf("SameSite 应为 Lax,got %v", c[0].SameSite)
|
||||
}
|
||||
|
||||
// rec2 保存rec2,供当前处理流程使用
|
||||
rec2 := httptest.NewRecorder()
|
||||
svc.ClearSessionCookie(rec2)
|
||||
// cc 保存cc,供当前处理流程使用
|
||||
cc := rec2.Result().Cookies()
|
||||
if len(cc) != 1 || cc[0].MaxAge != -1 {
|
||||
t.Fatalf("ClearSessionCookie 应 MaxAge=-1: %+v", cc)
|
||||
@@ -117,7 +142,9 @@ func TestSetAndClearCookie(t *testing.T) {
|
||||
// newEmptyStore 构造未初始化 admin 的测试 store,供 InitAdmin 测试。
|
||||
func newEmptyStore(t *testing.T) (*db.Store, func()) {
|
||||
t.Helper()
|
||||
// dbPath 保存db路径,供当前处理流程使用
|
||||
dbPath := filepath.Join(t.TempDir(), "init.db")
|
||||
// d、err 保存d、err,供当前处理流程使用
|
||||
d, _, err := db.Open(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
@@ -127,8 +154,10 @@ func newEmptyStore(t *testing.T) (*db.Store, func()) {
|
||||
|
||||
// TestInitAdmin_CreateThenReset 全新库创建 admin,二次调用走重置路径。
|
||||
func TestInitAdmin_CreateThenReset(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newEmptyStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
|
||||
// 全新库 → 创建。
|
||||
@@ -136,6 +165,7 @@ func TestInitAdmin_CreateThenReset(t *testing.T) {
|
||||
if err != nil || !created {
|
||||
t.Fatalf("首次 InitAdmin 应创建:created=%v err=%v", created, err)
|
||||
}
|
||||
// admin 保存admin,供当前处理流程使用
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if admin == nil || !admin.IsAdmin {
|
||||
t.Fatalf("admin 未正确创建/标记: %+v", admin)
|
||||
@@ -150,23 +180,29 @@ func TestInitAdmin_CreateThenReset(t *testing.T) {
|
||||
if err != nil || created2 {
|
||||
t.Fatalf("二次 InitAdmin 应重置:created=%v err=%v", created2, err)
|
||||
}
|
||||
if _, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw1"); ok {
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
_, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw1"); ok {
|
||||
t.Fatal("旧密码 pw1 应已失效")
|
||||
}
|
||||
if _, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw2"); !ok {
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
_, ok, _ := store.Users.VerifyAndUpgrade(ctx, "admin", "pw2"); !ok {
|
||||
t.Fatal("新密码 pw2 应可用")
|
||||
}
|
||||
}
|
||||
|
||||
// TestInitAdmin_DoesNotValidatePassword 密码强度校验由调用方负责(ensureAdmin),
|
||||
// InitAdmin 本身不拒绝空密码,仅保证不 panic 且能完成创建。
|
||||
// TestInitAdmin_DoesNotValidatePassword 负责TestInitAdminDoesNotValidate密码相关处理。
|
||||
func TestInitAdmin_DoesNotValidatePassword(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newEmptyStore(t)
|
||||
defer cleanup()
|
||||
if _, err := InitAdmin(context.Background(), store, "[email protected]", ""); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
_, err := InitAdmin(context.Background(), store, "[email protected]", ""); err != nil {
|
||||
t.Fatalf("InitAdmin 不应自行拒绝空密码: %v", err)
|
||||
}
|
||||
if admin, _ := store.Users.GetByUsername(context.Background(), "admin"); admin == nil {
|
||||
if // admin 保存admin,供当前处理流程使用
|
||||
admin, _ := store.Users.GetByUsername(context.Background(), "admin"); admin == nil {
|
||||
t.Fatal("空密码也应创建 admin")
|
||||
}
|
||||
}
|
||||
@@ -8,14 +8,18 @@ import (
|
||||
)
|
||||
|
||||
// Level is the process-wide dynamic slog level.
|
||||
// Level 保存Level,供当前处理流程使用
|
||||
var Level slog.LevelVar
|
||||
|
||||
// init 负责init相关处理。
|
||||
func init() {
|
||||
Level.Set(slog.LevelInfo)
|
||||
}
|
||||
|
||||
// NewLogger creates a slog logger wired to the dynamic Level.
|
||||
// NewLogger 负责NewLogger相关处理。
|
||||
func NewLogger(w io.Writer, format string) *slog.Logger {
|
||||
// opts 保存opts,供当前处理流程使用
|
||||
opts := &slog.HandlerOptions{Level: &Level}
|
||||
if strings.EqualFold(strings.TrimSpace(format), "json") {
|
||||
return slog.New(slog.NewJSONHandler(w, opts))
|
||||
@@ -24,7 +28,9 @@ func NewLogger(w io.Writer, format string) *slog.Logger {
|
||||
}
|
||||
|
||||
// SetLevel updates the process-wide log level.
|
||||
// SetLevel 设置Level。
|
||||
func SetLevel(raw string) error {
|
||||
// lv、err 保存lv、err,供当前处理流程使用
|
||||
lv, err := ParseLevel(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -34,6 +40,7 @@ func SetLevel(raw string) error {
|
||||
}
|
||||
|
||||
// ParseLevel parses debug/info/warn/error.
|
||||
// ParseLevel 解析Level。
|
||||
func ParseLevel(raw string) (slog.Level, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||
case "", "info":
|
||||
|
||||
@@ -7,9 +7,11 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestParseLevelAndSetLevel 负责TestParseLevelAndSetLevel相关处理。
|
||||
func TestParseLevelAndSetLevel(t *testing.T) {
|
||||
defer Level.Set(slog.LevelInfo)
|
||||
|
||||
// cases 保存cases,供当前处理流程使用
|
||||
cases := map[string]slog.Level{
|
||||
"": slog.LevelInfo,
|
||||
"debug": slog.LevelDebug,
|
||||
@@ -17,7 +19,9 @@ func TestParseLevelAndSetLevel(t *testing.T) {
|
||||
"warning": slog.LevelWarn,
|
||||
"error": slog.LevelError,
|
||||
}
|
||||
// in、want 表示当前遍历过程中的in、want
|
||||
for in, want := range cases {
|
||||
// got、err 保存got、err,供当前处理流程使用
|
||||
got, err := ParseLevel(in)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLevel(%q): %v", in, err)
|
||||
@@ -26,25 +30,32 @@ func TestParseLevelAndSetLevel(t *testing.T) {
|
||||
t.Fatalf("ParseLevel(%q)=%v want %v", in, got, want)
|
||||
}
|
||||
}
|
||||
if _, err := ParseLevel("verbose"); err == nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
_, err := ParseLevel("verbose"); err == nil {
|
||||
t.Fatal("invalid level should fail")
|
||||
}
|
||||
if err := SetLevel("debug"); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := SetLevel("debug"); err != nil {
|
||||
t.Fatalf("SetLevel: %v", err)
|
||||
}
|
||||
if got := Level.Level(); got != slog.LevelDebug {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
got := Level.Level(); got != slog.LevelDebug {
|
||||
t.Fatalf("global level=%v want debug", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewLoggerHonorsDynamicLevel 负责TestNewLoggerHonorsDynamicLevel相关处理。
|
||||
func TestNewLoggerHonorsDynamicLevel(t *testing.T) {
|
||||
defer Level.Set(slog.LevelInfo)
|
||||
// buf 保存buf,供当前处理流程使用
|
||||
var buf bytes.Buffer
|
||||
// logger 保存logger,供当前处理流程使用
|
||||
logger := NewLogger(&buf, "text")
|
||||
|
||||
Level.Set(slog.LevelWarn)
|
||||
logger.Info("hidden")
|
||||
logger.Warn("visible")
|
||||
// out 保存out,供当前处理流程使用
|
||||
out := buf.String()
|
||||
if strings.Contains(out, "hidden") {
|
||||
t.Fatalf("info log should be filtered: %s", out)
|
||||
|
||||
@@ -10,17 +10,21 @@ import (
|
||||
)
|
||||
|
||||
// ID returns a short stable fingerprint for a sensitive identifier.
|
||||
// ID 负责标识相关处理。
|
||||
func ID(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
// sum 保存sum,供当前处理流程使用
|
||||
sum := sha256.Sum256([]byte(s))
|
||||
return hex.EncodeToString(sum[:])[:12]
|
||||
}
|
||||
|
||||
// URL returns origin + path for URLs that may contain session tokens.
|
||||
// URL 负责URL相关处理。
|
||||
func URL(raw string) string {
|
||||
// u、err 保存u、err,供当前处理流程使用
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return "<redacted>"
|
||||
|
||||
@@ -2,6 +2,7 @@ package logsafe
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestRedactionHelpers 负责TestRedactionHelpers相关处理。
|
||||
func TestRedactionHelpers(t *testing.T) {
|
||||
if ID(" secret ") != ID("secret") || len(ID("secret")) != 12 {
|
||||
t.Fatal("ID should be trimmed, stable, and short")
|
||||
@@ -9,10 +10,12 @@ func TestRedactionHelpers(t *testing.T) {
|
||||
if ID("") != "" {
|
||||
t.Fatal("empty ID should remain empty")
|
||||
}
|
||||
if got := URL("https://example.com/path?q=token#secret"); got != "https://example.com/path" {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
got := URL("https://example.com/path?q=token#secret"); got != "https://example.com/path" {
|
||||
t.Fatalf("URL leaked query or fragment: %q", got)
|
||||
}
|
||||
if got := URL("not-a-url"); got != "<redacted>" {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
got := URL("not-a-url"); got != "<redacted>" {
|
||||
t.Fatalf("invalid URL = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// nonPublicPrefixes 保存nonPublicPrefixes,供当前处理流程使用
|
||||
var nonPublicPrefixes = []netip.Prefix{
|
||||
netip.MustParsePrefix("0.0.0.0/8"), netip.MustParsePrefix("10.0.0.0/8"),
|
||||
netip.MustParsePrefix("100.64.0.0/10"), netip.MustParsePrefix("127.0.0.0/8"),
|
||||
@@ -28,6 +29,7 @@ var nonPublicPrefixes = []netip.Prefix{
|
||||
|
||||
// PublicHTTPClient 返回只允许连接公网 IP 的客户端。DNS 与每次重定向都会重新校验。
|
||||
func PublicHTTPClient(timeout time.Duration) *http.Client {
|
||||
// transport 保存transport,供当前处理流程使用
|
||||
transport := &http.Transport{
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
return DialPublicContext(ctx, network, address, 10*time.Second)
|
||||
@@ -51,7 +53,9 @@ func PublicHTTPClient(timeout time.Duration) *http.Client {
|
||||
|
||||
// TrustedEndpointHTTPClient 用于管理员明确配置的集成端点。目标地址完全由管理员
|
||||
// 信任并负责,因此不限制 IP 类型、DNS 结果或 HTTP 重定向;仅校验 HTTP(S) URL。
|
||||
// TrustedEndpointHTTPClient 负责TrustedEndpointHTTPClient相关处理。
|
||||
func TrustedEndpointHTTPClient(rawBaseURL string, timeout time.Duration) (*http.Client, error) {
|
||||
// baseURL、err 保存baseURL、err,供当前处理流程使用
|
||||
baseURL, err := url.Parse(strings.TrimSpace(rawBaseURL))
|
||||
if err != nil || baseURL.Hostname() == "" {
|
||||
return nil, fmt.Errorf("服务地址无效")
|
||||
@@ -59,6 +63,7 @@ func TrustedEndpointHTTPClient(rawBaseURL string, timeout time.Duration) (*http.
|
||||
if baseURL.Scheme != "http" && baseURL.Scheme != "https" {
|
||||
return nil, fmt.Errorf("服务地址只支持 http 或 https")
|
||||
}
|
||||
// transport 保存transport,供当前处理流程使用
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
return &http.Client{
|
||||
Transport: transport,
|
||||
@@ -66,7 +71,9 @@ func TrustedEndpointHTTPClient(rawBaseURL string, timeout time.Duration) (*http.
|
||||
}, nil
|
||||
}
|
||||
|
||||
// IsPublicIP 负责IsPublicIP相关处理。
|
||||
func IsPublicIP(ip net.IP) bool {
|
||||
// addr、ok 保存addr、ok,供当前处理流程使用
|
||||
addr, ok := netip.AddrFromSlice(ip)
|
||||
if !ok {
|
||||
return false
|
||||
@@ -75,6 +82,7 @@ func IsPublicIP(ip net.IP) bool {
|
||||
if !addr.IsGlobalUnicast() {
|
||||
return false
|
||||
}
|
||||
// prefix 表示当前遍历过程中的prefix
|
||||
for _, prefix := range nonPublicPrefixes {
|
||||
if prefix.Contains(addr) {
|
||||
return false
|
||||
@@ -89,23 +97,31 @@ func DialPublicContext(ctx context.Context, network, address string, timeout tim
|
||||
"拒绝访问非公网地址", "连接公网地址失败")
|
||||
}
|
||||
|
||||
// dialContextWithPolicy 负责dial上下文WithPolicy相关处理。
|
||||
func dialContextWithPolicy(ctx context.Context, network, address string, timeout time.Duration,
|
||||
allow func(net.IP) bool, deniedMessage, connectErrorMessage string,
|
||||
) (net.Conn, error) {
|
||||
// host、port、err 保存host、port、err,供当前处理流程使用
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// ips、err 保存ips、err,供当前处理流程使用
|
||||
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// dialer 保存dialer,供当前处理流程使用
|
||||
dialer := &net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second}
|
||||
// lastErr 保存lastErr,供当前处理流程使用
|
||||
var lastErr error
|
||||
// foundAllowed 保存foundAllowed,供当前处理流程使用
|
||||
foundAllowed := false
|
||||
// resolved 表示当前遍历过程中的resolved
|
||||
for _, resolved := range ips {
|
||||
if allow(resolved.IP) {
|
||||
foundAllowed = true
|
||||
// conn、dialErr 保存conn、dialErr,供当前处理流程使用
|
||||
conn, dialErr := dialer.DialContext(ctx, network, net.JoinHostPort(resolved.IP.String(), port))
|
||||
if dialErr == nil {
|
||||
return conn, nil
|
||||
|
||||
@@ -9,7 +9,9 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestIsPublicIP 负责TestIsPublicIP相关处理。
|
||||
func TestIsPublicIP(t *testing.T) {
|
||||
// raw 表示当前遍历过程中的原始
|
||||
for _, raw := range []string{
|
||||
"127.0.0.1", "10.0.0.1", "172.16.1.1", "192.168.1.1", "169.254.169.254", "::1",
|
||||
"100.64.0.1", "198.18.0.1", "192.0.2.1", "198.51.100.1", "203.0.113.1", "2001:db8::1",
|
||||
@@ -23,30 +25,41 @@ func TestIsPublicIP(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublicHTTPClientRejectsLoopback 负责TestPublicHTTPClientRejectsLoopback相关处理。
|
||||
func TestPublicHTTPClientRejectsLoopback(t *testing.T) {
|
||||
// client 保存client,供当前处理流程使用
|
||||
client := PublicHTTPClient(0)
|
||||
// req 保存req,供当前处理流程使用
|
||||
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://127.0.0.1:1", nil)
|
||||
if _, err := client.Do(req); err == nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
_, err := client.Do(req); err == nil {
|
||||
t.Fatal("loopback request must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrustedEndpointHTTPClientAllowsLoopbackAndUnspecifiedAddress 负责TestTrustedEndpointHTTPClientAllowsLoopbackAndUnspecifiedAddress相关处理。
|
||||
func TestTrustedEndpointHTTPClientAllowsLoopbackAndUnspecifiedAddress(t *testing.T) {
|
||||
// server 保存server,供当前处理流程使用
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
// port、err 保存port、err,供当前处理流程使用
|
||||
_, port, err := net.SplitHostPort(strings.TrimPrefix(server.URL, "http://"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// host 表示当前遍历过程中的host
|
||||
for _, host := range []string{"127.0.0.1", "0.0.0.0"} {
|
||||
// baseURL 保存baseURL,供当前处理流程使用
|
||||
baseURL := "http://" + net.JoinHostPort(host, port)
|
||||
// client、clientErr 保存client、clientErr,供当前处理流程使用
|
||||
client, clientErr := TrustedEndpointHTTPClient(baseURL+"/v1", 0)
|
||||
if clientErr != nil {
|
||||
t.Fatal(clientErr)
|
||||
}
|
||||
// resp、requestErr 保存resp、requestErr,供当前处理流程使用
|
||||
resp, requestErr := client.Get(baseURL + "/v1/models")
|
||||
if requestErr != nil {
|
||||
t.Fatalf("trusted endpoint should reach %s: %v", host, requestErr)
|
||||
@@ -58,11 +71,14 @@ func TestTrustedEndpointHTTPClientAllowsLoopbackAndUnspecifiedAddress(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrustedEndpointHTTPClientDoesNotApplyAddressPolicy 负责TestTrustedEndpointHTTPClientDoesNotApplyAddressPolicy相关处理。
|
||||
func TestTrustedEndpointHTTPClientDoesNotApplyAddressPolicy(t *testing.T) {
|
||||
// raw 表示当前遍历过程中的原始
|
||||
for _, raw := range []string{
|
||||
"http://0.0.0.0:8080/v1", "http://127.0.0.1:8080/v1", "http://169.254.169.254/v1",
|
||||
"http://192.168.0.220/v1", "http://[::1]:8080/v1", "https://user:[email protected]/v1",
|
||||
} {
|
||||
// client、err 保存client、err,供当前处理流程使用
|
||||
client, err := TrustedEndpointHTTPClient(raw, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("admin-configured address should be accepted (%s): %v", raw, err)
|
||||
@@ -73,9 +89,12 @@ func TestTrustedEndpointHTTPClientDoesNotApplyAddressPolicy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrustedEndpointHTTPClientValidatesBaseURL 负责TestTrustedEndpointHTTPClientValidatesBaseURL相关处理。
|
||||
func TestTrustedEndpointHTTPClientValidatesBaseURL(t *testing.T) {
|
||||
// raw 表示当前遍历过程中的原始
|
||||
for _, raw := range []string{"", "file:///tmp/model", "://bad"} {
|
||||
if _, err := TrustedEndpointHTTPClient(raw, 0); err == nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
_, err := TrustedEndpointHTTPClient(raw, 0); err == nil {
|
||||
t.Fatalf("invalid base URL should fail: %q", raw)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package version
|
||||
|
||||
import "strings"
|
||||
|
||||
// Version 保存Version,供当前处理流程使用
|
||||
var (
|
||||
Version = "dev"
|
||||
Commit = "unknown"
|
||||
@@ -10,7 +11,9 @@ var (
|
||||
)
|
||||
|
||||
// ShortCommit returns a compact commit identifier suitable for UI display.
|
||||
// ShortCommit 负责ShortCommit相关处理。
|
||||
func ShortCommit() string {
|
||||
// commit 保存commit,供当前处理流程使用
|
||||
commit := strings.TrimSpace(Commit)
|
||||
if len(commit) > 12 {
|
||||
return commit[:12]
|
||||
|
||||
@@ -2,12 +2,15 @@ package version
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestShortCommit 负责TestShortCommit相关处理。
|
||||
func TestShortCommit(t *testing.T) {
|
||||
// original 保存original,供当前处理流程使用
|
||||
original := Commit
|
||||
t.Cleanup(func() { Commit = original })
|
||||
|
||||
Commit = "0123456789abcdef"
|
||||
if got := ShortCommit(); got != "0123456789ab" {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
got := ShortCommit(); got != "0123456789ab" {
|
||||
t.Fatalf("ShortCommit() = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,13 @@ import (
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
// files 保存文件列表,供当前处理流程使用
|
||||
//
|
||||
//go:embed static/*
|
||||
var files embed.FS
|
||||
|
||||
// Static returns the embedded built frontend rooted at static/.
|
||||
// Static 负责Static相关处理。
|
||||
func Static() (fs.FS, error) {
|
||||
return fs.Sub(files, "static")
|
||||
}
|
||||
@@ -5,11 +5,14 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestStaticContainsIndex 负责TestStaticContainsIndex相关处理。
|
||||
func TestStaticContainsIndex(t *testing.T) {
|
||||
// static、err 保存static、err,供当前处理流程使用
|
||||
static, err := Static()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// data、err 保存data、err,供当前处理流程使用
|
||||
data, err := fs.ReadFile(static, "index.html")
|
||||
if err != nil || len(data) == 0 {
|
||||
t.Fatalf("embedded index missing: %v", err)
|
||||
|
||||
Reference in new issue
Block a user