forked from integrations/terraform-provider-github
/
resource_github_actions_secret.go
201 lines (172 loc) · 5.56 KB
/
resource_github_actions_secret.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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package github
import (
"context"
"encoding/base64"
"fmt"
"log"
"net/http"
"github.com/google/go-github/v39/github"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"golang.org/x/crypto/nacl/box"
)
func resourceGithubActionsSecret() *schema.Resource {
return &schema.Resource{
Create: resourceGithubActionsSecretCreateOrUpdate,
Read: resourceGithubActionsSecretRead,
Update: resourceGithubActionsSecretCreateOrUpdate,
Delete: resourceGithubActionsSecretDelete,
Schema: map[string]*schema.Schema{
"repository": {
Type: schema.TypeString,
Required: true,
},
"secret_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateSecretNameFunc,
},
"encrypted_value": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"plaintext_value"},
},
"plaintext_value": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"encrypted_value"},
},
"created_at": {
Type: schema.TypeString,
Computed: true,
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceGithubActionsSecretCreateOrUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
ctx := context.Background()
repo := d.Get("repository").(string)
secretName := d.Get("secret_name").(string)
plaintextValue := d.Get("plaintext_value").(string)
var encryptedValue string
keyId, publicKey, err := getPublicKeyDetails(owner, repo, meta)
if err != nil {
return err
}
if encryptedText, ok := d.GetOk("encrypted_value"); ok {
encryptedValue = encryptedText.(string)
} else {
encryptedBytes, err := encryptPlaintext(plaintextValue, publicKey)
if err != nil {
return err
}
encryptedValue = base64.StdEncoding.EncodeToString(encryptedBytes)
}
// Create an EncryptedSecret and encrypt the plaintext value into it
eSecret := &github.EncryptedSecret{
Name: secretName,
KeyID: keyId,
EncryptedValue: encryptedValue,
}
_, err = client.Actions.CreateOrUpdateRepoSecret(ctx, owner, repo, eSecret)
if err != nil {
return err
}
d.SetId(buildTwoPartID(repo, secretName))
return resourceGithubActionsSecretRead(d, meta)
}
func resourceGithubActionsSecretRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
ctx := context.Background()
repoName, secretName, err := parseTwoPartID(d.Id(), "repository", "secret_name")
if err != nil {
return err
}
secret, _, err := client.Actions.GetRepoSecret(ctx, owner, repoName, secretName)
if err != nil {
if ghErr, ok := err.(*github.ErrorResponse); ok {
if ghErr.Response.StatusCode == http.StatusNotFound {
log.Printf("[WARN] Removing actions secret %s from state because it no longer exists in GitHub",
d.Id())
d.SetId("")
return nil
}
}
return err
}
d.Set("encrypted_value", d.Get("encrypted_value"))
d.Set("plaintext_value", d.Get("plaintext_value"))
d.Set("created_at", secret.CreatedAt.String())
// This is a drift detection mechanism based on timestamps.
//
// If we do not currently store the "updated_at" field, it means we've only
// just created the resource and the value is most likely what we want it to
// be.
//
// If the resource is changed externally in the meantime then reading back
// the last update timestamp will return a result different than the
// timestamp we've persisted in the state. In that case, we can no longer
// trust that the value (which we don't see) is equal to what we've declared
// previously.
//
// The only solution to enforce consistency between is to mark the resource
// as deleted (unset the ID) in order to fix potential drift by recreating
// the resource.
if updatedAt, ok := d.GetOk("updated_at"); ok && updatedAt != secret.UpdatedAt.String() {
log.Printf("[WARN] The secret %s has been externally updated in GitHub", d.Id())
d.SetId("")
} else if !ok {
d.Set("updated_at", secret.UpdatedAt.String())
}
return nil
}
func resourceGithubActionsSecretDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
ctx := context.WithValue(context.Background(), ctxId, d.Id())
repoName, secretName, err := parseTwoPartID(d.Id(), "repository", "secret_name")
if err != nil {
return err
}
log.Printf("[DEBUG] Deleting secret: %s", d.Id())
_, err = client.Actions.DeleteRepoSecret(ctx, orgName, repoName, secretName)
return err
}
func getPublicKeyDetails(owner, repository string, meta interface{}) (keyId, pkValue string, err error) {
client := meta.(*Owner).v3client
ctx := context.Background()
publicKey, _, err := client.Actions.GetRepoPublicKey(ctx, owner, repository)
if err != nil {
return keyId, pkValue, err
}
return publicKey.GetKeyID(), publicKey.GetKey(), err
}
func encryptPlaintext(plaintext, publicKeyB64 string) ([]byte, error) {
publicKeyBytes, err := base64.StdEncoding.DecodeString(publicKeyB64)
if err != nil {
return nil, err
}
var publicKeyBytes32 [32]byte
copiedLen := copy(publicKeyBytes32[:], publicKeyBytes)
if copiedLen == 0 {
return nil, fmt.Errorf("could not convert publicKey to bytes")
}
plaintextBytes := []byte(plaintext)
var encryptedBytes []byte
cipherText, err := box.SealAnonymous(encryptedBytes, plaintextBytes, &publicKeyBytes32, nil)
if err != nil {
return nil, err
}
return cipherText, nil
}