Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions github/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,8 @@ func tokenFromGHCLI(u *url.URL) string {
host := u.Host
if host == DotComAPIHost {
host = DotComHost
} else if GHECAPIHostMatch.MatchString(host) {
host = strings.TrimPrefix(host, "api.")
}
Comment thread
clawster marked this conversation as resolved.
Outdated

out, err := exec.Command(ghCliPath, "auth", "token", "--hostname", host).Output()
Expand Down
65 changes: 65 additions & 0 deletions github/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package github

import (
"fmt"
"net/url"
"os"
"path/filepath"
"regexp"
"testing"

Expand Down Expand Up @@ -259,3 +262,65 @@ data "github_ip_ranges" "test" {}
})
})
}

func Test_tokenFromGHCLI(t *testing.T) {
Comment thread
clawster marked this conversation as resolved.
Outdated
// Create a fake gh CLI script that echoes back the hostname it receives.
// tokenFromGHCLI calls: gh auth token --hostname <host>
// Our fake script extracts the hostname argument and prints it as the "token".
tmpDir := t.TempDir()
fakeGH := filepath.Join(tmpDir, "gh")
err := os.WriteFile(fakeGH, []byte("#!/bin/sh\necho \"$4\"\n"), 0755)
if err != nil {
t.Fatalf("failed to create fake gh script: %s", err)
}

testCases := []struct {
name string
url string
expectedHost string
}{
{
name: "dotcom API host is mapped to dotcom host",
url: "https://api.github.com/",
expectedHost: "github.com",
},
{
name: "ghec API host has api. prefix stripped",
url: "https://api.my-enterprise.ghe.com/",
expectedHost: "my-enterprise.ghe.com",
},
{
name: "ghec API host with numbers has api. prefix stripped",
url: "https://api.customer-123.ghe.com/",
expectedHost: "customer-123.ghe.com",
},
{
name: "ghes host is passed through unchanged",
url: "https://github.example.com/",
expectedHost: "github.example.com",
},
{
name: "ghes host with port is passed through unchanged",
url: "https://github.example.com:8443/",
expectedHost: "github.example.com:8443",
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("GH_PATH", fakeGH)

u, err := url.Parse(tc.url)
if err != nil {
t.Fatalf("failed to parse URL %q: %s", tc.url, err)
}

// tokenFromGHCLI returns the trimmed output of the fake script,
// which is the hostname argument passed to `gh auth token --hostname`.
got := tokenFromGHCLI(u)
if got != tc.expectedHost {
t.Errorf("tokenFromGHCLI(%q): hostname passed to gh CLI = %q, want %q", tc.url, got, tc.expectedHost)
}
})
}
}
Comment thread
clawster marked this conversation as resolved.
Outdated