githubauth

package module
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 20, 2026 License: MIT Imports: 21 Imported by: 16

README

go-githubauth

GoDoc Test Status codecov Go Report Card Mentioned in Awesome Go

go-githubauth is a Go package that provides utilities for GitHub authentication, including generating and using GitHub App tokens, installation tokens, and personal access tokens.

v1.5.0 removes the go-github dependency, implementing a lightweight internal GitHub API client. This reduces external dependencies while maintaining full compatibility with the OAuth2 token source interface.


Found this package useful? Give it a star on GitHub! Your support helps others discover this project and motivates continued development.

Star this repo

Share this project: Share on X Share on Reddit


Features

go-githubauth package provides implementations of the TokenSource interface from the golang.org/x/oauth2 package. This interface has a single method, Token, which returns an *oauth2.Token.

v1.5.0 Features
  • 📦 Zero External Dependencies: Removed go-github dependency - lightweight internal implementation
  • 🔐 Personal Access Token Support: Native support for both classic and fine-grained personal access tokens
  • ⚡ Token Caching: Dual-layer caching system for optimal performance
    • JWT tokens cached until expiration (up to 10 minutes)
    • Installation tokens cached until expiration (defined by GitHub response)
  • 🚀 Pooled HTTP Client: Production-ready HTTP client with connection pooling
  • 📈 Performance Optimizations: Up to 99% reduction in unnecessary GitHub API calls
  • 🏗️ Production Ready: Optimized for high-throughput and enterprise applications
  • 🌐 Simplified Enterprise Support: Streamlined configuration with single base URL parameter
Core Capabilities
  • Generate GitHub Application JWT Generating a jwt for a github app
  • Obtain GitHub App installation tokens Authenticating as a GitHub App
  • Authenticate with Personal Access Tokens (classic and fine-grained) Managing your personal access tokens
  • Verify incoming webhook deliveries with constant-time HMAC-SHA256 checks Validating webhook deliveries
  • Sign JWTs with external crypto.Signer backends (AWS KMS, GCP KMS, Azure Key Vault, HashiCorp Vault Transit, PKCS#11 HSMs, ssh-agent) so the private key never touches process memory
  • RS256-signed JWTs with proper clock drift protection
  • Support for both legacy App IDs and modern Client IDs (recommended by GitHub)
  • Intelligent token caching with proactive refresh — tokens are regenerated 30s before expiry to eliminate in-flight 401s (tunable via WithExpirySkew / WithInstallationExpirySkew)
  • Clean HTTP clients with connection pooling and no shared state
Requirements
  • Go 1.25 or higher (required by golang.org/x/oauth2)
  • This package is designed to be used with the golang.org/x/oauth2 package
  • No external GitHub SDK dependencies required

Installation

To use go-githubauth in your project, you need to have Go installed. You can get the package via:

go get -u github.com/jferrl/go-githubauth

Usage

Usage with oauth2

You can use this package standalone with any HTTP client, or integrate it with the go-github SDK if you need additional GitHub API functionality.

package main

import (
 "context"
 "fmt"
 "os"
 "strconv"

 "github.com/google/go-github/v76/github"
 "github.com/jferrl/go-githubauth"
 "golang.org/x/oauth2"
)

func main() {
 privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
 clientID := os.Getenv("GITHUB_APP_CLIENT_ID") // e.g., "Iv1.1234567890abcdef"
 installationID, _ := strconv.ParseInt(os.Getenv("GITHUB_INSTALLATION_ID"), 10, 64)

 // Go automatically infers the type as string for Client ID
 appTokenSource, err := githubauth.NewApplicationTokenSource(clientID, privateKey)
 if err != nil {
  fmt.Println("Error creating application token source:", err)
  return
 }

 installationTokenSource := githubauth.NewInstallationTokenSource(installationID, appTokenSource)

 // oauth2.NewClient creates a new http.Client that adds an Authorization header with the token
 httpClient := oauth2.NewClient(context.Background(), installationTokenSource)
 githubClient := github.NewClient(httpClient)

 _, _, err = githubClient.PullRequests.CreateComment(context.Background(), "owner", "repo", 1, &github.PullRequestComment{
  Body: github.String("Awesome comment!"),
 })
 if err != nil {
  fmt.Println("Error creating comment:", err)
  return
 }
}
App ID (Legacy)
package main

import (
 "context"
 "fmt"
 "os"
 "strconv"

 "github.com/google/go-github/v76/github"
 "github.com/jferrl/go-githubauth"
 "golang.org/x/oauth2"
)

func main() {
 privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
 appID, _ := strconv.ParseInt(os.Getenv("GITHUB_APP_ID"), 10, 64)
 installationID, _ := strconv.ParseInt(os.Getenv("GITHUB_INSTALLATION_ID"), 10, 64)

 // Explicitly cast to int64 for App ID - Go automatically infers the type
 appTokenSource, err := githubauth.NewApplicationTokenSource(int64(appID), privateKey)
 if err != nil {
  fmt.Println("Error creating application token source:", err)
  return
 }

 installationTokenSource := githubauth.NewInstallationTokenSource(installationID, appTokenSource)

 httpClient := oauth2.NewClient(context.Background(), installationTokenSource)
 githubClient := github.NewClient(httpClient)

 _, _, err = githubClient.PullRequests.CreateComment(context.Background(), "owner", "repo", 1, &github.PullRequestComment{
  Body: github.String("Awesome comment!"),
 })
 if err != nil {
  fmt.Println("Error creating comment:", err)
  return
 }
}
Generate GitHub Application Token

First, create a GitHub App and generate a private key. To authenticate as a GitHub App, you need to generate a JWT. Generating a JWT for a GitHub App

package main

import (
 "fmt"
 "os"
 "time"

 "github.com/jferrl/go-githubauth"
)

func main() {
 privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
 clientID := os.Getenv("GITHUB_APP_CLIENT_ID") // e.g., "Iv1.1234567890abcdef"

 // Type automatically inferred as string
 tokenSource, err := githubauth.NewApplicationTokenSource(
  clientID, 
  privateKey, 
  githubauth.WithApplicationTokenExpiration(5*time.Minute),
 )
 if err != nil {
  fmt.Println("Error creating token source:", err)
  return
 }

 token, err := tokenSource.Token()
 if err != nil {
  fmt.Println("Error generating token:", err)
  return
 }

 fmt.Println("Generated JWT token:", token.AccessToken)
}
With App ID
package main

import (
 "fmt"
 "os"
 "strconv"
 "time"

 "github.com/jferrl/go-githubauth"
)

func main() {
 privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
 appID, _ := strconv.ParseInt(os.Getenv("GITHUB_APP_ID"), 10, 64)

 // Type automatically inferred as int64
 tokenSource, err := githubauth.NewApplicationTokenSource(
  int64(appID), 
  privateKey, 
  githubauth.WithApplicationTokenExpiration(5*time.Minute),
 )
 if err != nil {
  fmt.Println("Error creating token source:", err)
  return
 }

 token, err := tokenSource.Token()
 if err != nil {
  fmt.Println("Error generating token:", err)
  return
 }

 fmt.Println("Generated JWT token:", token.AccessToken)
}
Generate GitHub App Installation Token

To authenticate as a GitHub App installation, you need to obtain an installation token using your GitHub App JWT.

package main

import (
 "fmt"
 "os"
 "strconv"

 "github.com/jferrl/go-githubauth"
)

func main() {
 privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
 clientID := os.Getenv("GITHUB_APP_CLIENT_ID") // e.g., "Iv1.1234567890abcdef"
 installationID, _ := strconv.ParseInt(os.Getenv("GITHUB_INSTALLATION_ID"), 10, 64)

 // Create GitHub App JWT token source with Client ID
 appTokenSource, err := githubauth.NewApplicationTokenSource(clientID, privateKey)
 if err != nil {
  fmt.Println("Error creating application token source:", err)
  return
 }

 // Create installation token source using the app token source
 installationTokenSource := githubauth.NewInstallationTokenSource(installationID, appTokenSource)

 token, err := installationTokenSource.Token()
 if err != nil {
  fmt.Println("Error generating installation token:", err)
  return
 }

 fmt.Println("Generated installation token:", token.AccessToken)
}
Proactive Token Refresh

oauth2.ReuseTokenSource only refreshes a cached token after its expiry has passed. A request that starts at T-100ms with a token expiring at T can arrive at GitHub with an already-expired credential and receive a 401 that the caller must manually retry. This is especially painful with short application-token windows (default 10 min, optionally lower).

Both NewApplicationTokenSource and NewInstallationTokenSource wrap the returned source in ReuseTokenSourceWithSkew, which refreshes when time.Until(exp) <= skew. The default DefaultExpirySkew is 30 seconds, so a default 10-minute application JWT has ~9m30s of effective validity — the tail risk is closed, the overhead is negligible.

// Use a shorter skew (e.g. to maximize validity for very short JWTs).
appTokenSource, err := githubauth.NewApplicationTokenSource(
    clientID,
    privateKey,
    githubauth.WithApplicationTokenExpiration(1*time.Minute),
    githubauth.WithExpirySkew(5*time.Second),
)

// Override the installation-layer skew too (default 30s is usually fine for 1h tokens).
installationTokenSource := githubauth.NewInstallationTokenSource(
    installationID,
    appTokenSource,
    githubauth.WithInstallationExpirySkew(1*time.Minute),
)

Passing WithExpirySkew(0) (or any non-positive value) disables the skew and falls back to the exact oauth2.ReuseTokenSource behavior. For third-party oauth2.TokenSource implementations outside this package, ReuseTokenSourceWithSkew is exported directly:

src := githubauth.ReuseTokenSourceWithSkew(nil, someTokenSource, 30*time.Second)

The wrapper is safe for concurrent use — concurrent Token() calls that find the cache stale collapse into a single upstream fetch.

Signing with External Key Stores (AWS KMS, GCP KMS, Vault, HSM)

For regulated or high-security environments, the private key should never leave its secure boundary. NewApplicationTokenSourceFromSigner accepts any crypto.Signer whose public key is RSA — AWS KMS, Google Cloud KMS, Azure Key Vault, HashiCorp Vault Transit, PKCS#11 HSMs, and ssh-agent all fit.

The same crypto.Signer call (Sign(rand, digest, crypto.SHA256)) maps to each backend's native RSASSA-PKCS1-v1_5 SHA-256 signing operation. GitHub requires RS256.

package main

import (
 "context"
 "fmt"
 "os"

 "github.com/jferrl/go-githubauth"
)

func main() {
 clientID := os.Getenv("GITHUB_APP_CLIENT_ID")

 // signer is any crypto.Signer backed by an RSA key: *rsa.PrivateKey,
 // an AWS KMS wrapper, a GCP KMS wrapper, a Vault Transit wrapper,
 // a PKCS#11 HSM library like github.com/ThalesGroup/crypto11, or
 // an ssh-agent adapter. The private key never touches process memory.
 signer := newKMSBackedSigner(context.Background(), os.Getenv("KMS_KEY_ARN"))

 appTokenSource, err := githubauth.NewApplicationTokenSourceFromSigner(clientID, signer)
 if err != nil {
  fmt.Println("Error creating application token source:", err)
  return
 }

 token, err := appTokenSource.Token()
 if err != nil {
  fmt.Println("Error generating JWT:", err)
  return
 }

 fmt.Println("Generated JWT token:", token.AccessToken)
}

Backend references (all support RSASSA_PKCS1_V1_5_SHA_256 on RSA keys ≥ 2048):

🔐 Security Note: The signer's public key must be RSA. The constructor rejects non-RSA signers (ECDSA, ed25519) at construction time since GitHub requires RS256.

Personal Access Token Authentication

GitHub Personal Access Tokens provide direct authentication for users and organizations. This package supports both classic personal access tokens and fine-grained personal access tokens.

Using Personal Access Tokens
With oauth2 Client (Standalone)
package main

import (
 "context"
 "fmt"
 "io"
 "net/http"
 "os"

 "github.com/jferrl/go-githubauth"
 "golang.org/x/oauth2"
)

func main() {
 // Personal access token from environment variable
 token := os.Getenv("GITHUB_TOKEN") // e.g., "ghp_..." or "github_pat_..."

 // Create token source
 tokenSource := githubauth.NewPersonalAccessTokenSource(token)

 // Create HTTP client with OAuth2 transport
 httpClient := oauth2.NewClient(context.Background(), tokenSource)

 // Use the HTTP client for GitHub API calls
 resp, err := httpClient.Get("https://api.github.com/user")
 if err != nil {
  fmt.Println("Error getting user:", err)
  return
 }
 defer resp.Body.Close()

 body, _ := io.ReadAll(resp.Body)
 fmt.Printf("User info: %s\n", body)
}
With go-github SDK (Optional)
package main

import (
 "context"
 "fmt"
 "os"

 "github.com/google/go-github/v76/github"
 "github.com/jferrl/go-githubauth"
 "golang.org/x/oauth2"
)

func main() {
 // Personal access token from environment variable
 token := os.Getenv("GITHUB_TOKEN") // e.g., "ghp_..." or "github_pat_..."

 // Create token source
 tokenSource := githubauth.NewPersonalAccessTokenSource(token)

 // Create HTTP client with OAuth2 transport
 httpClient := oauth2.NewClient(context.Background(), tokenSource)
 githubClient := github.NewClient(httpClient)

 // Use the GitHub client for API calls
 user, _, err := githubClient.Users.Get(context.Background(), "")
 if err != nil {
  fmt.Println("Error getting user:", err)
  return
 }

 fmt.Printf("Authenticated as: %s\n", user.GetLogin())
}
Creating Personal Access Tokens
  1. Classic Personal Access Token: Visit GitHub Settings > Developer settings > Personal access tokens > Tokens (classic)
  2. Fine-grained Personal Access Token: Visit GitHub Settings > Developer settings > Personal access tokens > Fine-grained tokens

🔐 Security Note: Store your personal access tokens securely and never commit them to version control. Use environment variables or secure credential management systems.

Webhook Signature Verification

GitHub signs every webhook delivery with HMAC-SHA256 over the raw request body, using the secret configured on the webhook. The webhook subpackage verifies the X-Hub-Signature-256 header in constant time and ships an http.Handler middleware that restores the body for downstream handlers.

See Validating webhook deliveries.

package main

import (
 "encoding/json"
 "log"
 "net/http"
 "os"

 "github.com/jferrl/go-githubauth/webhook"
)

func main() {
 secret := []byte(os.Getenv("GITHUB_WEBHOOK_SECRET"))

 mux := http.NewServeMux()
 mux.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {
  event := r.Header.Get(webhook.EventHeader)
  delivery := r.Header.Get(webhook.DeliveryHeader)

  var payload map[string]any
  if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
   http.Error(w, "bad payload", http.StatusBadRequest)
   return
  }

  log.Printf("received %s delivery=%s", event, delivery)
  w.WriteHeader(http.StatusNoContent)
 })

 // Middleware verifies the signature, restores r.Body, then invokes mux.
 // Failed verifications short-circuit with 401; oversized bodies return 413.
 log.Fatal(http.ListenAndServe(":8080", webhook.Middleware(secret)(mux)))
}

Middleware options:

  • webhook.WithMaxPayloadSize(n int64) — override the 25 MiB default cap (GitHub's documented delivery limit).
  • webhook.WithErrorHandler(fn) — customize the response for verification failures (e.g., structured logging, alternate status codes).
Direct verification (queues, Lambda, custom transports)

Use webhook.Verify when the request does not arrive through net/http, for example in AWS Lambda, Cloud Run event triggers, or after consuming from a message queue.

import (
 "errors"

 "github.com/jferrl/go-githubauth/webhook"
)

func handle(secret, body []byte, signature string) error {
 if err := webhook.Verify(secret, body, signature); err != nil {
  switch {
  case errors.Is(err, webhook.ErrMissingSignature):
   // header absent
  case errors.Is(err, webhook.ErrInvalidSignatureFormat):
   // malformed header
  case errors.Is(err, webhook.ErrSignatureMismatch):
   // wrong secret or tampered body
  }
  return err
 }
 // body is trusted from here
 return nil
}

🔐 Security Note: Store the webhook secret with the same care as a credential. A leaked secret lets an attacker forge deliveries to your endpoint.

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Overview

Package githubauth provides utilities for GitHub authentication, including generating and using GitHub App tokens and installation tokens.

This package implements oauth2.TokenSource interfaces for GitHub App authentication and GitHub App installation token generation. It is built on top of the golang.org/x/oauth2 library.

Index

Constants

View Source
const (
	// DefaultApplicationTokenExpiration is the default expiration time for GitHub App tokens.
	// The maximum allowed expiration is 10 minutes.
	DefaultApplicationTokenExpiration = 10 * time.Minute

	// DefaultExpirySkew is the default early-refresh window applied to cached
	// tokens returned by NewApplicationTokenSource and NewInstallationTokenSource.
	// At 30s the effective validity of a default 10-minute application JWT becomes
	// 9m30s, which is acceptable and eliminates the common in-flight 401 caused
	// by a request starting near exp and arriving at GitHub after exp.
	DefaultExpirySkew = 30 * time.Second
)

Variables

View Source
var ErrRateLimited = errors.New("github API rate limited")

ErrRateLimited wraps errors returned when GitHub has throttled a request (HTTP 429 or 403 with rate-limit headers). Callers can branch with errors.Is.

Functions

func NewApplicationTokenSource

func NewApplicationTokenSource[T Identifier](id T, privateKey []byte, opts ...ApplicationTokenOpt) (oauth2.TokenSource, error)

NewApplicationTokenSource creates a GitHub App JWT token source from a PEM-encoded RSA private key. Accepts either int64 App ID or string Client ID. GitHub recommends Client IDs for new apps. Generated JWTs are RS256-signed with iat, exp, and iss claims. JWTs expire in max 10 minutes and include clock drift protection (iat set 60s in past).

The returned token source is wrapped in ReuseTokenSourceWithSkew with DefaultExpirySkew (30s), so cached tokens are refreshed before exp rather than after. With the default 10-minute expiration the effective validity is 9m30s. Override with WithExpirySkew.

For KMS, HSM, Vault, or ssh-agent backed signing, use NewApplicationTokenSourceFromSigner instead — the private key never leaves its secure boundary.

See https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app

func NewApplicationTokenSourceFromSigner added in v1.6.0

func NewApplicationTokenSourceFromSigner[T Identifier](id T, signer crypto.Signer, opts ...ApplicationTokenOpt) (oauth2.TokenSource, error)

NewApplicationTokenSourceFromSigner creates a GitHub App JWT token source backed by an external crypto.Signer. Any RSA-backed signer works: AWS KMS, GCP KMS, Azure Key Vault, HashiCorp Vault Transit, PKCS#11 HSMs, or ssh-agent. The private key never touches process memory.

The signer's public key must be RSA — GitHub requires RS256 (RSASSA-PKCS1-v1_5 with SHA-256, per RFC 7518 §3.3). The signer must return signatures in that form when called with crypto.SHA256; every stdlib-compatible RSA signer does.

See https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app

func NewInstallationTokenSource

func NewInstallationTokenSource(id int64, src oauth2.TokenSource, opts ...InstallationTokenSourceOpt) oauth2.TokenSource

NewInstallationTokenSource creates a GitHub App installation token source. Requires installation ID and a GitHub App JWT token source for authentication.

The returned token source is wrapped in ReuseTokenSourceWithSkew so cached tokens are refreshed DefaultExpirySkew before their expiry, eliminating in-flight 401s when a request starts close to exp and reaches GitHub after. Override the window with WithInstallationExpirySkew.

See https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-an-installation-access-token-for-a-github-app

func NewPersonalAccessTokenSource added in v1.4.0

func NewPersonalAccessTokenSource(token string) oauth2.TokenSource

NewPersonalAccessTokenSource creates a token source for GitHub personal access tokens. The provided token should be a valid GitHub personal access token (classic or fine-grained). This token source returns the same token value for all Token() calls without expiration, making it suitable for long-lived authentication scenarios.

func Ptr added in v1.5.0

func Ptr[T any](v T) *T

Ptr is a helper function to create a pointer to a value. This is useful when constructing InstallationTokenOptions with permissions.

func ReuseTokenSourceWithSkew added in v1.6.0

func ReuseTokenSourceWithSkew(t *oauth2.Token, src oauth2.TokenSource, skew time.Duration) oauth2.TokenSource

ReuseTokenSourceWithSkew wraps src so cached tokens are refreshed proactively, skew before their expiry. oauth2.ReuseTokenSource refreshes only once exp has passed (via oauth2.Token.Valid), so a request that starts at T-100ms with a token expiring at T can arrive at GitHub already expired and yield a 401 the caller must manually retry. This wrapper refreshes when time.Until(t.Expiry) <= skew, cutting out that race.

If skew is zero or negative the wrapper delegates to oauth2.ReuseTokenSource, preserving its exact behavior. An initial non-nil t is used until it needs refresh under the same rule. The returned source is safe for concurrent use; concurrent Token calls that find the cache stale collapse into a single upstream fetch.

Types

type ApplicationTokenOpt

type ApplicationTokenOpt func(*applicationTokenSource)

ApplicationTokenOpt is a functional option for configuring an applicationTokenSource.

func WithApplicationTokenExpiration

func WithApplicationTokenExpiration(exp time.Duration) ApplicationTokenOpt

WithApplicationTokenExpiration sets the JWT expiration duration. Must be between 0 and 10 minutes per GitHub's JWT requirements. Invalid values default to 10 minutes. See https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app#about-json-web-tokens-jwts

func WithExpirySkew added in v1.6.0

func WithExpirySkew(d time.Duration) ApplicationTokenOpt

WithExpirySkew overrides the default early-refresh window (DefaultExpirySkew, 30s) applied to the token cache returned by NewApplicationTokenSource. The cached token is refreshed when time.Until(exp) <= d. A zero or negative value disables the skew and falls back to oauth2.ReuseTokenSource behavior (refresh only after exp has passed).

Tune this when your application token expiration (see WithApplicationTokenExpiration) is short: the effective validity is expiration - skew, so with the default 10-minute expiration and 30s skew tokens are refreshed at 9m30s.

type Identifier added in v1.3.0

type Identifier interface {
	~int64 | ~string
}

Identifier constrains GitHub App identifiers to int64 (App ID) or string (Client ID).

type InstallationPermissions added in v1.5.0

type InstallationPermissions struct {
	Actions                         *string `json:"actions,omitempty"`
	Administration                  *string `json:"administration,omitempty"`
	Checks                          *string `json:"checks,omitempty"`
	Contents                        *string `json:"contents,omitempty"`
	ContentReferences               *string `json:"content_references,omitempty"`
	Deployments                     *string `json:"deployments,omitempty"`
	Environments                    *string `json:"environments,omitempty"`
	Issues                          *string `json:"issues,omitempty"`
	Metadata                        *string `json:"metadata,omitempty"`
	Packages                        *string `json:"packages,omitempty"`
	Pages                           *string `json:"pages,omitempty"`
	PullRequests                    *string `json:"pull_requests,omitempty"`
	RepositoryAnnouncementBanners   *string `json:"repository_announcement_banners,omitempty"`
	RepositoryHooks                 *string `json:"repository_hooks,omitempty"`
	RepositoryProjects              *string `json:"repository_projects,omitempty"`
	SecretScanningAlerts            *string `json:"secret_scanning_alerts,omitempty"`
	Secrets                         *string `json:"secrets,omitempty"`
	SecurityEvents                  *string `json:"security_events,omitempty"`
	SingleFile                      *string `json:"single_file,omitempty"`
	Statuses                        *string `json:"statuses,omitempty"`
	VulnerabilityAlerts             *string `json:"vulnerability_alerts,omitempty"`
	Workflows                       *string `json:"workflows,omitempty"`
	Members                         *string `json:"members,omitempty"`
	OrganizationAdministration      *string `json:"organization_administration,omitempty"`
	OrganizationCustomRoles         *string `json:"organization_custom_roles,omitempty"`
	OrganizationAnnouncementBanners *string `json:"organization_announcement_banners,omitempty"`
	OrganizationHooks               *string `json:"organization_hooks,omitempty"`
	OrganizationPlan                *string `json:"organization_plan,omitempty"`
	OrganizationProjects            *string `json:"organization_projects,omitempty"`
	OrganizationPackages            *string `json:"organization_packages,omitempty"`
	OrganizationSecrets             *string `json:"organization_secrets,omitempty"`
	OrganizationSelfHostedRunners   *string `json:"organization_self_hosted_runners,omitempty"`
	OrganizationUserBlocking        *string `json:"organization_user_blocking,omitempty"`
	TeamDiscussions                 *string `json:"team_discussions,omitempty"`
}

InstallationPermissions represents the permissions granted to an installation token.

type InstallationToken added in v1.5.0

type InstallationToken struct {
	Token        string                   `json:"token"`
	ExpiresAt    time.Time                `json:"expires_at"`
	Permissions  *InstallationPermissions `json:"permissions,omitempty"`
	Repositories []Repository             `json:"repositories,omitempty"`
}

InstallationToken represents a GitHub App installation token.

type InstallationTokenOptions added in v1.5.0

type InstallationTokenOptions struct {
	// Repositories is a list of repository names that the token should have access to.
	Repositories []string `json:"repositories,omitempty"`
	// RepositoryIDs is a list of repository IDs that the token should have access to.
	RepositoryIDs []int64 `json:"repository_ids,omitempty"`
	// Permissions are the permissions granted to the access token.
	Permissions *InstallationPermissions `json:"permissions,omitempty"`
}

InstallationTokenOptions specifies options for creating an installation token.

type InstallationTokenSourceOpt

type InstallationTokenSourceOpt func(*installationTokenSource)

InstallationTokenSourceOpt is a functional option for InstallationTokenSource.

func WithContext added in v1.1.0

WithContext sets the context for the GitHub App installation token source.

func WithEnterpriseURL added in v1.5.0

func WithEnterpriseURL(baseURL string) InstallationTokenSourceOpt

WithEnterpriseURL sets the base URL for GitHub Enterprise Server. This option should be used after WithHTTPClient to ensure the HTTP client is properly configured. If the provided base URL is invalid, the option is ignored and default GitHub base URL is used.

func WithHTTPClient

func WithHTTPClient(client *http.Client) InstallationTokenSourceOpt

WithHTTPClient sets the HTTP client for the GitHub App installation token source.

func WithInstallationExpirySkew added in v1.6.0

func WithInstallationExpirySkew(d time.Duration) InstallationTokenSourceOpt

WithInstallationExpirySkew overrides the default early-refresh window (DefaultExpirySkew, 30s) applied to the installation token cache returned by NewInstallationTokenSource. Installation tokens live 1 hour, so the 30s default leaves ~59m30s effective validity — this option exists mostly for parity with WithExpirySkew. A zero or negative value falls back to oauth2.ReuseTokenSource behavior.

func WithInstallationTokenOptions

func WithInstallationTokenOptions(opts *InstallationTokenOptions) InstallationTokenSourceOpt

WithInstallationTokenOptions sets the options for the GitHub App installation token.

func WithRetryOnThrottle added in v1.6.0

func WithRetryOnThrottle(enabled bool) InstallationTokenSourceOpt

WithRetryOnThrottle enables or disables a single automatic retry when GitHub returns a throttled response (HTTP 429, or 403 with rate-limit headers) for the installation token POST. Enabled by default.

On a throttled response the client sleeps the duration hinted by Retry-After or x-ratelimit-reset (capped at 60s, honoring ctx cancellation) and retries once. Subsequent failures bubble up unchanged. On a terminal throttle the returned error wraps ErrRateLimited so callers can branch with errors.Is.

Disable this when the caller implements its own backoff or when deterministic latency matters more than transient rate-limit resilience.

type Repository added in v1.5.0

type Repository struct {
	ID   *int64  `json:"id,omitempty"`
	Name *string `json:"name,omitempty"`
}

Repository represents a GitHub repository.

Directories

Path Synopsis
Package webhook verifies GitHub webhook deliveries.
Package webhook verifies GitHub webhook deliveries.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL