Skip to content

Commit 08aa432

Browse files
authored
Merge branch 'main' into feat/enterprise-ip-allow-list
2 parents 5dd8ef6 + 1af72d4 commit 08aa432

2 files changed

Lines changed: 57 additions & 4 deletions

File tree

github/provider.go

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -498,17 +498,27 @@ func providerConfigure(p *schema.Provider) schema.ConfigureContextFunc {
498498
}
499499
}
500500

501+
// ghCLIHostFromAPIHost maps an API hostname to the corresponding
502+
// gh-CLI --hostname value. For example api.github.com -> github.com
503+
// and api.<slug>.ghe.com -> <slug>.ghe.com.
504+
// for unrecognized hostnames, input is returned unmodified.
505+
func ghCLIHostFromAPIHost(host string) string {
506+
if host == DotComAPIHost {
507+
return DotComHost
508+
} else if GHECAPIHostMatch.MatchString(host) {
509+
return strings.TrimPrefix(host, "api.")
510+
}
511+
return host
512+
}
513+
501514
// See https://github.com/integrations/terraform-provider-github/issues/1822
502515
func tokenFromGHCLI(u *url.URL) string {
503516
ghCliPath := os.Getenv("GH_PATH")
504517
if ghCliPath == "" {
505518
ghCliPath = "gh"
506519
}
507520

508-
host := u.Host
509-
if host == DotComAPIHost {
510-
host = DotComHost
511-
}
521+
host := ghCLIHostFromAPIHost(u.Host)
512522

513523
out, err := exec.Command(ghCliPath, "auth", "token", "--hostname", host).Output()
514524
if err != nil {

github/provider_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,3 +259,46 @@ data "github_ip_ranges" "test" {}
259259
})
260260
})
261261
}
262+
263+
func Test_ghCLIHostFromAPIHost(t *testing.T) {
264+
testCases := []struct {
265+
name string
266+
host string
267+
expectedHost string
268+
}{
269+
{
270+
name: "dotcom API host is mapped to dotcom host",
271+
host: "api.github.com",
272+
expectedHost: "github.com",
273+
},
274+
{
275+
name: "ghec API host has api. prefix stripped",
276+
host: "api.my-enterprise.ghe.com",
277+
expectedHost: "my-enterprise.ghe.com",
278+
},
279+
{
280+
name: "ghec API host with numbers has api. prefix stripped",
281+
host: "api.customer-123.ghe.com",
282+
expectedHost: "customer-123.ghe.com",
283+
},
284+
{
285+
name: "ghes host is passed through unchanged",
286+
host: "github.example.com",
287+
expectedHost: "github.example.com",
288+
},
289+
{
290+
name: "ghes host with port is passed through unchanged",
291+
host: "github.example.com:8443",
292+
expectedHost: "github.example.com:8443",
293+
},
294+
}
295+
296+
for _, tc := range testCases {
297+
t.Run(tc.name, func(t *testing.T) {
298+
got := ghCLIHostFromAPIHost(tc.host)
299+
if got != tc.expectedHost {
300+
t.Errorf("ghCLIHostFromAPIHost(%q) = %q, want %q", tc.host, got, tc.expectedHost)
301+
}
302+
})
303+
}
304+
}

0 commit comments

Comments
 (0)