-
Notifications
You must be signed in to change notification settings - Fork 958
Expand file tree
/
Copy pathresource_github_actions_repository_permissions.go
More file actions
316 lines (272 loc) · 9.64 KB
/
resource_github_actions_repository_permissions.go
File metadata and controls
316 lines (272 loc) · 9.64 KB
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package github
import (
"context"
"log"
"github.com/google/go-github/v84/github"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceGithubActionsRepositoryPermissions() *schema.Resource {
return &schema.Resource{
Create: resourceGithubActionsRepositoryPermissionsCreate,
Read: resourceGithubActionsRepositoryPermissionsRead,
Update: resourceGithubActionsRepositoryPermissionsUpdate,
Delete: resourceGithubActionsRepositoryPermissionsDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"allowed_actions": {
Type: schema.TypeString,
Optional: true,
Description: "The permissions policy that controls the actions that are allowed to run. Can be one of: 'all', 'local_only', or 'selected'.",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"all", "local_only", "selected"}, false)),
},
"allowed_actions_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Sets the actions that are allowed in an repository. Only available when 'allowed_actions' = 'selected'. ",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"github_owned_allowed": {
Type: schema.TypeBool,
Required: true,
Description: "Whether GitHub-owned actions are allowed in the repository.",
},
"patterns_allowed": {
Type: schema.TypeSet,
Optional: true,
Description: "Specifies a list of string-matching patterns to allow specific action(s). Wildcards, tags, and SHAs are allowed. For example, 'monalisa/octocat@', 'monalisa/octocat@v2', 'monalisa/'.",
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"verified_allowed": {
Type: schema.TypeBool,
Optional: true,
Description: "Whether actions in GitHub Marketplace from verified creators are allowed. Set to 'true' to allow all GitHub Marketplace actions by verified creators.",
},
},
},
},
"enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Should GitHub actions be enabled on this repository.",
},
"repository": {
Type: schema.TypeString,
Required: true,
Description: "The GitHub repository.",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringLenBetween(1, 100)),
},
"sha_pinning_required": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Description: "Whether pinning to a specific SHA is required for all actions and reusable workflows in a repository.",
},
},
}
}
func resourceGithubActionsRepositoryAllowedObject(d *schema.ResourceData) *github.ActionsAllowed {
allowed := &github.ActionsAllowed{}
config := d.Get("allowed_actions_config").([]any)
if len(config) > 0 {
data := config[0].(map[string]any)
switch x := data["github_owned_allowed"].(type) {
case bool:
allowed.GithubOwnedAllowed = &x
}
switch x := data["verified_allowed"].(type) {
case bool:
allowed.VerifiedAllowed = &x
}
patternsAllowed := []string{}
switch t := data["patterns_allowed"].(type) {
case *schema.Set:
for _, value := range t.List() {
patternsAllowed = append(patternsAllowed, value.(string))
}
}
allowed.PatternsAllowed = patternsAllowed
} else {
return nil
}
return allowed
}
func resourceGithubActionsRepositoryPermissionsCreate(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
repoName := d.Get("repository").(string)
ctx := context.Background()
allowedActions := d.Get("allowed_actions").(string)
enabled := d.Get("enabled").(bool)
log.Printf("[DEBUG] Actions enabled: %t", enabled)
repoActionPermissions := github.ActionsPermissionsRepository{
Enabled: &enabled,
}
// Only specify `allowed_actions` if actions are enabled.
if enabled {
repoActionPermissions.AllowedActions = &allowedActions
}
// Use `GetOkExists` for `sha_pinning_required` to detect explicit
// `false` values.
//
// The `sha_pinning_required` is an Optional and Computed boolean.
//
// When a user writes `sha_pinning_required = false`,
// `GetOk` returns `(false, false)`. The second `false` argument
// means "not set", which is indistinguishable from the user omitting
// the field entirely. So the explicit false was silently ignored.
//
// `GetOkExists` returns `(false, true)`.
// The `true` value correctly indicates the user did want to set it.
if v, ok := d.GetOkExists("sha_pinning_required"); ok { //nolint:staticcheck
repoActionPermissions.SHAPinningRequired = github.Ptr(v.(bool))
}
_, _, err := client.Repositories.UpdateActionsPermissions(ctx,
owner,
repoName,
repoActionPermissions,
)
if err != nil {
return err
}
if allowedActions == "selected" {
actionsAllowedData := resourceGithubActionsRepositoryAllowedObject(d)
if actionsAllowedData != nil {
log.Printf("[DEBUG] Allowed actions config is set")
_, _, err = client.Repositories.EditActionsAllowed(ctx,
owner,
repoName,
*actionsAllowedData)
if err != nil {
return err
}
} else {
log.Printf("[DEBUG] Allowed actions config not set, skipping")
}
}
d.SetId(repoName)
return resourceGithubActionsRepositoryPermissionsRead(d, meta)
}
func resourceGithubActionsRepositoryPermissionsUpdate(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
repoName := d.Get("repository").(string)
ctx := context.WithValue(context.Background(), ctxId, d.Id())
allowedActions := d.Get("allowed_actions").(string)
enabled := d.Get("enabled").(bool)
log.Printf("[DEBUG] Actions enabled: %t", enabled)
repoActionPermissions := github.ActionsPermissionsRepository{
Enabled: &enabled,
}
// Only specify `allowed_actions` if actions are enabled.
if enabled {
repoActionPermissions.AllowedActions = &allowedActions
}
// Use `HasChange` + `Get` for `sha_pinning_required` to send the
// value only when it changes.
if d.HasChange("sha_pinning_required") {
repoActionPermissions.SHAPinningRequired = github.Ptr(d.Get("sha_pinning_required").(bool))
}
_, _, err := client.Repositories.UpdateActionsPermissions(ctx,
owner,
repoName,
repoActionPermissions,
)
if err != nil {
return err
}
if allowedActions == "selected" {
actionsAllowedData := resourceGithubActionsRepositoryAllowedObject(d)
if actionsAllowedData != nil {
log.Printf("[DEBUG] The allowedActions variable is set.")
_, _, err = client.Repositories.EditActionsAllowed(ctx,
owner,
repoName,
*actionsAllowedData)
if err != nil {
return err
}
} else {
log.Printf("[DEBUG] The allowedActions variable is not set, skipping.")
}
}
return resourceGithubActionsRepositoryPermissionsRead(d, meta)
}
func resourceGithubActionsRepositoryPermissionsRead(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
repoName := d.Id()
ctx := context.WithValue(context.Background(), ctxId, d.Id())
actionsPermissions, _, err := client.Repositories.GetActionsPermissions(ctx, owner, repoName)
if err != nil {
return err
}
// only load and fill allowed_actions_config if allowed_actions_config is also set
// in the TF code. (see #2105)
// on initial import there might not be any value in the state, then we have to import the data
// -> but we can only load an existing state if the current config is set to "selected" (see #2182)
allowedActions := d.Get("allowed_actions").(string)
allowedActionsConfig := d.Get("allowed_actions_config").([]any)
serverHasAllowedActionsConfig := actionsPermissions.GetAllowedActions() == "selected" && actionsPermissions.GetEnabled()
userWantsAllowedActionsConfig := (allowedActions == "selected" && len(allowedActionsConfig) > 0) || allowedActions == ""
if serverHasAllowedActionsConfig && userWantsAllowedActionsConfig {
actionsAllowed, _, err := client.Repositories.GetActionsAllowed(ctx, owner, repoName)
if err != nil {
return err
}
// If actionsAllowed set to local/all by removing all actions config settings, the response will be empty
if actionsAllowed != nil {
if err = d.Set("allowed_actions_config", []any{
map[string]any{
"github_owned_allowed": actionsAllowed.GetGithubOwnedAllowed(),
"patterns_allowed": actionsAllowed.PatternsAllowed,
"verified_allowed": actionsAllowed.GetVerifiedAllowed(),
},
}); err != nil {
return err
}
}
} else {
if err = d.Set("allowed_actions_config", []any{}); err != nil {
return err
}
}
if err = d.Set("allowed_actions", actionsPermissions.GetAllowedActions()); err != nil {
return err
}
if err = d.Set("enabled", actionsPermissions.GetEnabled()); err != nil {
return err
}
if err = d.Set("repository", repoName); err != nil {
return err
}
if err = d.Set("sha_pinning_required", actionsPermissions.GetSHAPinningRequired()); err != nil {
return err
}
return nil
}
func resourceGithubActionsRepositoryPermissionsDelete(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
repoName := d.Id()
ctx := context.WithValue(context.Background(), ctxId, d.Id())
// Reset the repo to "default" settings
repoActionPermissions := github.ActionsPermissionsRepository{
AllowedActions: new("all"),
Enabled: new(true),
}
_, _, err := client.Repositories.UpdateActionsPermissions(ctx,
owner,
repoName,
repoActionPermissions,
)
if err != nil {
return err
}
return nil
}