/
resource_github_codespaces_secret.go
220 lines (187 loc) · 6.38 KB
/
resource_github_codespaces_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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package github
import (
"context"
"encoding/base64"
"fmt"
"log"
"net/http"
"strings"
"github.com/google/go-github/v57/github"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceGithubCodespacesSecret() *schema.Resource {
return &schema.Resource{
Create: resourceGithubCodespacesSecretCreateOrUpdate,
Read: resourceGithubCodespacesSecretRead,
Delete: resourceGithubCodespacesSecretDelete,
Importer: &schema.ResourceImporter{
State: resourceGithubCodespacesSecretImport,
},
Schema: map[string]*schema.Schema{
"repository": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Name of the repository.",
},
"secret_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Name of the secret.",
ValidateFunc: validateSecretNameFunc,
},
"encrypted_value": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"plaintext_value"},
Description: "Encrypted value of the secret using the GitHub public key in Base64 format.",
},
"plaintext_value": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"encrypted_value"},
Description: "Plaintext value of the secret to be encrypted.",
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "Date of 'codespaces_secret' creation.",
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
Description: "Date of 'codespaces_secret' update.",
},
},
}
}
func resourceGithubCodespacesSecretCreateOrUpdate(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 := getCodespacesPublicKeyDetails(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.Codespaces.CreateOrUpdateRepoSecret(ctx, owner, repo, eSecret)
if err != nil {
return err
}
d.SetId(buildTwoPartID(repo, secretName))
return resourceGithubCodespacesSecretRead(d, meta)
}
func resourceGithubCodespacesSecretRead(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.Codespaces.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 resourceGithubCodespacesSecretDelete(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.Codespaces.DeleteRepoSecret(ctx, orgName, repoName, secretName)
return err
}
func resourceGithubCodespacesSecretImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
ctx := context.Background()
parts := strings.Split(d.Id(), "/")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid ID specified: supplied ID must be written as <repository>/<secret_name>")
}
d.SetId(buildTwoPartID(parts[0], parts[1]))
repoName, secretName, err := parseTwoPartID(d.Id(), "repository", "secret_name")
if err != nil {
return nil, err
}
secret, _, err := client.Codespaces.GetRepoSecret(ctx, owner, repoName, secretName)
if err != nil {
return nil, err
}
d.Set("repository", repoName)
d.Set("secret_name", secretName)
// encrypted_value or plaintext_value can not be imported
d.Set("created_at", secret.CreatedAt.String())
d.Set("updated_at", secret.UpdatedAt.String())
return []*schema.ResourceData{d}, nil
}
func getCodespacesPublicKeyDetails(owner, repository string, meta interface{}) (keyId, pkValue string, err error) {
client := meta.(*Owner).v3client
ctx := context.Background()
publicKey, _, err := client.Codespaces.GetRepoPublicKey(ctx, owner, repository)
if err != nil {
return keyId, pkValue, err
}
return publicKey.GetKeyID(), publicKey.GetKey(), err
}