ci: 复用部署服务器缓存并支持 HTTPS 同源登录

This commit is contained in:
2026-10-09 21:11:44 +08:00
parent 2cad6d7533
commit ac936d2a1a
14 changed files with 158 additions and 47 deletions
+8
View File
@@ -14,6 +14,7 @@ import (
type Config struct {
PythonExecutable string
PublicOrigin string
Logging logging.Options
Environment, HTTPAddr string
PGHost, PGPort, PGDatabase, PGUser, PGPassword, PGSSLMode, PGAdminDatabase string
@@ -62,6 +63,13 @@ func LoadEnvFile(path string) error {
func Load() (Config, error) {
c := Config{Environment: env("APP_ENV", "local"), HTTPAddr: env("HTTP_ADDR", "127.0.0.1:8080"), PGHost: env("PGHOST", "192.168.100.127"), PGPort: env("PGPORT", "5432"), PGDatabase: env("PGDATABASE", "veyra"), PGUser: os.Getenv("PGUSER"), PGPassword: os.Getenv("PGPASSWORD"), PGSSLMode: env("PGSSLMODE", "disable"), PGAdminDatabase: env("PGADMIN_DATABASE", "postgres"), RedisAddr: env("REDIS_ADDR", "192.168.100.127:6379"), RedisUsername: os.Getenv("REDIS_USERNAME"), RedisPassword: os.Getenv("REDIS_PASSWORD")}
c.PythonExecutable = env("PYTHON_EXECUTABLE", "python3")
c.PublicOrigin = os.Getenv("PUBLIC_ORIGIN")
if c.PublicOrigin != "" {
origin, err := url.Parse(c.PublicOrigin)
if err != nil || (origin.Scheme != "http" && origin.Scheme != "https") || origin.Hostname() == "" || origin.User != nil || origin.Path != "" || origin.RawQuery != "" || origin.Fragment != "" || origin.Opaque != "" || origin.Scheme+"://"+origin.Host != c.PublicOrigin {
return Config{}, fmt.Errorf("PUBLIC_ORIGIN must be an http or https origin without a path")
}
}
c.Logging = logging.Options{Directory: env("LOG_DIR", "logs"), Level: env("LOG_LEVEL", "info"), MaxSizeMB: 50, MaxBackups: 10, MaxAgeDays: 14}
for key, dest := range map[string]*int{"LOG_MAX_SIZE_MB": &c.Logging.MaxSizeMB, "LOG_MAX_BACKUPS": &c.Logging.MaxBackups, "LOG_MAX_AGE_DAYS": &c.Logging.MaxAgeDays} {
if value := os.Getenv(key); value != "" {
+25
View File
@@ -23,3 +23,28 @@ func TestRejectInvalidRedisDB(t *testing.T) {
t.Fatal("negative database must be rejected")
}
}
func TestPublicOriginConfiguration(t *testing.T) {
for _, tc := range []struct {
origin string
valid bool
}{
{"", true},
{"https://veyra.sundynix.cn", true},
{"http://localhost:8080", true},
{"https://veyra.sundynix.cn/", false},
{"https://veyra.sundynix.cn?", false},
{"https://veyra.sundynix.cn#", false},
{"https://user:password@veyra.sundynix.cn", false},
{"ftp://veyra.sundynix.cn", false},
{"https:///missing-host", false},
} {
t.Run(tc.origin, func(t *testing.T) {
t.Setenv("PUBLIC_ORIGIN", tc.origin)
_, err := Load()
if (err == nil) != tc.valid {
t.Fatalf("valid=%v error=%v", tc.valid, err)
}
})
}
}
+6
View File
@@ -35,10 +35,13 @@ type IdentityOptions struct {
Limiter LoginLimiter
DevelopmentLogin bool
SecureCookie bool
PublicOrigin string
}
const sessionCookie = "veyra_admin_session"
type publicOriginContextKey struct{}
func bindIdentity(r *gin.Engine, options IdentityOptions) {
r.SetTrustedProxies(nil)
adminAuth := func(c *gin.Context) { authenticate(c, options, "admin") }
@@ -210,6 +213,9 @@ func sameOrigin(r *http.Request) bool {
if err != nil || origin.Host == "" || origin.User != nil || origin.Path != "" || origin.RawQuery != "" || origin.Fragment != "" {
return false
}
if expected, _ := r.Context().Value(publicOriginContextKey{}).(string); expected != "" {
return origin.Host == r.Host && origin.Scheme+"://"+origin.Host == expected
}
scheme := "http"
if r.TLS != nil {
scheme = "https"
+32
View File
@@ -49,3 +49,35 @@ func TestDevelopmentLoginDisabledByDefault(t *testing.T) {
t.Fatal("development login open outside explicitly enabled environment")
}
}
func TestHTTPSPublicOriginBehindProxy(t *testing.T) {
auth, err := service.NewAuthService(nil)
if err != nil {
t.Fatal(err)
}
probe := func(context.Context) error { return nil }
for _, tc := range []struct {
name, publicOrigin, host, origin, forwardedProto string
status int
}{
{"configured HTTPS", "https://veyra.sundynix.cn", "veyra.sundynix.cn", "https://veyra.sundynix.cn", "https", 503},
{"no reliance on proxy header", "https://veyra.sundynix.cn", "veyra.sundynix.cn", "https://veyra.sundynix.cn", "", 503},
{"foreign origin", "https://veyra.sundynix.cn", "veyra.sundynix.cn", "https://evil.example", "https", 403},
{"HTTP origin rejected", "https://veyra.sundynix.cn", "veyra.sundynix.cn", "http://veyra.sundynix.cn", "https", 403},
{"wrong host", "https://veyra.sundynix.cn", "evil.example", "https://veyra.sundynix.cn", "https", 403},
{"spoofed proxy header", "", "veyra.sundynix.cn", "https://veyra.sundynix.cn", "https", 403},
} {
t.Run(tc.name, func(t *testing.T) {
router := NewRouter(service.NewHealthService(probe, probe), zap.NewNop(), IdentityOptions{Auth: auth, DevelopmentLogin: true, PublicOrigin: tc.publicOrigin})
req := httptest.NewRequest(http.MethodPost, "http://"+tc.host+"/api/admin/v1/auth/login", strings.NewReader(`{"login_name":"admin","password":"test-password"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Origin", tc.origin)
req.Header.Set("X-Forwarded-Proto", tc.forwardedProto)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != tc.status {
t.Fatalf("got %d want %d", rec.Code, tc.status)
}
})
}
}
+3
View File
@@ -21,6 +21,9 @@ func NewRouter(health *service.HealthService, logger *zap.Logger, identity Ident
r.Use(func(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
if identity.PublicOrigin != "" {
ctx = context.WithValue(ctx, publicOriginContextKey{}, identity.PublicOrigin)
}
c.Request = c.Request.WithContext(ctx)
requestID := uuid.NewString()
c.Header("X-Request-ID", requestID)