forked from alexellis/actions-batch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
secrets.go
74 lines (60 loc) · 1.75 KB
/
secrets.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
70
71
72
73
74
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"os"
"path"
"strings"
"github.com/google/go-github/v57/github"
"golang.org/x/crypto/nacl/box"
)
func createSecrets(ctx context.Context, client *github.Client, owner, repoName, secretsFrom string) (map[string]string, error) {
mapped := map[string]string{}
key, _, err := client.Actions.GetRepoPublicKey(ctx, owner, repoName)
if err != nil {
return nil, err
}
dir, err := os.ReadDir(secretsFrom)
if err != nil {
return nil, err
}
for _, f := range dir {
if f.IsDir() {
continue
}
secretName := strings.ToUpper(strings.ReplaceAll(f.Name(), "-", "_"))
secretData, _ := os.ReadFile(path.Join(secretsFrom, f.Name()))
encryptedVal, err := encryptSecret(key, strings.TrimSpace(string(secretData)))
if err != nil {
return nil, err
}
if _, err := client.Actions.CreateOrUpdateRepoSecret(ctx, owner, repoName, &github.EncryptedSecret{
Name: secretName,
EncryptedValue: encryptedVal,
KeyID: key.GetKeyID(),
}); err != nil {
return nil, err
} else {
fmt.Printf("Created secret: %s (%s)\n", secretName, path.Join(secretsFrom, f.Name()))
mapped[secretName] = string(secretName)
}
}
return mapped, nil
}
func encryptSecret(publicKey *github.PublicKey, secret string) (string, error) {
publicKeyBytes, err := base64.StdEncoding.DecodeString(publicKey.GetKey())
if err != nil {
return "", err
}
// Decode the public key
var publicKeyDecoded [32]byte
copy(publicKeyDecoded[:], publicKeyBytes)
encrypted, err := box.SealAnonymous(nil, []byte(secret), (*[32]byte)(publicKeyBytes), rand.Reader)
if err != nil {
return "", err
}
encryptedBase64 := base64.StdEncoding.EncodeToString(encrypted)
return encryptedBase64, nil
}