Debian Codegraph @

example/codespaces/newusersecretwithxcrypto/main.go

raw
1 // Copyright 2023 The go-github AUTHORS. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 // newusersecretwithxcrypto creates a new secret in GitHub for a given user.
7 // newusersecretwithxcrypto uses x/crypto/nacl/box instead of sodium.
8 // It does not depend on any native libraries and is easier to cross-compile for different platforms.
9 // Quite possibly there is a performance penalty due to this.
10 //
11 // newusersecretwithxcrypto takes in one argument for the name of the secret to add, and 2 flags owner, repo.
12 // If owner/repo are defined then it adds the secret to that repository
13 // The secret value is pulled from an environment variable based on the secret name.
14 // To authenticate with GitHub, provide your token via an environment variable GITHUB_AUTH_TOKEN.
15 //
16 // To verify the new secret, navigate to GitHub User > Settings > left side options bar > Codespaces > Secrets.
17 //
18 // Usage:
19 //
20 // export GITHUB_AUTH_TOKEN=<auth token from github that has secret create rights>
21 // export SECRET_VARIABLE=<secret value of the secret variable>
22 // go run main.go SECRET_VARIABLE
23 //
24 // Example:
25 //
26 // export GITHUB_AUTH_TOKEN=0000000000000000
27 // export SECRET_VARIABLE="my-secret"
28 // go run main.go SECRET_VARIABLE
29 package main
30
31 import (
32 "context"
33 crypto_rand "crypto/rand"
34 "encoding/base64"
35 "flag"
36 "fmt"
37 "log"
38 "os"
39
40 "github.com/google/go-github/v60/github"
41 "golang.org/x/crypto/nacl/box"
42 )
43
44 var (
45 repo = flag.String("repo", "", "The repo that the secret should be added to, ex. go-github")
46 owner = flag.String("owner", "", "The owner of there repo this should be added to, ex. google")
47 )
48
49 func main() {
50 flag.Parse()
51
52 token := os.Getenv("GITHUB_AUTH_TOKEN")
53 if token == "" {
54 log.Fatal("please provide a GitHub API token via env variable GITHUB_AUTH_TOKEN")
55 }
56
57 secretName, err := getSecretName()
58 if err != nil {
59 log.Fatal(err)
60 }
61
62 secretValue, err := getSecretValue(secretName)
63 if err != nil {
64 log.Fatal(err)
65 }
66
67 ctx := context.Background()
68 client := github.NewClient(nil).WithAuthToken(token)
69
70 if err := addUserSecret(ctx, client, secretName, secretValue, *owner, *repo); err != nil {
71 log.Fatal(err)
72 }
73
74 fmt.Printf("Added secret %q to the authenticated user\n", secretName)
75 }
76
77 func getSecretName() (string, error) {
78 secretName := flag.Arg(0)
79 if secretName == "" {
80 return "", fmt.Errorf("missing argument secret name")
81 }
82 return secretName, nil
83 }
84
85 func getSecretValue(secretName string) (string, error) {
86 secretValue := os.Getenv(secretName)
87 if secretValue == "" {
88 return "", fmt.Errorf("secret value not found under env variable %q", secretName)
89 }
90 return secretValue, nil
91 }
92
93 // addUserSecret will add a secret to a GitHub user for use in GitHub Codespaces.
94 //
95 // The secretName and secretValue will determine the name of the secret added and it's corresponding value.
96 //
97 // The actual transmission of the secret value to GitHub using the api requires that the secret value is encrypted
98 // using the public key of the target user. This encryption is done using x/crypto/nacl/box.
99 //
100 // First, the public key of the user is retrieved. The public key comes base64
101 // encoded, so it must be decoded prior to use.
102 //
103 // Second, the decode key is converted into a fixed size byte array.
104 //
105 // Third, the secret value is converted into a slice of bytes.
106 //
107 // Fourth, the secret is encrypted with box.SealAnonymous using the user's decoded public key.
108 //
109 // Fifth, the encrypted secret is encoded as a base64 string to be used in a github.EncodedSecret type.
110 //
111 // Sixth, The other two properties of the github.EncodedSecret type are determined. The name of the secret to be added
112 // (string not base64), and the KeyID of the public key used to encrypt the secret.
113 // This can be retrieved via the public key's GetKeyID method.
114 //
115 // Seventh, the github.EncodedSecret is passed into the GitHub client.Codespaces.CreateOrUpdateUserSecret method to
116 // populate the secret in the GitHub user.
117 //
118 // Finally, if a repo and owner are passed in, it adds the repo to the user secret.
119 func addUserSecret(ctx context.Context, client *github.Client, secretName, secretValue, owner, repo string) error {
120 publicKey, _, err := client.Codespaces.GetUserPublicKey(ctx)
121 if err != nil {
122 return err
123 }
124
125 encryptedSecret, err := encryptSecretWithPublicKey(publicKey, secretName, secretValue)
126 if err != nil {
127 return err
128 }
129
130 if _, err := client.Codespaces.CreateOrUpdateUserSecret(ctx, encryptedSecret); err != nil {
131 return fmt.Errorf("Codespaces.CreateOrUpdateUserSecret returned error: %v", err)
132 }
133
134 if owner != "" && repo != "" {
135 r, _, err := client.Repositories.Get(ctx, owner, repo)
136 if err != nil {
137 return fmt.Errorf("Repositories.Get returned error: %v", err)
138 }
139 _, err = client.Codespaces.AddSelectedRepoToUserSecret(ctx, encryptedSecret.Name, r)
140 if err != nil {
141 return fmt.Errorf("Codespaces.AddSelectedRepoToUserSecret returned error: %v", err)
142 }
143 fmt.Printf("Added secret %q to %v/%v\n", secretName, owner, repo)
144 }
145
146 return nil
147 }
148
149 func encryptSecretWithPublicKey(publicKey *github.PublicKey, secretName string, secretValue string) (*github.EncryptedSecret, error) {
150 decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey.GetKey())
151 if err != nil {
152 return nil, fmt.Errorf("base64.StdEncoding.DecodeString was unable to decode public key: %v", err)
153 }
154
155 var boxKey [32]byte
156 copy(boxKey[:], decodedPublicKey)
157 secretBytes := []byte(secretValue)
158 encryptedBytes, err := box.SealAnonymous([]byte{}, secretBytes, &boxKey, crypto_rand.Reader)
159 if err != nil {
160 return nil, fmt.Errorf("box.SealAnonymous failed with error %w", err)
161 }
162
163 encryptedString := base64.StdEncoding.EncodeToString(encryptedBytes)
164 keyID := publicKey.GetKeyID()
165 encryptedSecret := &github.EncryptedSecret{
166 Name: secretName,
167 KeyID: keyID,
168 EncryptedValue: encryptedString,
169 }
170 return encryptedSecret, nil
171 }