|
| 1 | +package internal |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rsa" |
| 6 | + "crypto/x509" |
| 7 | + "encoding/pem" |
| 8 | + "fmt" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/golang-jwt/jwt/v5" |
| 14 | + |
| 15 | + sdk "github.com/GoCodeAlone/workflow/plugin/external/sdk" |
| 16 | +) |
| 17 | + |
| 18 | +// githubAppModule implements sdk.ModuleInstance. |
| 19 | +// It manages GitHub App authentication, generating installation access tokens |
| 20 | +// from an App's private key and installation ID. |
| 21 | +// |
| 22 | +// Module config: |
| 23 | +// |
| 24 | +// app_id: 12345 |
| 25 | +// installation_id: 67890 |
| 26 | +// private_key: "${GITHUB_APP_PRIVATE_KEY}" # PEM-encoded RSA key |
| 27 | +type githubAppModule struct { |
| 28 | + name string |
| 29 | + config githubAppConfig |
| 30 | + |
| 31 | + // cached token and expiry for reuse within the valid window |
| 32 | + cachedToken string |
| 33 | + tokenExpiry time.Time |
| 34 | +} |
| 35 | + |
| 36 | +type githubAppConfig struct { |
| 37 | + AppID int64 `yaml:"app_id"` |
| 38 | + InstallationID int64 `yaml:"installation_id"` |
| 39 | + PrivateKey string `yaml:"private_key"` |
| 40 | +} |
| 41 | + |
| 42 | +// newGitHubAppModule parses the config map and returns a githubAppModule. |
| 43 | +func newGitHubAppModule(name string, config map[string]any) (*githubAppModule, error) { |
| 44 | + var cfg githubAppConfig |
| 45 | + |
| 46 | + switch v := config["app_id"].(type) { |
| 47 | + case int: |
| 48 | + cfg.AppID = int64(v) |
| 49 | + case int64: |
| 50 | + cfg.AppID = v |
| 51 | + case float64: |
| 52 | + cfg.AppID = int64(v) |
| 53 | + } |
| 54 | + if cfg.AppID == 0 { |
| 55 | + return nil, fmt.Errorf("github.app %q: config.app_id is required", name) |
| 56 | + } |
| 57 | + |
| 58 | + switch v := config["installation_id"].(type) { |
| 59 | + case int: |
| 60 | + cfg.InstallationID = int64(v) |
| 61 | + case int64: |
| 62 | + cfg.InstallationID = v |
| 63 | + case float64: |
| 64 | + cfg.InstallationID = int64(v) |
| 65 | + } |
| 66 | + if cfg.InstallationID == 0 { |
| 67 | + return nil, fmt.Errorf("github.app %q: config.installation_id is required", name) |
| 68 | + } |
| 69 | + |
| 70 | + cfg.PrivateKey, _ = config["private_key"].(string) |
| 71 | + cfg.PrivateKey = os.ExpandEnv(cfg.PrivateKey) |
| 72 | + if cfg.PrivateKey == "" { |
| 73 | + return nil, fmt.Errorf("github.app %q: config.private_key is required", name) |
| 74 | + } |
| 75 | + |
| 76 | + return &githubAppModule{name: name, config: cfg}, nil |
| 77 | +} |
| 78 | + |
| 79 | +// Init is a no-op; the module is ready after construction. |
| 80 | +func (m *githubAppModule) Init() error { return nil } |
| 81 | + |
| 82 | +// Start is a no-op. |
| 83 | +func (m *githubAppModule) Start(_ context.Context) error { return nil } |
| 84 | + |
| 85 | +// Stop is a no-op. |
| 86 | +func (m *githubAppModule) Stop(_ context.Context) error { return nil } |
| 87 | + |
| 88 | +// Name returns the module name. |
| 89 | +func (m *githubAppModule) Name() string { return m.name } |
| 90 | + |
| 91 | +// GetInstallationToken returns a valid GitHub App installation access token, |
| 92 | +// using a cached value if it is still valid (expires in >5 minutes). |
| 93 | +func (m *githubAppModule) GetInstallationToken(ctx context.Context) (string, error) { |
| 94 | + if m.cachedToken != "" && time.Until(m.tokenExpiry) > 5*time.Minute { |
| 95 | + return m.cachedToken, nil |
| 96 | + } |
| 97 | + |
| 98 | + jwtToken, err := m.generateJWT() |
| 99 | + if err != nil { |
| 100 | + return "", fmt.Errorf("generate app JWT: %w", err) |
| 101 | + } |
| 102 | + |
| 103 | + client := NewSDKClient(jwtToken) |
| 104 | + token, _, err := client.GH.Apps.CreateInstallationToken(ctx, m.config.InstallationID, nil) |
| 105 | + if err != nil { |
| 106 | + return "", fmt.Errorf("create installation token: %w", err) |
| 107 | + } |
| 108 | + |
| 109 | + m.cachedToken = token.GetToken() |
| 110 | + m.tokenExpiry = token.GetExpiresAt().Time |
| 111 | + return m.cachedToken, nil |
| 112 | +} |
| 113 | + |
| 114 | +// generateJWT creates a short-lived JWT for GitHub App authentication. |
| 115 | +func (m *githubAppModule) generateJWT() (string, error) { |
| 116 | + key, err := parseRSAPrivateKey(m.config.PrivateKey) |
| 117 | + if err != nil { |
| 118 | + return "", err |
| 119 | + } |
| 120 | + |
| 121 | + now := time.Now() |
| 122 | + claims := jwt.MapClaims{ |
| 123 | + "iat": now.Add(-60 * time.Second).Unix(), // issued 60s ago to handle clock skew |
| 124 | + "exp": now.Add(10 * time.Minute).Unix(), |
| 125 | + "iss": m.config.AppID, |
| 126 | + } |
| 127 | + |
| 128 | + token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) |
| 129 | + return token.SignedString(key) |
| 130 | +} |
| 131 | + |
| 132 | +// parseRSAPrivateKey decodes a PEM-encoded RSA private key. |
| 133 | +func parseRSAPrivateKey(pem_encoded string) (*rsa.PrivateKey, error) { |
| 134 | + block, _ := pem.Decode([]byte(pem_encoded)) |
| 135 | + if block == nil { |
| 136 | + return nil, fmt.Errorf("failed to decode PEM block for RSA private key") |
| 137 | + } |
| 138 | + key, err := x509.ParsePKCS1PrivateKey(block.Bytes) |
| 139 | + if err != nil { |
| 140 | + // Try PKCS8 format as well. |
| 141 | + iface, err2 := x509.ParsePKCS8PrivateKey(block.Bytes) |
| 142 | + if err2 != nil { |
| 143 | + return nil, fmt.Errorf("parse RSA private key (PKCS1: %v, PKCS8: %v)", err, err2) |
| 144 | + } |
| 145 | + rsakey, ok := iface.(*rsa.PrivateKey) |
| 146 | + if !ok { |
| 147 | + return nil, fmt.Errorf("private key is not RSA") |
| 148 | + } |
| 149 | + return rsakey, nil |
| 150 | + } |
| 151 | + return key, nil |
| 152 | +} |
| 153 | + |
| 154 | +// AppTransport implements http.RoundTripper for GitHub App authentication, |
| 155 | +// automatically refreshing the installation token as needed. |
| 156 | +type AppTransport struct { |
| 157 | + module *githubAppModule |
| 158 | + base http.RoundTripper |
| 159 | +} |
| 160 | + |
| 161 | +// NewAppTransport creates an http.RoundTripper that uses App installation tokens. |
| 162 | +func NewAppTransport(mod *githubAppModule) *AppTransport { |
| 163 | + return &AppTransport{module: mod, base: http.DefaultTransport} |
| 164 | +} |
| 165 | + |
| 166 | +// RoundTrip injects the installation token into each request. |
| 167 | +func (t *AppTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| 168 | + token, err := t.module.GetInstallationToken(req.Context()) |
| 169 | + if err != nil { |
| 170 | + return nil, fmt.Errorf("get installation token: %w", err) |
| 171 | + } |
| 172 | + reqCopy := req.Clone(req.Context()) |
| 173 | + reqCopy.Header.Set("Authorization", "Bearer "+token) |
| 174 | + return t.base.RoundTrip(reqCopy) |
| 175 | +} |
| 176 | + |
| 177 | +// GetSDKClient returns an SDK client authenticated with this App's installation token. |
| 178 | +func (m *githubAppModule) GetSDKClient() *SDKClient { |
| 179 | + return NewSDKClientFromTransport(NewAppTransport(m)) |
| 180 | +} |
| 181 | + |
| 182 | +// Ensure githubAppModule satisfies sdk.ModuleInstance at compile time. |
| 183 | +var _ sdk.ModuleInstance = (*githubAppModule)(nil) |
0 commit comments