-
Notifications
You must be signed in to change notification settings - Fork 0
/
authz.go
69 lines (59 loc) · 1.44 KB
/
authz.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package factory
import (
"fmt"
"io"
"os"
"github.com/zalgonoise/cloaki/authz"
"github.com/zalgonoise/cloaki/crypt"
"github.com/zalgonoise/x/errors"
)
const (
signingKeyPath = "/cloaki/server/key"
)
// Authorizer creates a new authorizer with the input key `key`, or creates a new
// one under the preset folder if it doesn't yet exist and is not provided
func Authorizer(path string) (auth authz.Authorizer, err error) {
var defErr error
auth, err = loadKey(path)
if err != nil {
auth, defErr = loadKey(signingKeyPath)
if defErr != nil {
return nil, errors.Join(defErr, fmt.Errorf("failed to load key from input path and from default path: %w", err))
}
}
return authz.WithTrace(auth), nil
}
func loadKey(path string) (authz.Authorizer, error) {
fs, err := os.Stat(path)
if (err != nil && os.IsNotExist(err)) || (fs != nil && fs.Size() == 0) {
return createKey(path)
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
b, err := io.ReadAll(f)
if err != nil {
return nil, err
}
if len(b) == 0 {
return nil, errors.New("zero bytes read")
}
return authz.NewAuthorizer(b), nil
}
func createKey(path string) (authz.Authorizer, error) {
// try to create local key
k := crypt.New256Key()
f, err := os.Create(path)
if err != nil {
return nil, err
}
n, err := f.Write(k[:])
if err != nil {
return nil, err
}
if n == 0 {
return nil, errors.New("zero bytes written")
}
return authz.NewAuthorizer(k[:]), nil
}