Skip to content
Merged
Changes from all 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
53 changes: 23 additions & 30 deletions internal/githubclient/client.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package githubclient

import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"time"
Expand Down Expand Up @@ -95,44 +96,36 @@ func generateAppJWT(appID string, issuedAt time.Time, privateKeyPEM []byte) (str
}

func getInstallationAccessToken(baseURL, appJWT, installationID string) (string, error) {
tc := &http.Client{
Transport: &jwtTransport{
token: appJWT,
rt: http.DefaultTransport,
},
Timeout: 30 * time.Second,
}
url := fmt.Sprintf("%s/app/installations/%s/access_tokens", baseURL, installationID)

client, err := github.NewClient(tc).WithEnterpriseURLs(baseURL, baseURL)
req, err := http.NewRequest("POST", url, nil)
if err != nil {
return "", fmt.Errorf("failed to create github client: %v", err)
return "", fmt.Errorf("failed to create request: %v", err)
}

installationIDInt, err := strconv.ParseInt(installationID, 10, 64)
req.Header.Set("Authorization", "Bearer "+appJWT)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("User-Agent", "terraform-provider-kw-github")

client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("invalid installation ID: %v", err)
return "", fmt.Errorf("failed to make request: %v", err)
}
defer resp.Body.Close()

token, _, err := client.Apps.CreateInstallationToken(
context.Background(),
installationIDInt,
&github.InstallationTokenOptions{},
)
if err != nil {
return "", fmt.Errorf("failed to create installation token: %v", err)
if resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("failed to get access token: %s - %s", resp.Status, string(body))
}

return token.GetToken(), nil
}
var tokenResp struct {
Token string `json:"token"`
}

type jwtTransport struct {
token string
rt http.RoundTripper
}
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
return "", fmt.Errorf("failed to decode response: %v", err)
}

func (t *jwtTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", "Bearer "+t.token)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("User-Agent", "terraform-provider-kw-github")
return t.rt.RoundTrip(req)
return tokenResp.Token, nil
}
Loading