forked from integrations/terraform-provider-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource_github_enterprise_organization.go
More file actions
542 lines (469 loc) · 14.9 KB
/
resource_github_enterprise_organization.go
File metadata and controls
542 lines (469 loc) · 14.9 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
package github
import (
"context"
"errors"
"fmt"
"log"
"strings"
"github.com/google/go-github/v81/github"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/shurcooL/githubv4"
)
func isSAMLEnforcementError(err error) bool {
if err == nil {
return false
}
var ghErr *github.ErrorResponse
if errors.As(err, &ghErr) {
return ghErr.Response != nil &&
ghErr.Response.StatusCode == 403 &&
strings.Contains(ghErr.Message, "SAML enforcement")
}
return strings.Contains(err.Error(), "Resource protected by organization SAML enforcement")
}
func resourceGithubEnterpriseOrganization() *schema.Resource {
return &schema.Resource{
Create: resourceGithubEnterpriseOrganizationCreate,
Read: resourceGithubEnterpriseOrganizationRead,
Delete: resourceGithubEnterpriseOrganizationDelete,
Update: resourceGithubEnterpriseOrganizationUpdate,
Importer: &schema.ResourceImporter{
State: resourceGithubEnterpriseOrganizationImport,
},
Schema: map[string]*schema.Schema{
"enterprise_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The ID of the enterprise.",
},
"id": {
Type: schema.TypeString,
Computed: true,
Description: "The node ID of the organization.",
},
"database_id": {
Type: schema.TypeInt,
Computed: true,
Description: "The database ID of the organization.",
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The name of the organization.",
},
"display_name": {
Type: schema.TypeString,
Optional: true,
Description: "The display name of the organization.",
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: "The description of the organization.",
},
"admin_logins": {
Type: schema.TypeSet,
Required: true,
Description: "List of organization owner usernames.",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"billing_email": {
Type: schema.TypeString,
Required: true,
Description: "The billing email address.",
},
},
}
}
func resourceGithubEnterpriseOrganizationCreate(data *schema.ResourceData, meta any) error {
var mutate struct {
CreateEnterpriseOrganization struct {
Organization struct {
ID githubv4.ID
}
} `graphql:"createEnterpriseOrganization(input:$input)"`
}
owner := meta.(*Owner)
v3 := owner.v3client
v4 := owner.v4client
var adminLogins []githubv4.String
for _, v := range data.Get("admin_logins").(*schema.Set).List() {
adminLogins = append(adminLogins, githubv4.String(v.(string)))
}
input := githubv4.CreateEnterpriseOrganizationInput{
EnterpriseID: data.Get("enterprise_id"),
Login: githubv4.String(data.Get("name").(string)),
ProfileName: githubv4.String(data.Get("name").(string)),
BillingEmail: githubv4.String(data.Get("billing_email").(string)),
AdminLogins: adminLogins,
}
err := v4.Mutate(context.Background(), &mutate, input, nil)
if err != nil {
return err
}
data.SetId(fmt.Sprintf("%s", mutate.CreateEnterpriseOrganization.Organization.ID))
// We use the V3 api to set the description of the org, because there is no mutator in the V4 API to edit the org's
// description and display name
//NOTE: There is some odd behavior here when using an EMU with SSO. If the user token has been granted permission to
//ANY ORG in the enterprise, then this works, provided that our token has sufficient permission. If the user token
//has not been added to any orgs, then this will fail.
//
//Unfortunately, there is no way in the api to grant a token permission to access an org. This needs to be done
//via the UI. This means our resource will work fine if the user has sufficient admin permissions and at least one
//org exists. It also means that we can't use terraform to automate creation of the very first org in an enterprise.
//That sucks a little, but seems like a restriction we can live with.
//
//It would be nice if there was an API available in github to enable a token for SSO.
description := data.Get("description").(string)
displayName := data.Get("display_name").(string)
if description != "" || displayName != "" {
_, _, err = v3.Organizations.Edit(
context.Background(),
data.Get("name").(string),
&github.Organization{
Description: github.Ptr(description),
Name: github.Ptr(displayName),
},
)
if err != nil {
if isSAMLEnforcementError(err) {
// The org was created but we can't set description/display_name until the PAT is authorized.
// Clear them from state so next plan will show drift and retry after PAT authorization.
log.Printf("[WARN] Organization %q created but could not set description/display_name due to SAML enforcement. Authorize the PAT and run apply again.", data.Get("name").(string))
_ = data.Set("description", "")
_ = data.Set("display_name", "")
return nil
}
return err
}
}
return nil
}
func resourceGithubEnterpriseOrganizationRead(data *schema.ResourceData, meta any) error {
var query struct {
Node struct {
Organization struct {
ID githubv4.ID
DatabaseId githubv4.Int
Name githubv4.String
Login githubv4.String
Description githubv4.String
OrganizationBillingEmail githubv4.String
MembersWithRole struct {
Edges []struct {
User struct {
Login githubv4.String
} `graphql:"node"`
Role githubv4.String
} `graphql:"edges"`
PageInfo PageInfo
} `graphql:"membersWithRole(first:100, after:$cursor)"`
} `graphql:"... on Organization"`
} `graphql:"node(id: $id)"`
}
variables := map[string]any{
"id": data.Id(),
"cursor": (*githubv4.String)(nil),
}
var adminLogins []any
for {
v4 := meta.(*Owner).v4client
err := v4.Query(context.Background(), &query, variables)
if err != nil {
if strings.Contains(err.Error(), "Could not resolve to a node with the global id") {
log.Printf("[INFO] Removing organization (%s) from state because it no longer exists in GitHub", data.Id())
data.SetId("")
return nil
}
return err
}
for _, v := range query.Node.Organization.MembersWithRole.Edges {
if v.Role == "ADMIN" {
adminLogins = append(adminLogins, string(v.User.Login))
}
}
if !query.Node.Organization.MembersWithRole.PageInfo.HasNextPage {
break
}
variables["cursor"] = githubv4.NewString(query.Node.Organization.MembersWithRole.PageInfo.EndCursor)
}
err := data.Set("admin_logins", schema.NewSet(schema.HashString, adminLogins))
if err != nil {
return err
}
err = data.Set("name", query.Node.Organization.Login)
if err != nil {
return err
}
if query.Node.Organization.Name != query.Node.Organization.Login {
err = data.Set("display_name", query.Node.Organization.Name)
if err != nil {
return err
}
}
err = data.Set("billing_email", query.Node.Organization.OrganizationBillingEmail)
if err != nil {
return err
}
err = data.Set("database_id", query.Node.Organization.DatabaseId)
if err != nil {
return err
}
err = data.Set("description", query.Node.Organization.Description)
return err
}
func resourceGithubEnterpriseOrganizationDelete(data *schema.ResourceData, meta any) error {
owner := meta.(*Owner)
v3 := owner.v3client
ctx := context.WithValue(context.Background(), ctxId, data.Id())
_, err := v3.Organizations.Delete(ctx, data.Get("name").(string))
// We expect the delete to return with a 202 Accepted error so ignore those
acceptedError := &github.AcceptedError{}
if errors.As(err, &acceptedError) {
return nil
}
return err
}
func resourceGithubEnterpriseOrganizationImport(data *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
parts := strings.Split(data.Id(), "/")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid ID specified: supplied ID must be written as <enterprise_slug>/<org_name>")
}
v4 := meta.(*Owner).v4client
ctx := context.Background()
enterpriseId, err := getEnterpriseId(ctx, v4, parts[0])
if err != nil {
return nil, err
}
_ = data.Set("enterprise_id", enterpriseId)
orgId, err := getOrganizationId(ctx, v4, parts[1])
if err != nil {
return nil, err
}
data.SetId(orgId)
err = resourceGithubEnterpriseOrganizationRead(data, meta)
if err != nil {
return nil, err
}
return []*schema.ResourceData{data}, nil
}
func getEnterpriseId(ctx context.Context, v4 *githubv4.Client, enterpriseSlug string) (string, error) {
var query struct {
Enterprise struct {
ID githubv4.String
} `graphql:"enterprise(slug: $enterpriseSlug)"`
}
err := v4.Query(ctx, &query, map[string]any{"enterpriseSlug": githubv4.String(enterpriseSlug)})
if err != nil {
return "", err
}
return string(query.Enterprise.ID), nil
}
func getOrganizationId(ctx context.Context, v4 *githubv4.Client, orgName string) (string, error) {
var query struct {
Organization struct {
Id githubv4.String
} `graphql:"organization(login: $orgName)"`
}
err := v4.Query(ctx, &query, map[string]any{"orgName": githubv4.String(orgName)})
if err != nil {
return "", err
}
return string(query.Organization.Id), nil
}
func updateDescription(ctx context.Context, data *schema.ResourceData, v3 *github.Client) error {
orgName := data.Get("name").(string)
oldDesc, newDesc := stringChanges(data.GetChange("description"))
if oldDesc != newDesc {
_, _, err := v3.Organizations.Edit(
ctx,
orgName,
&github.Organization{
Description: github.Ptr(newDesc),
},
)
if err != nil {
if isSAMLEnforcementError(err) {
// Reset state to old value so next plan shows drift
log.Printf("[WARN] Could not update description for %q due to SAML enforcement. Authorize the PAT and run apply again.", orgName)
_ = data.Set("description", oldDesc)
return nil
}
return err
}
}
return nil
}
func updateDisplayName(ctx context.Context, data *schema.ResourceData, v4 *github.Client) error {
orgName := data.Get("name").(string)
oldDisplayName, newDisplayName := stringChanges(data.GetChange("display_name"))
if oldDisplayName != newDisplayName {
_, _, err := v4.Organizations.Edit(
ctx,
orgName,
&github.Organization{
Name: github.Ptr(newDisplayName),
},
)
if err != nil {
if isSAMLEnforcementError(err) {
// Reset state to old value so next plan shows drift
log.Printf("[WARN] Could not update display_name for %q due to SAML enforcement. Authorize the PAT and run apply again.", orgName)
_ = data.Set("display_name", oldDisplayName)
return nil
}
return err
}
}
return nil
}
func removeUsers(ctx context.Context, v3 *github.Client, v4 *githubv4.Client, toRemove []any, orgName string) error {
for _, user := range toRemove {
err := removeUser(ctx, v3, v4, user.(string), orgName)
if err != nil {
return err
}
}
return nil
}
func removeUser(ctx context.Context, v3 *github.Client, v4 *githubv4.Client, user, orgName string) error {
//How we remove an admin user from an enterprise organization depends on if the user is a member of any teams.
//If they are a member of any teams, we shouldn't delete them, instead we edit their membership role to be
//'MEMBER' instead of 'ADMIN'. If the user is not a member of any teams, then we remove from the org.
// First, use the v4 API to count how many teams the user is in
var query struct {
Organization struct {
Teams struct {
TotalCount githubv4.Int
} `graphql:"teams(first:1, userLogins:[$user])"`
} `graphql:"organization(login: $org)"`
}
err := v4.Query(
ctx,
&query,
map[string]any{
"org": githubv4.String(orgName),
"user": githubv4.String(user),
},
)
if err != nil {
return err
}
if query.Organization.Teams.TotalCount == 0 {
_, err = v3.Organizations.RemoveOrgMembership(ctx, user, orgName)
return err
}
membership, _, err := v3.Organizations.GetOrgMembership(ctx, user, orgName)
if err != nil {
return err
}
membership.Role = github.Ptr("member")
_, _, err = v3.Organizations.EditOrgMembership(ctx, user, orgName, membership)
return err
}
func updateAdminList(ctx context.Context, data *schema.ResourceData, orgName string, v3 *github.Client, v4 *githubv4.Client) error {
oldSet, newSet := setChanges(data.GetChange("admin_logins"))
toRemove := oldSet.Difference(newSet).List()
toAdd := newSet.Difference(oldSet).List()
err := addUsers(ctx, data, v4, toAdd)
if err != nil {
return err
}
return removeUsers(ctx, v3, v4, toRemove, orgName)
}
func addUsers(ctx context.Context, data *schema.ResourceData, v4 *githubv4.Client, toAdd []any) error {
if len(toAdd) != 0 {
var mutate struct {
AddEnterpriseOrganizationMember struct {
Ignored string `graphql:"clientMutationId"`
} `graphql:"addEnterpriseOrganizationMember(input: $input)"`
}
adminRole := githubv4.OrganizationMemberRoleAdmin
userIds, err := getUserIds(v4, toAdd)
if err != nil {
return err
}
input := githubv4.AddEnterpriseOrganizationMemberInput{
EnterpriseID: data.Get("enterprise_id"),
OrganizationID: data.Id(),
UserIDs: userIds,
Role: &adminRole,
}
err = v4.Mutate(ctx, &mutate, input, nil)
if err != nil {
return err
}
}
return nil
}
func updateBillingEmail(ctx context.Context, data *schema.ResourceData, orgName string, v3 *github.Client) error {
oldBilling, newBilling := stringChanges(data.GetChange("billing_email"))
if oldBilling != newBilling {
_, _, err := v3.Organizations.Edit(
ctx,
orgName,
&github.Organization{
BillingEmail: &newBilling,
},
)
if err != nil {
return err
}
}
return nil
}
func resourceGithubEnterpriseOrganizationUpdate(data *schema.ResourceData, meta any) error {
v3 := meta.(*Owner).v3client
v4 := meta.(*Owner).v4client
ctx := context.Background()
err := updateDisplayName(ctx, data, v3)
if err != nil {
return err
}
err = updateDescription(ctx, data, v3)
if err != nil {
return err
}
orgName := data.Get("name").(string)
err = updateAdminList(ctx, data, orgName, v3, v4)
if err != nil {
return err
}
return updateBillingEmail(ctx, data, orgName, v3)
}
func getUserIds(v4 *githubv4.Client, loginNames []any) ([]githubv4.ID, error) {
var query struct {
User struct {
ID githubv4.String
} `graphql:"user(login: $login)"`
}
var ret []githubv4.ID
for _, l := range loginNames {
err := v4.Query(context.Background(), &query, map[string]any{"login": githubv4.String(l.(string))})
if err != nil {
return nil, err
}
ret = append(ret, query.User.ID)
}
return ret, nil
}
func stringChanges(oldValue, newValue any) (string, string) {
oldString, _ := oldValue.(string)
newString, _ := newValue.(string)
return oldString, newString
}
func setChanges(oldValue, newValue any) (*schema.Set, *schema.Set) {
oldSet, _ := oldValue.(*schema.Set)
newSet, _ := newValue.(*schema.Set)
if oldSet == nil {
oldSet = schema.NewSet(schema.HashString, nil)
}
if newSet == nil {
newSet = schema.NewSet(schema.HashString, nil)
}
return oldSet, newSet
}