-
Notifications
You must be signed in to change notification settings - Fork 956
Expand file tree
/
Copy pathresource_github_actions_organization_permissions.go
More file actions
395 lines (346 loc) · 11.8 KB
/
resource_github_actions_organization_permissions.go
File metadata and controls
395 lines (346 loc) · 11.8 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package github
import (
"context"
"errors"
"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 resourceGithubActionsOrganizationPermissions() *schema.Resource {
return &schema.Resource{
Create: resourceGithubActionsOrganizationPermissionsCreate,
Read: resourceGithubActionsOrganizationPermissionsRead,
Update: resourceGithubActionsOrganizationPermissionsUpdate,
Delete: resourceGithubActionsOrganizationPermissionsDelete,
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)),
},
"enabled_repositories": {
Type: schema.TypeString,
Required: true,
Description: "The policy that controls the repositories in the organization that are allowed to run GitHub Actions. Can be one of: 'all', 'none', or 'selected'.",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"all", "none", "selected"}, false)),
},
"allowed_actions_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Sets the actions that are allowed in an organization. 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 organization.",
},
"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_repositories_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Sets the list of selected repositories that are enabled for GitHub Actions in an organization. Only available when 'enabled_repositories' = 'selected'.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"repository_ids": {
Type: schema.TypeSet,
Description: "List of repository IDs to enable for GitHub Actions.",
Elem: &schema.Schema{Type: schema.TypeInt},
Required: true,
},
},
},
},
"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 an organization.",
},
},
}
}
func resourceGithubActionsOrganizationAllowedObject(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 resourceGithubActionsEnabledRepositoriesObject(d *schema.ResourceData) ([]int64, error) {
var enabled []int64
config := d.Get("enabled_repositories_config").([]any)
if len(config) > 0 {
data := config[0].(map[string]any)
switch x := data["repository_ids"].(type) {
case *schema.Set:
for _, value := range x.List() {
enabled = append(enabled, int64(value.(int)))
}
}
} else {
return nil, errors.New("the enabled_repositories_config {} block must be specified if enabled_repositories == 'selected'")
}
return enabled, nil
}
func resourceGithubActionsOrganizationPermissionsCreate(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
ctx := context.Background()
err := checkOrganization(meta)
if err != nil {
return err
}
allowedActions := d.Get("allowed_actions").(string)
enabledRepositories := d.Get("enabled_repositories").(string)
actionsPermissions := github.ActionsPermissions{
AllowedActions: &allowedActions,
EnabledRepositories: &enabledRepositories,
}
// 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
actionsPermissions.SHAPinningRequired = github.Ptr(v.(bool))
}
_, _, err = client.Actions.UpdateActionsPermissions(ctx,
orgName,
actionsPermissions)
if err != nil {
return err
}
if allowedActions == "selected" {
actionsAllowedData := resourceGithubActionsOrganizationAllowedObject(d)
if actionsAllowedData != nil {
log.Printf("[DEBUG] Allowed actions config is set")
_, _, err = client.Actions.UpdateActionsAllowed(ctx,
orgName,
*actionsAllowedData)
if err != nil {
return err
}
} else {
log.Printf("[DEBUG] Allowed actions config not set, skipping")
}
}
if enabledRepositories == "selected" {
enabledReposData, err := resourceGithubActionsEnabledRepositoriesObject(d)
if err != nil {
return err
}
_, err = client.Actions.SetEnabledReposInOrg(ctx,
orgName,
enabledReposData)
if err != nil {
return err
}
}
d.SetId(orgName)
return resourceGithubActionsOrganizationPermissionsRead(d, meta)
}
func resourceGithubActionsOrganizationPermissionsUpdate(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
ctx := context.WithValue(context.Background(), ctxId, d.Id())
err := checkOrganization(meta)
if err != nil {
return err
}
allowedActions := d.Get("allowed_actions").(string)
enabledRepositories := d.Get("enabled_repositories").(string)
actionsPermissions := github.ActionsPermissions{
AllowedActions: &allowedActions,
EnabledRepositories: &enabledRepositories,
}
// Use `HasChange` + `Get` for `sha_pinning_required` to send the
// value only when it changes.
if d.HasChange("sha_pinning_required") {
actionsPermissions.SHAPinningRequired = github.Ptr(d.Get("sha_pinning_required").(bool))
}
_, _, err = client.Actions.UpdateActionsPermissions(ctx,
orgName,
actionsPermissions)
if err != nil {
return err
}
if allowedActions == "selected" {
actionsAllowedData := resourceGithubActionsOrganizationAllowedObject(d)
if actionsAllowedData != nil {
log.Printf("[DEBUG] The allowedActions variable is set.")
_, _, err = client.Actions.UpdateActionsAllowed(ctx,
orgName,
*actionsAllowedData)
if err != nil {
return err
}
} else {
log.Printf("[DEBUG] The allowedActions variable is not set, skipping.")
}
}
if enabledRepositories == "selected" {
enabledReposData, err := resourceGithubActionsEnabledRepositoriesObject(d)
if err != nil {
return err
}
_, err = client.Actions.SetEnabledReposInOrg(ctx,
orgName,
enabledReposData)
if err != nil {
return err
}
}
return resourceGithubActionsOrganizationPermissionsRead(d, meta)
}
func resourceGithubActionsOrganizationPermissionsRead(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
ctx := context.Background()
err := checkOrganization(meta)
if err != nil {
return err
}
actionsPermissions, _, err := client.Actions.GetActionsPermissions(ctx, d.Id())
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"
userWantsAllowedActionsConfig := (allowedActions == "selected" && len(allowedActionsConfig) > 0) || allowedActions == ""
if serverHasAllowedActionsConfig && userWantsAllowedActionsConfig {
actionsAllowed, _, err := client.Actions.GetActionsAllowed(ctx, d.Id())
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 actionsPermissions.GetEnabledRepositories() == "selected" {
opts := github.ListOptions{PerPage: 10, Page: 1}
var repoList []int64
var allRepos []*github.Repository
for {
enabledRepos, resp, err := client.Actions.ListEnabledReposInOrg(ctx, d.Id(), &opts)
if err != nil {
return err
}
allRepos = append(allRepos, enabledRepos.Repositories...)
opts.Page = resp.NextPage
if resp.NextPage == 0 {
break
}
}
for index := range allRepos {
repoList = append(repoList, *allRepos[index].ID)
}
if allRepos != nil {
if err = d.Set("enabled_repositories_config", []any{
map[string]any{
"repository_ids": repoList,
},
}); err != nil {
return err
}
} else {
if err = d.Set("enabled_repositories_config", []any{}); err != nil {
return err
}
}
}
if err = d.Set("allowed_actions", actionsPermissions.GetAllowedActions()); err != nil {
return err
}
if err = d.Set("enabled_repositories", actionsPermissions.GetEnabledRepositories()); err != nil {
return err
}
if err = d.Set("sha_pinning_required", actionsPermissions.GetSHAPinningRequired()); err != nil {
return err
}
return nil
}
func resourceGithubActionsOrganizationPermissionsDelete(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
ctx := context.WithValue(context.Background(), ctxId, d.Id())
err := checkOrganization(meta)
if err != nil {
return err
}
// This will nullify any allowedActions elements
_, _, err = client.Actions.UpdateActionsPermissions(ctx,
orgName,
github.ActionsPermissions{
AllowedActions: new("all"),
EnabledRepositories: new("all"),
})
if err != nil {
return err
}
return nil
}