-
-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathsecurity_utils.go
More file actions
118 lines (92 loc) · 2.16 KB
/
Copy pathsecurity_utils.go
File metadata and controls
118 lines (92 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package utils
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net"
"regexp"
"strings"
"github.com/google/uuid"
)
var (
ErrFilterEmpty = errors.New("filter is empty")
)
func GetSecret(conf string, file string) string {
if conf == "" && file == "" {
return ""
}
if conf != "" {
return conf
}
contents, err := ReadFile(file)
if err != nil {
return ""
}
return ParseSecretFile(contents)
}
func ParseSecretFile(contents string) string {
lines := strings.Split(contents, "\n")
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
return strings.TrimSpace(line)
}
return ""
}
func EncodeBasicAuth(username string, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
func CheckIPFilter(filter string, ip string) (bool, error) {
ipAddr := net.ParseIP(ip)
if ipAddr == nil {
return false, fmt.Errorf("invalid ip address")
}
filter = strings.ReplaceAll(filter, "-", "/")
if strings.Contains(filter, "/") {
_, cidr, err := net.ParseCIDR(filter)
if err != nil {
return false, fmt.Errorf("invalid cidr notation: %w", err)
}
return cidr.Contains(ipAddr), nil
}
ipFilter := net.ParseIP(filter)
if ipFilter == nil {
return false, fmt.Errorf("invalid ip address")
}
if ipFilter.Equal(ipAddr) {
return true, nil
}
return false, nil
}
func CheckFilter(filter string, input string) (bool, error) {
if len(strings.TrimSpace(filter)) == 0 {
return false, ErrFilterEmpty
}
if strings.HasPrefix(filter, "/") && strings.HasSuffix(filter, "/") {
re, err := regexp.Compile(filter[1 : len(filter)-1])
if err != nil {
return false, fmt.Errorf("invalid regex filter: %w", err)
}
if re.MatchString(input) {
return true, nil
}
}
for item := range strings.SplitSeq(filter, ",") {
if strings.TrimSpace(item) == input {
return true, nil
}
}
return false, nil
}
func GenerateUUID(str string) string {
uuid := uuid.NewSHA1(uuid.NameSpaceURL, []byte(str))
return uuid.String()
}
func GenerateString(length int) string {
src := make([]byte, length)
rand.Read(src)
return base64.RawURLEncoding.EncodeToString(src)[:length]
}