refactor(template): Enhance template loading security and error messages

This commit is contained in:
2025-10-15 16:40:07 +11:00
parent fce75baed4
commit 23a85f573b
4 changed files with 27 additions and 11 deletions

View File

@@ -3,11 +3,27 @@ package common
import (
"io"
"os"
"path/filepath"
"strings"
)
func LoadTemplate(templatePath string) ([]byte, error) {
if _, err := os.Stat(templatePath); err == nil {
file, err := os.Open(templatePath)
const templatesDir = "templates"
// LoadTemplate 只读取运行目录下的 templates 目录,防止其他文件内容泄漏
func LoadTemplate(templateName string) ([]byte, error) {
// 清理路径,防止目录遍历攻击
cleanTemplateName := filepath.Clean(templateName)
// 检查是否尝试访问父目录
if strings.HasPrefix(cleanTemplateName, "..") || strings.Contains(cleanTemplateName, string(filepath.Separator)+".."+string(filepath.Separator)) {
return nil, NewFileNotFoundError(templateName) // 拒绝包含父目录的路径
}
// 构建完整路径,确保只从 templates 目录读取
fullPath := filepath.Join(templatesDir, cleanTemplateName)
if _, err := os.Stat(fullPath); err == nil {
file, err := os.Open(fullPath)
if err != nil {
return nil, err
}
@@ -22,5 +38,5 @@ func LoadTemplate(templatePath string) ([]byte, error) {
}
return result, nil
}
return nil, NewFileNotFoundError(templatePath)
return nil, NewFileNotFoundError(templateName)
}