|
| 1 | +package githubauth |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "net/url" |
| 11 | + "time" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + // defaultBaseURL is the default GitHub API base URL. |
| 16 | + defaultBaseURL = "https://api.github.com/" |
| 17 | +) |
| 18 | + |
| 19 | +// InstallationTokenOptions specifies options for creating an installation token. |
| 20 | +type InstallationTokenOptions struct { |
| 21 | + // Repositories is a list of repository names that the token should have access to. |
| 22 | + Repositories []string `json:"repositories,omitempty"` |
| 23 | + // RepositoryIDs is a list of repository IDs that the token should have access to. |
| 24 | + RepositoryIDs []int64 `json:"repository_ids,omitempty"` |
| 25 | + // Permissions are the permissions granted to the access token. |
| 26 | + Permissions *InstallationPermissions `json:"permissions,omitempty"` |
| 27 | +} |
| 28 | + |
| 29 | +// InstallationPermissions represents the permissions granted to an installation token. |
| 30 | +type InstallationPermissions struct { |
| 31 | + Actions *string `json:"actions,omitempty"` |
| 32 | + Administration *string `json:"administration,omitempty"` |
| 33 | + Checks *string `json:"checks,omitempty"` |
| 34 | + Contents *string `json:"contents,omitempty"` |
| 35 | + ContentReferences *string `json:"content_references,omitempty"` |
| 36 | + Deployments *string `json:"deployments,omitempty"` |
| 37 | + Environments *string `json:"environments,omitempty"` |
| 38 | + Issues *string `json:"issues,omitempty"` |
| 39 | + Metadata *string `json:"metadata,omitempty"` |
| 40 | + Packages *string `json:"packages,omitempty"` |
| 41 | + Pages *string `json:"pages,omitempty"` |
| 42 | + PullRequests *string `json:"pull_requests,omitempty"` |
| 43 | + RepositoryAnnouncementBanners *string `json:"repository_announcement_banners,omitempty"` |
| 44 | + RepositoryHooks *string `json:"repository_hooks,omitempty"` |
| 45 | + RepositoryProjects *string `json:"repository_projects,omitempty"` |
| 46 | + SecretScanningAlerts *string `json:"secret_scanning_alerts,omitempty"` |
| 47 | + Secrets *string `json:"secrets,omitempty"` |
| 48 | + SecurityEvents *string `json:"security_events,omitempty"` |
| 49 | + SingleFile *string `json:"single_file,omitempty"` |
| 50 | + Statuses *string `json:"statuses,omitempty"` |
| 51 | + VulnerabilityAlerts *string `json:"vulnerability_alerts,omitempty"` |
| 52 | + Workflows *string `json:"workflows,omitempty"` |
| 53 | + Members *string `json:"members,omitempty"` |
| 54 | + OrganizationAdministration *string `json:"organization_administration,omitempty"` |
| 55 | + OrganizationCustomRoles *string `json:"organization_custom_roles,omitempty"` |
| 56 | + OrganizationAnnouncementBanners *string `json:"organization_announcement_banners,omitempty"` |
| 57 | + OrganizationHooks *string `json:"organization_hooks,omitempty"` |
| 58 | + OrganizationPlan *string `json:"organization_plan,omitempty"` |
| 59 | + OrganizationProjects *string `json:"organization_projects,omitempty"` |
| 60 | + OrganizationPackages *string `json:"organization_packages,omitempty"` |
| 61 | + OrganizationSecrets *string `json:"organization_secrets,omitempty"` |
| 62 | + OrganizationSelfHostedRunners *string `json:"organization_self_hosted_runners,omitempty"` |
| 63 | + OrganizationUserBlocking *string `json:"organization_user_blocking,omitempty"` |
| 64 | + TeamDiscussions *string `json:"team_discussions,omitempty"` |
| 65 | +} |
| 66 | + |
| 67 | +// InstallationToken represents a GitHub App installation token. |
| 68 | +type InstallationToken struct { |
| 69 | + Token string `json:"token"` |
| 70 | + ExpiresAt time.Time `json:"expires_at"` |
| 71 | + Permissions *InstallationPermissions `json:"permissions,omitempty"` |
| 72 | + Repositories []Repository `json:"repositories,omitempty"` |
| 73 | +} |
| 74 | + |
| 75 | +// Repository represents a GitHub repository. |
| 76 | +type Repository struct { |
| 77 | + ID *int64 `json:"id,omitempty"` |
| 78 | + Name *string `json:"name,omitempty"` |
| 79 | +} |
| 80 | + |
| 81 | +// githubClient is a simple GitHub API client for creating installation tokens. |
| 82 | +type githubClient struct { |
| 83 | + baseURL *url.URL |
| 84 | + client *http.Client |
| 85 | +} |
| 86 | + |
| 87 | +// newGitHubClient creates a new GitHub API client. |
| 88 | +func newGitHubClient(httpClient *http.Client) *githubClient { |
| 89 | + baseURL, _ := url.Parse(defaultBaseURL) |
| 90 | + |
| 91 | + return &githubClient{ |
| 92 | + baseURL: baseURL, |
| 93 | + client: httpClient, |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +// withEnterpriseURL sets the base URL for GitHub Enterprise Server. |
| 98 | +func (c *githubClient) withEnterpriseURL(baseURL string) (*githubClient, error) { |
| 99 | + base, err := url.Parse(baseURL) |
| 100 | + if err != nil { |
| 101 | + return nil, fmt.Errorf("failed to parse base URL: %w", err) |
| 102 | + } |
| 103 | + |
| 104 | + c.baseURL = base |
| 105 | + |
| 106 | + return c, nil |
| 107 | +} |
| 108 | + |
| 109 | +// createInstallationToken creates an installation access token for a GitHub App. |
| 110 | +// API documentation: https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app |
| 111 | +func (c *githubClient) createInstallationToken(ctx context.Context, installationID int64, opts *InstallationTokenOptions) (*InstallationToken, error) { |
| 112 | + endpoint := fmt.Sprintf("app/installations/%d/access_tokens", installationID) |
| 113 | + u, err := c.baseURL.Parse(endpoint) |
| 114 | + if err != nil { |
| 115 | + return nil, fmt.Errorf("failed to parse endpoint URL: %w", err) |
| 116 | + } |
| 117 | + |
| 118 | + var body io.Reader |
| 119 | + if opts != nil { |
| 120 | + jsonBody, err := json.Marshal(opts) |
| 121 | + if err != nil { |
| 122 | + return nil, fmt.Errorf("failed to marshal request body: %w", err) |
| 123 | + } |
| 124 | + body = bytes.NewReader(jsonBody) |
| 125 | + } |
| 126 | + |
| 127 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), body) |
| 128 | + if err != nil { |
| 129 | + return nil, fmt.Errorf("failed to create request: %w", err) |
| 130 | + } |
| 131 | + |
| 132 | + req.Header.Set("Accept", "application/vnd.github+json") |
| 133 | + req.Header.Set("Content-Type", "application/json") |
| 134 | + |
| 135 | + resp, err := c.client.Do(req) |
| 136 | + if err != nil { |
| 137 | + return nil, fmt.Errorf("failed to execute request: %w", err) |
| 138 | + } |
| 139 | + defer resp.Body.Close() |
| 140 | + |
| 141 | + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { |
| 142 | + bodyBytes, _ := io.ReadAll(resp.Body) |
| 143 | + return nil, fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, string(bodyBytes)) |
| 144 | + } |
| 145 | + |
| 146 | + var token InstallationToken |
| 147 | + if err := json.NewDecoder(resp.Body).Decode(&token); err != nil { |
| 148 | + return nil, fmt.Errorf("failed to decode response: %w", err) |
| 149 | + } |
| 150 | + |
| 151 | + return &token, nil |
| 152 | +} |
| 153 | + |
| 154 | +// ptr is a helper function to create a pointer to a value. |
| 155 | +func ptr[T any](v T) *T { |
| 156 | + return &v |
| 157 | +} |
0 commit comments