github-bot-sdk
A comprehensive GitHub Bot SDK for Rust, providing authentication, webhook validation, and API client functionality for building robust GitHub Apps and integrations.
Why Use This SDK?
Building GitHub Apps requires handling complex authentication flows, webhook validation, rate limiting, and API interactions. This SDK provides:
- Type-Safe API: Leverage Rust's type system to catch errors at compile time rather than runtime
- Security by Default: Built-in HMAC signature validation, secure token handling, and constant-time comparisons
- Production-Ready: Automatic retry logic with exponential backoff, rate limit handling, and comprehensive error types
- Developer Experience: Clear abstractions, extensive documentation, and idiomatic Rust patterns
- Zero-Cost Abstractions: High-level ergonomics without runtime overhead
Comparison with Direct API Usage
| Feature | Direct API Calls | This SDK |
|---|---|---|
| Type Safety | Manual JSON parsing | Strongly-typed models |
| Authentication | Manual JWT signing | Automated token management |
| Rate Limiting | Manual tracking | Built-in detection and retry |
| Error Handling | HTTP status codes | Rich error types with context |
| Webhook Security | Manual HMAC validation | Verified by default |
| Token Expiry | Manual tracking | Automatic refresh and caching |
Features
-
🔐 GitHub App Authentication
- RS256 JWT signing for GitHub App authentication
- Automated installation token generation and caching
- Secure token handling with memory zeroing on drop
- Support for installation-scoped permissions
-
🔒 Webhook Validation
- HMAC-SHA256 signature verification
- Constant-time comparison to prevent timing attacks
- Built-in request body validation
- Support for GitHub webhook secret rotation
-
🌐 API Client
- Type-safe wrappers for GitHub REST API endpoints
- Repository, Issue, Pull Request, Project, Release, and Workflow operations
- Automatic rate limit detection and handling
- Exponential backoff retry logic for transient failures
- Comprehensive pagination support
-
📨 Event Processing
- Webhook event envelope normalization
- Type-safe event parsing and routing
- Session-based event processing patterns
- Support for all GitHub webhook event types
-
🦀 Rust-First Design
- Zero-cost abstractions with async/await
- Leverages Rust's type system for correctness
- Built on tokio runtime for high-performance async I/O
- Comprehensive error types with rich context
Installation
Add to your Cargo.toml:
[]
= "0.1.0"
Quick Start
Basic Authentication and API Usage
use ;
use Arc;
async
Webhook Validation
use SignatureValidator;
use SecretProvider;
use Arc;
async
Repository Operations
use ;
use ;
async
Issue and Pull Request Operations
use GitHubClient;
use InstallationId;
async
Ok
}
Event Processing
use ;
use async_trait;
;
Usage
Authentication
JWT Generation for GitHub Apps
The SDK handles JWT (JSON Web Token) generation automatically for app-level operations:
use ;
// JWT tokens are generated automatically by the authentication provider
// Maximum 10-minute expiration (GitHub requirement)
// Uses RS256 algorithm (RSA SHA-256)
Installation Tokens
Installation tokens provide access to specific installations with scoped permissions:
use ;
// Tokens are automatically requested and cached
// Refresh happens automatically before expiration
// Respects GitHub's rate limits during token refresh
let installation = client.installation;
// Installation token is obtained and used automatically
Token Caching
The SDK includes built-in token caching to minimize API calls:
- Installation tokens are cached until near expiration
- Automatic refresh with 60-second buffer before expiry
- Thread-safe cache for concurrent access
- Configurable cache implementation
API Operations
Repository Operations
// Get repository details
let repo = installation.get_repository.await?;
// List repositories for installation
let repos = installation.list_repositories.await?;
// Get branch information
let branch = installation.get_branch.await?;
// List all branches
let branches = installation.list_branches.await?;
// Create a branch
installation.create_branch.await?;
// Delete a branch
installation.delete_branch.await?;
Issue Operations
// List issues
let issues = installation.list_issues.await?;
// Get specific issue
let issue = installation.get_issue.await?;
// Create issue
let new_issue = installation
.create_issue
.await?;
// Update issue
installation
.update_issue
.await?;
// Close issue
installation.close_issue.await?;
// Add comment
installation
.create_issue_comment
.await?;
// Add/remove labels
installation.add_labels.await?;
installation.remove_label.await?;
Pull Request Operations
// List pull requests
let prs = installation.list_pull_requests.await?;
// Get specific PR
let pr = installation.get_pull_request.await?;
// Create pull request
let new_pr = installation
.create_pull_request
.await?;
// Update pull request
installation
.update_pull_request
.await?;
// Merge pull request
installation
.merge_pull_request
.await?;
// Request reviewers
installation
.request_reviewers
.await?;
// Add review comment
installation
.create_review_comment
.await?;
Project Operations (GitHub Projects V2)
// Get project details
let project = installation.get_project.await?;
// List project items
let items = installation.list_project_items.await?;
// Add item to project
installation.add_project_item.await?;
// Update project item field
installation
.update_project_item_field
.await?;
Release Operations
// List releases
let releases = installation.list_releases.await?;
// Get latest release
let latest = installation.get_latest_release.await?;
// Create release
let release = installation
.create_release
.await?;
// Upload release asset
installation
.upload_release_asset
.await?;
Workflow Operations
// List workflows
let workflows = installation.list_workflows.await?;
// Trigger workflow dispatch
installation
.dispatch_workflow
.await?;
// List workflow runs
let runs = installation.list_workflow_runs.await?;
Event Processing
Parsing Webhook Events
use ;
// Parse incoming webhook
let envelope = parse_webhook?;
// Access event data
println!;
println!;
println!;
// Parse specific event payload
match envelope.event_type.as_str
Session-Based Processing
use SessionManager;
// Note: Session API is provided for managing event processing state
// Create session manager
let session_manager = new;
// Track event processing
let session_id = session_manager.create_session.await;
println!;
Ok
}).await?;
Webhook Handling
HMAC Signature Validation
use ;
// Create validator
let validator = new;
// Validate webhook signature
let signature = request.headers.get?;
let is_valid = validator.validate.await?;
if !is_valid
Complete Webhook Handler
use WebhookHandler;
Rate Limiting and Retry
Automatic Rate Limit Handling
The SDK automatically detects and handles GitHub's rate limits:
// Rate limits are detected from response headers
// Primary rate limits: Automatic backoff before hitting limit
// Secondary rate limits (429/403): Exponential backoff retry
// Retry-After headers are respected
Retry Configuration
use ClientConfig;
use Duration;
let config = default
.with_max_retries // Maximum retry attempts
.with_initial_retry_delay
.with_max_retry_delay
.with_rate_limit_margin; // Keep 10% buffer
let client = builder
.config
.build?;
Pagination
use PagedResponse;
// Pagination is handled via PagedResponse type
// Extract page numbers from Link headers
// See client::pagination module for utilities
// Example:
let next_page = extract_page_number;
if let Some = next_page
Configuration
Environment Variables
The SDK can be configured using environment variables for common settings:
# GitHub App Configuration
GITHUB_APP_ID=123456
GITHUB_PRIVATE_KEY_PATH=/path/to/private-key.pem
GITHUB_WEBHOOK_SECRET=your_webhook_secret
# API Configuration
GITHUB_API_URL=https://api.github.com # Default, override for GitHub Enterprise
GITHUB_USER_AGENT=my-bot/1.0
# Timeouts and Retries
GITHUB_REQUEST_TIMEOUT_SECS=30
GITHUB_MAX_RETRIES=3
Client Configuration Options
Customize client behavior through ClientConfig:
use ClientConfig;
use Duration;
let config = builder
.user_agent // Required by GitHub API
.timeout // Request timeout
.max_retries // Maximum retry attempts
.initial_retry_delay // Base delay for retries
.max_retry_delay // Maximum backoff delay
.rate_limit_margin // Keep 10% rate limit buffer
.github_api_url // API base URL
.build;
GitHub App Setup Requirements
To use this SDK, you need a GitHub App with appropriate permissions:
-
Create a GitHub App:
- Go to Settings → Developer settings → GitHub Apps
- Click "New GitHub App"
- Configure webhook URL and permissions
-
Required Permissions:
- Repository permissions (based on your use case):
- Contents: Read & Write (for file operations)
- Issues: Read & Write (for issue operations)
- Pull requests: Read & Write (for PR operations)
- Workflows: Read & Write (for workflow operations)
- Organization permissions (if needed):
- Members: Read (for team operations)
- Repository permissions (based on your use case):
-
Generate Private Key:
- In your app settings, scroll to "Private keys"
- Click "Generate a private key"
- Download and securely store the
.pemfile
-
Install the App:
- Install the app on your organization or repositories
- Note the installation ID from the installation URL
-
Webhook Configuration (if using webhooks):
- Set webhook URL to your server endpoint
- Generate and securely store webhook secret
- Select event subscriptions you need
Security Best Practices
- Never commit private keys or secrets to version control
- Store secrets in environment variables or secret management systems (Azure Key Vault, AWS Secrets Manager)
- Use separate keys for development and production
- Rotate webhook secrets periodically
- Implement proper webhook signature validation
- Use HTTPS for all webhook endpoints
- Monitor failed authentication attempts
Testing
Running Tests
Run the complete test suite:
# Run all tests
# Run tests with output
# Run specific test module
# Run doc tests
Test Coverage
Generate and view test coverage:
# Install cargo-llvm-cov
# Generate coverage report
# Open coverage report
Mocking GitHub API with WireMock
The SDK uses wiremock for testing GitHub API interactions:
use ;
use ;
async
Integration Testing
For integration tests with real GitHub API:
// tests/integration_test.rs
use GitHubClient;
// Run with: cargo test -- --ignored
async
Test Organization
Tests are colocated with source files using the _tests.rs pattern:
src/
├── auth/
│ ├── mod.rs # Implementation
│ ├── mod_tests.rs # Tests for mod.rs
│ ├── tokens.rs # Implementation
│ └── tokens_tests.rs # Tests for tokens.rs
Continuous Integration
Tests run automatically on every push via GitHub Actions:
- Unit tests with full coverage
- Doc tests
- Lint checks (rustfmt, clippy)
- Dependency security audits
See .github/workflows/ci.yml for the complete CI configuration.
Documentation
Examples
The SDK provides comprehensive examples demonstrating common use cases:
Available Examples
Examples will be added in the examples/ directory. Planned examples include:
- Basic Bot - Simple webhook listener with event processing
- Issue Labeler - Automatically label issues based on content
- PR Review Bot - Automated PR review comments and checks
- Release Manager - Automated release creation and notes
- Repository Manager - Bulk repository configuration and maintenance
- Webhook Server - Complete webhook receiver with signature validation
- Multi-Installation Bot - Handle events across multiple installations
Running Examples
Once examples are added, run them with:
# Set required environment variables
# Run an example
Example Structure
Each example demonstrates:
- Complete authentication setup
- Proper error handling
- Production-ready patterns
- Security best practices
- Logging and observability
See the examples/ directory for complete working code with detailed comments.
Contributing
We welcome contributions! Please see CONTRIBUTING.md for detailed guidelines.
Quick Start for Contributors
# Fork and clone the repository
# Create a feature branch
# Make your changes, add tests, update docs
# Run tests and linters
# Commit with conventional commit format
# Push and create pull request
Contribution Guidelines
- Follow the Code of Conduct: Be respectful and inclusive
- Write Tests: All new features must have comprehensive tests
- Document Changes: Update rustdoc comments and specifications
- Follow Conventions: Use conventional commits for automated versioning
- Check CI: Ensure all CI checks pass before requesting review
- Sign Commits: Use signed commits (optional but recommended)
Areas for Contribution
- Features: Implement additional GitHub API endpoints
- Documentation: Improve examples, guides, and API docs
- Testing: Add more test coverage or integration tests
- Performance: Optimize hot paths or reduce allocations
- Bug Fixes: Report and fix issues
- Examples: Create new example bots demonstrating use cases
Changelog and Versioning
Semantic Versioning
This project follows Semantic Versioning:
- MAJOR version for incompatible API changes
- MINOR version for backwards-compatible functionality additions
- PATCH version for backwards-compatible bug fixes
Changelog
See CHANGELOG.md for a detailed history of changes in each release.
Changelog is automatically generated from conventional commits using git-cliff.
Release Process
Releases are automated using release-plz:
- Commits are analyzed for semantic versioning impact
- CHANGELOG.md is automatically updated
- Version is bumped in Cargo.toml
- GitHub release is created with notes
- Crate is published to crates.io
Versioning Policy
- Stable releases (1.0+): Breaking changes require major version bump
- Pre-1.0 releases (0.x): Minor versions may include breaking changes
- Release Candidates: Tagged as
vX.Y.Z-rc.Nfor testing before stable release
License
Licensed under the Apache License, Version 2.0. See LICENSE for details.
Copyright 2024-2026 Patrick van der Velde
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Acknowledgments
This SDK builds upon the excellent work of the Rust community and several key dependencies:
- reqwest - HTTP client for GitHub API communication
- tokio - Async runtime powering all I/O operations
- jsonwebtoken - JWT signing for GitHub App authentication
- serde - Serialization framework for API types
- wiremock - HTTP mocking for comprehensive testing