Debian Codegraph @

filesystem/fs.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package filesystem
5
6 import (
7 "errors"
8 "path/filepath"
9 "strings"
10 )
11
12 var (
13 // ErrOutsideRepo is returned when the target file is outside of the repository
14 ErrOutsideRepo = errors.New("target file outside repository")
15 )
16
17 // EvaluateFilePath sanitize and validate the file against the local repository
18 func EvaluateFilePath(repository, urlpath string) (string, error) {
19 fpath := repository + urlpath
20
21 // Get the absolute file path
22 fpath, err := filepath.Abs(fpath)
23 if err != nil {
24 return "", err
25 }
26
27 // Check if absolute path is within the repository
28 if !IsInRepository(repository, fpath) {
29 return "", ErrOutsideRepo
30 }
31
32 // Evaluate symlinks
33 targetPath, err := filepath.EvalSymlinks(fpath)
34 if err != nil {
35 return "", err
36 }
37 if targetPath != fpath {
38 targetPath, err = filepath.Abs(targetPath)
39 if err != nil {
40 return "", err
41 }
42 if !IsInRepository(repository, targetPath) {
43 return "", ErrOutsideRepo
44 }
45 return targetPath[len(repository):], nil
46 }
47 return fpath[len(repository):], nil
48 }
49
50 // IsInRepository ensures that the given file path is contained in the repository
51 func IsInRepository(repository, filePath string) bool {
52 if filePath == repository {
53 return true
54 }
55 if strings.HasPrefix(filePath, repository+"/") {
56 return true
57 }
58 return false
59 }