Skip to content

Commit

Permalink
Fix: use X-Cr- as custom header prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
HFO4 committed Nov 23, 2021
1 parent 865a801 commit 3948ee7
Show file tree
Hide file tree
Showing 12 changed files with 36 additions and 35 deletions.
8 changes: 4 additions & 4 deletions middleware/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import (
// MasterMetadata 解析主机节点发来请求的包含主机节点信息的元数据
func MasterMetadata() gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("MasterSiteID", c.GetHeader("X-Site-Id"))
c.Set("MasterSiteURL", c.GetHeader("X-Site-Url"))
c.Set("MasterVersion", c.GetHeader("X-Cloudreve-Version"))
c.Set("MasterSiteID", c.GetHeader("X-Cr-Site-Id"))
c.Set("MasterSiteURL", c.GetHeader("X-Cr-Site-Url"))
c.Set("MasterVersion", c.GetHeader("X-Cr-Cloudreve-Version"))
c.Next()
}
}
Expand Down Expand Up @@ -41,7 +41,7 @@ func UseSlaveAria2Instance(clusterController cluster.Controller) gin.HandlerFunc

func SlaveRPCSignRequired(nodePool cluster.Pool) gin.HandlerFunc {
return func(c *gin.Context) {
nodeID, err := strconv.ParseUint(c.GetHeader("X-Node-Id"), 10, 64)
nodeID, err := strconv.ParseUint(c.GetHeader("X-Cr-Node-Id"), 10, 64)
if err != nil {
c.JSON(200, serializer.ParamErr("未知的主机节点ID", err))
c.Abort()
Expand Down
12 changes: 6 additions & 6 deletions middleware/cluster_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ func TestMasterMetadata(t *testing.T) {
c.Request = httptest.NewRequest("GET", "/", nil)

c.Request.Header = map[string][]string{
"X-Site-Id": {"expectedSiteID"},
"X-Site-Url": {"expectedSiteURL"},
"X-Cloudreve-Version": {"expectedMasterVersion"},
"X-Cr-Site-Id": {"expectedSiteID"},
"X-Cr-Site-Url": {"expectedSiteURL"},
"X-Cr-Cloudreve-Version": {"expectedMasterVersion"},
}
masterMetaDataFunc(c)
siteID, _ := c.Get("MasterSiteID")
Expand All @@ -47,7 +47,7 @@ func TestSlaveRPCSignRequired(t *testing.T) {
{
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest("GET", "/", nil)
c.Request.Header.Set("X-Node-Id", "unknown")
c.Request.Header.Set("X-Cr-Node-Id", "unknown")
slaveRPCSignRequiredFunc(c)
a.True(c.IsAborted())
}
Expand All @@ -56,7 +56,7 @@ func TestSlaveRPCSignRequired(t *testing.T) {
{
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest("GET", "/", nil)
c.Request.Header.Set("X-Node-Id", "38")
c.Request.Header.Set("X-Cr-Node-Id", "38")
slaveRPCSignRequiredFunc(c)
a.True(c.IsAborted())
}
Expand All @@ -70,7 +70,7 @@ func TestSlaveRPCSignRequired(t *testing.T) {

c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest("POST", "/", nil)
c.Request.Header.Set("X-Node-Id", "38")
c.Request.Header.Set("X-Cr-Node-Id", "38")
c.Request = auth.SignRequest(authInstance, c.Request, 0)
slaveRPCSignRequiredFunc(c)
a.False(c.IsAborted())
Expand Down
3 changes: 2 additions & 1 deletion models/scripts/invoker/invoker.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"github.com/cloudreve/Cloudreve/v3/pkg/util"
"strings"
)

type DBScript interface {
Expand All @@ -29,7 +30,7 @@ func Register(name string, script DBScript) {
func ListPrefix(prefix string) []string {
var scripts []string
for name := range availableScripts {
if name[:len(prefix)] == prefix {
if strings.HasPrefix(name, prefix) {
scripts = append(scripts, name)
}
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type Auth interface {
}

// SignRequest 对PUT\POST等复杂HTTP请求签名,只会对URI部分、
// 请求正文、`X-`开头的header进行签名
// 请求正文、`X-Cr-`开头的header进行签名
func SignRequest(instance Auth, r *http.Request, expires int64) *http.Request {
// 处理有效期
if expires > 0 {
Expand Down Expand Up @@ -69,7 +69,7 @@ func CheckRequest(instance Auth, r *http.Request) error {
func getSignContent(r *http.Request) (rawSignString string) {
// 读取所有body正文
var body = []byte{}
if _, ok := r.Header["X-Policy"]; !ok {
if _, ok := r.Header["X-Cr-Policy"]; !ok {
if r.Body != nil {
body, _ = ioutil.ReadAll(r.Body)
_ = r.Body.Close()
Expand All @@ -80,7 +80,7 @@ func getSignContent(r *http.Request) (rawSignString string) {
// 决定要签名的header
var signedHeader []string
for k, _ := range r.Header {
if strings.HasPrefix(k, "X-") && k != "X-Filename" {
if strings.HasPrefix(k, "X-Cr-") && k != "X-Cr-Filename" {
signedHeader = append(signedHeader, fmt.Sprintf("%s=%s", k, r.Header.Get(k)))
}
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func TestSignRequest(t *testing.T) {
strings.NewReader("I am body."),
)
asserts.NoError(err)
req.Header["X-Policy"] = []string{"I am Policy"}
req.Header["X-Cr-Policy"] = []string{"I am Policy"}
req = SignRequest(General, req, 10)
asserts.NotEmpty(req.Header["Authorization"])
}
Expand Down Expand Up @@ -114,7 +114,7 @@ func TestCheckRequest(t *testing.T) {
strings.NewReader("I am body."),
)
asserts.NoError(err)
req.Header["X-Policy"] = []string{"I am Policy"}
req.Header["X-Cr-Policy"] = []string{"I am Policy"}
req = SignRequest(General, req, 0)
err = CheckRequest(General, req)
asserts.NoError(err)
Expand Down
2 changes: 1 addition & 1 deletion pkg/conf/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ var CaptchaConfig = &captcha{
var CORSConfig = &cors{
AllowOrigins: []string{"UNSET"},
AllowMethods: []string{"PUT", "POST", "GET", "OPTIONS"},
AllowHeaders: []string{"Cookie", "X-Policy", "Authorization", "Content-Length", "Content-Type", "X-Path", "X-FileName"},
AllowHeaders: []string{"Cookie", "X-Cr-Policy", "Authorization", "Content-Length", "Content-Type", "X-Path", "X-FileName"},

This comment has been minimized.

Copy link
@WeidiDeng

WeidiDeng Nov 25, 2021

Member

最后两个X-Path, X-FileName没有添加X-Cr前缀

This comment has been minimized.

Copy link
@HFO4

HFO4 Nov 26, 2021

Author Member

感谢 已经补上了。还好不会影响太多client

AllowCredentials: false,
ExposeHeaders: nil,
}
Expand Down
10 changes: 5 additions & 5 deletions pkg/filesystem/driver/remote/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,9 @@ func (handler Driver) Put(ctx context.Context, file io.ReadCloser, dst string, s
handler.Policy.GetUploadURL(),
file,
request.WithHeader(map[string][]string{
"X-Policy": {credential.Policy},
"X-FileName": {fileName},
"X-Overwrite": {overwrite},
"X-Cr-Policy": {credential.Policy},
"X-Cr-FileName": {fileName},
"X-Cr-Overwrite": {overwrite},
}),
request.WithContentLength(int64(size)),
request.WithTimeout(time.Duration(0)),
Expand Down Expand Up @@ -332,8 +332,8 @@ func (handler Driver) getUploadCredential(ctx context.Context, policy serializer
// 签名上传策略
uploadRequest, _ := http.NewRequest("POST", "/api/v3/slave/upload", nil)
uploadRequest.Header = map[string][]string{
"X-Policy": {policyEncoded},
"X-Overwrite": {"false"},
"X-Cr-Policy": {policyEncoded},
"X-Cr-Overwrite": {"false"},
}
auth.SignRequest(handler.AuthInstance, uploadRequest, TTL)

Expand Down
8 changes: 4 additions & 4 deletions pkg/request/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,13 @@ func (c HTTPClient) Request(method, target string, body io.Reader, opts ...Optio
}

if options.masterMeta && conf.SystemConfig.Mode == "master" {
req.Header.Add("X-Site-Url", model.GetSiteURL().String())
req.Header.Add("X-Site-Id", model.GetSettingByName("siteID"))
req.Header.Add("X-Cloudreve-Version", conf.BackendVersion)
req.Header.Add("X-Cr-Site-Url", model.GetSiteURL().String())
req.Header.Add("X-Cr-Site-Id", model.GetSettingByName("siteID"))
req.Header.Add("X-Cr-Cloudreve-Version", conf.BackendVersion)
}

if options.slaveNodeID != "" && conf.SystemConfig.Mode == "slave" {
req.Header.Add("X-Node-Id", options.slaveNodeID)
req.Header.Add("X-Cr-Node-Id", options.slaveNodeID)
}

if options.contentLength != -1 {
Expand Down
4 changes: 2 additions & 2 deletions routers/controllers/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,8 +308,8 @@ func FileUploadStream(c *gin.Context) {
}

// 解码文件名和路径
fileName, err := url.QueryUnescape(c.Request.Header.Get("X-FileName"))
filePath, err := url.QueryUnescape(c.Request.Header.Get("X-Path"))
fileName, err := url.QueryUnescape(c.Request.Header.Get("X-Cr-FileName"))
filePath, err := url.QueryUnescape(c.Request.Header.Get("X-Cr-Path"))
if err != nil {
c.JSON(200, ErrorResponse(err))
return
Expand Down
6 changes: 3 additions & 3 deletions routers/controllers/slave.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func SlaveUpload(c *gin.Context) {
fs.Handler = local.Driver{}

// 从请求中取得上传策略
uploadPolicyRaw := c.GetHeader("X-Policy")
uploadPolicyRaw := c.GetHeader("X-Cr-Policy")
if uploadPolicyRaw == "" {
c.JSON(200, serializer.ParamErr("未指定上传策略", nil))
return
Expand All @@ -54,7 +54,7 @@ func SlaveUpload(c *gin.Context) {
}

// 解码文件名和路径
fileName, err := url.QueryUnescape(c.Request.Header.Get("X-FileName"))
fileName, err := url.QueryUnescape(c.Request.Header.Get("X-Cr-FileName"))
if err != nil {
c.JSON(200, ErrorResponse(err))
return
Expand All @@ -74,7 +74,7 @@ func SlaveUpload(c *gin.Context) {
fs.Use("AfterValidateFailed", filesystem.HookDeleteTempFile)

// 是否允许覆盖
if c.Request.Header.Get("X-Overwrite") == "false" {
if c.Request.Header.Get("X-Cr-Overwrite") == "false" {
ctx = context.WithValue(ctx, fsctx.DisableOverwrite, true)
}

Expand Down
6 changes: 3 additions & 3 deletions routers/file_router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func TestLocalFileUpload(t *testing.T) {
strings.NewReader("2333"),
)
req.Header.Add("Content-Length", "4")
req.Header.Add("X-FileName", "大地的%sfsf")
req.Header.Add("X-Cr-FileName", "大地的%sfsf")
return req
},
ExpectCode: 40002,
Expand All @@ -87,8 +87,8 @@ func TestLocalFileUpload(t *testing.T) {
strings.NewReader("2333"),
)
req.Header.Add("Content-Length", "4")
req.Header.Add("X-FileName", "TestFileUploadRoute.txt")
req.Header.Add("X-Path", "/")
req.Header.Add("X-Cr-FileName", "TestFileUploadRoute.txt")
req.Header.Add("X-Cr-Path", "/")
return req
},
ExpectCode: 0,
Expand Down

0 comments on commit 3948ee7

Please sign in to comment.