Skip to content

Commit 5c73c63

Browse files
committed
add more test
1 parent 0904421 commit 5c73c63

File tree

2 files changed

+46
-7
lines changed

2 files changed

+46
-7
lines changed

modules/storage/local.go

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@ package storage
77
import (
88
"context"
99
"errors"
10+
"fmt"
1011
"io"
1112
"net/url"
1213
"os"
1314
"path/filepath"
15+
"strings"
1416

1517
"code.gitea.io/gitea/modules/log"
1618
"code.gitea.io/gitea/modules/util"
@@ -62,15 +64,15 @@ func NewLocalStorage(ctx context.Context, cfg interface{}) (ObjectStorage, error
6264

6365
// Open a file
6466
func (l *LocalStorage) Open(path string) (Object, error) {
65-
if !l.isValid(path) {
67+
if !isLocalPathValid(path) {
6668
return nil, ErrLocalPathNotSupported
6769
}
6870
return os.Open(filepath.Join(l.dir, path))
6971
}
7072

7173
// Save a file
7274
func (l *LocalStorage) Save(path string, r io.Reader, size int64) (int64, error) {
73-
if !l.isValid(path) {
75+
if !isLocalPathValid(path) {
7476
return 0, ErrLocalPathNotSupported
7577
}
7678

@@ -117,17 +119,17 @@ func (l *LocalStorage) Stat(path string) (os.FileInfo, error) {
117119
return os.Stat(filepath.Join(l.dir, path))
118120
}
119121

120-
func (l *LocalStorage) isValid(path string) bool {
121-
a, err := filepath.Abs(path)
122-
if err != nil {
122+
func isLocalPathValid(path string) bool {
123+
a := filepath.Clean(path)
124+
if strings.HasPrefix(a, fmt.Sprintf("..%c", filepath.Separator)) {
123125
return false
124126
}
125-
return a == "/"+path
127+
return a == path
126128
}
127129

128130
// Delete delete a file
129131
func (l *LocalStorage) Delete(path string) error {
130-
if !l.isValid(path) {
132+
if !isLocalPathValid(path) {
131133
return ErrLocalPathNotSupported
132134
}
133135
p := filepath.Join(l.dir, path)

modules/storage/local_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Copyright 2022 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package storage
6+
7+
import (
8+
"testing"
9+
10+
"github.com/stretchr/testify/assert"
11+
)
12+
13+
func TestLocalPathIsValid(t *testing.T) {
14+
var kases = []struct{
15+
path string
16+
valid bool
17+
} {
18+
{
19+
"a/0/a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a14",
20+
true,
21+
},
22+
{
23+
"../a/0/a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a14",
24+
false,
25+
},
26+
{
27+
"b/../a/0/a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a14",
28+
false,
29+
},
30+
}
31+
32+
for _, k := range kases {
33+
t.Run(k.path, func(t *testing.T) {
34+
assert.EqualValues(t, k.valid, isLocalPathValid(k.path))
35+
})
36+
}
37+
}

0 commit comments

Comments
 (0)