-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathowner_tokens_dir.go
51 lines (45 loc) · 1.3 KB
/
owner_tokens_dir.go
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
package util
import (
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// OwnerTokensDir handles finding owner based tokens in a directory for GitHub Apps
type OwnerTokensDir struct {
gitServer string
dir string
}
// NewOwnerTokensDir creates a new dir token scanner
func NewOwnerTokensDir(gitServer, dir string) *OwnerTokensDir {
return &OwnerTokensDir{gitServer, dir}
}
// FindToken finds the token for the given owner
func (o *OwnerTokensDir) FindToken(owner string) (string, error) {
dir := o.dir
ownerURL := URLJoin(o.gitServer, owner)
prefix := ownerURL + "="
files, err := os.ReadDir(dir)
if err != nil {
return "", errors.Wrapf(err, "failed to list files in dir %s", dir)
}
for _, f := range files {
localName := f.Name()
if f.IsDir() || localName == "username" || strings.HasPrefix(localName, ".") {
continue
}
name := filepath.Join(dir, localName)
logrus.Tracef("loading file %s", name)
/* #nosec */
data, err := os.ReadFile(name)
if err != nil {
return "", errors.Wrapf(err, "failed to load file %s", name)
}
text := strings.TrimSpace(string(data))
if strings.HasPrefix(text, prefix) {
return strings.TrimPrefix(text, prefix), nil
}
}
return "", errors.Errorf("no github app secret found for owner URL %s", ownerURL)
}