git

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2025 License: MPL-2.0 Imports: 21 Imported by: 0

README

argus-provider-git: Argus remote provider for Git repositories

an AGILira library

Official Argus provider for remote configuration management through Git repositories. Enables real-time configuration loading and watching from GitHub, GitLab, Bitbucket, and self-hosted Git servers with production-ready security and performance features.

CI CodeQL Security Go Report Card Made For Argus

FeaturesInstallationQuick StartConfigurationAuthenticationSecurityPerformance

Features

GitOps Integration

  • Multi-platform Git provider support (GitHub, GitLab, Bitbucket, self-hosted)
  • Efficient polling using git ls-remote without full repository clones
  • Multiple authentication methods: tokens, SSH keys, basic auth
  • Branch, tag, and commit-specific configuration loading

Secure by Design

  • Red-team tested against path traversal and SSRF attacks
  • URL validation and sanitization
  • SSH key permission validation
  • Resource limits for DoS protection
  • Fuzz tested for path traversal protection

High Performance

  • Intelligent multi-layer caching (authentication, repository metadata, configurations)
  • Retry logic with exponential backoff
  • Shallow clones for minimal bandwidth usage
  • Concurrent operation limits with resource management

Compatibility

Requires Go 1.25+ and go-git v5+.

Security Note: Go 1.25+ is required to avoid supply chain vulnerabilities detected by govulncheck in earlier versions.

Installation

go get github.com/agilira/argus-provider-git

Quick Start

import (
    "github.com/agilira/argus"
    git "github.com/agilira/argus-provider-git"
)

// Register the Git provider with Argus
provider := git.GetProvider()
err := argus.RegisterRemoteProvider(provider)
if err != nil {
    log.Fatal("Failed to register Git provider:", err)
}

// Load configuration from Git repository
config, err := argus.LoadRemoteConfig("https://github.com/myorg/configs.git#config.json?ref=main")
if err != nil {
    log.Fatal("Failed to load config:", err)
}
Direct Provider Usage

For advanced use cases, you can use the provider directly:

package main

import (
    "context"
    "log"

    git "github.com/agilira/argus-provider-git"
)

func main() {
    provider := git.GetProvider()
    ctx := context.Background()
    
    // Load configuration once
    configURL := "https://github.com/myorg/configs.git#config.json?ref=production"
    config, err := provider.Load(ctx, configURL)
    if err != nil {
        log.Fatalf("Failed to load config: %v", err)
    }
    
    log.Printf("Configuration: %+v", config)
    
    // Watch for configuration changes  
    configURL = "https://github.com/myorg/configs.git#config.json?ref=main&poll=30s"
    configChan, err := provider.Watch(ctx, configURL)
    if err != nil {
        log.Fatalf("Failed to start watch: %v", err)
    }
    
    for config := range configChan {
        log.Printf("Configuration updated: %+v", config)
        // Apply configuration to your application
    }
}

Configuration

URL Format

Configuration URLs follow the Git repository format with additional parameters:

<scheme>://<host>/<path>#<file>?<parameters>

Supported Schemes:

  • https:// - HTTPS (recommended)
  • ssh:// - SSH
  • git:// - Git protocol

Examples:

https://github.com/user/repo.git#config.json?ref=main
https://github.com/user/private-repo.git#config.yaml?auth=token:ghp_xxxxx
ssh://git@gitlab.com/user/repo.git#configs/prod.toml?auth=key:/path/to/key
URL Parameters

File Selection:

  • #<file> - Path to configuration file in repository
  • ref=<branch|tag|commit> - Git reference (default: "main")

Polling Configuration:

  • poll=<duration> - Watch polling interval (e.g., "30s", "5m", "1h")

Authentication:

  • auth=token:<token> - Access token (GitHub/GitLab)
  • auth=basic:<USERNAME>:<PASSWORD> - HTTP Basic Authentication
  • auth=key:<path> - SSH private key path
  • auth=ssh:<path>:<passphrase> - SSH key with passphrase
Supported Configuration Formats

The provider supports multiple configuration file formats:

JSON:

{
  "database": {
    "host": "localhost",
    "port": 5432
  },
  "features": {
    "caching": true
  }
}

YAML:

database:
  host: localhost
  port: 5432
features:
  caching: true

TOML:

[database]
host = "localhost"
port = 5432

[features]
caching = true

Additional formats: HCL, INI, and Properties files are also supported.

Authentication

Token Authentication: ?auth=token:YOUR_TOKEN (GitHub, GitLab, Bitbucket)
SSH Keys: ?auth=key:/path/to/key (requires 0600 permissions)
Basic Auth: ?auth=basic:username:password (self-hosted Git)

# Examples
https://github.com/user/repo.git#config.json?auth=token:ghp_xxxxx
ssh://git@gitlab.com/user/repo.git#config.yaml?auth=key:/home/user/.ssh/id_rsa
HTTP Basic Authentication

For Git servers supporting basic authentication:

https://git.company.com/repo.git#config.json?auth=basic:YOUR_USERNAME:YOUR_PASSWORD

Security

Security Features

Path Traversal Protection - Prevents access outside repository boundaries with 50+ attack vector tests
SSRF Protection - Blocks localhost, private networks, and cloud metadata access
SSH Security - Validates key permissions and secure credential caching
Automated Security - CodeQL analysis, gosec, and govulncheck

Resource Limits

The provider enforces the following limits for security and performance:

const (
    maxConfigFileSize       = 5 * 1024 * 1024  // 5MB maximum file size
    maxConcurrentOperations = 10               // Maximum parallel operations  
    maxActiveWatches       = 5                 // Maximum active watch operations
    defaultGitTimeout      = 60 * time.Second  // Git operation timeout
    minPollInterval        = 5 * time.Second   // Minimum polling interval
    maxPollInterval        = 10 * time.Minute  // Maximum polling interval
)

Performance

Multi-layer Caching - Authentication, metadata, and configuration caching with intelligent eviction
Efficient Operations - git ls-remote for change detection, shallow clones, exponential backoff
Resource Management - Connection pooling, concurrent limits, memory-efficient file handling

Advanced Configuration

Environment Variables: Use GITHUB_TOKEN, GITLAB_TOKEN, SSH_KEY_PATH for secure credential management
Multi-Environment: Support for dev/staging/prod configurations with different repositories and branches


## Troubleshooting

### Common Issues

**Authentication Failures**
- Verify token has correct permissions (repo scope for private repositories)
- Ensure SSH keys are registered in your Git platform account  
- Test authentication: `git ls-remote <repo-url>`

**File Not Found**
- Verify file exists in specified repository and branch
- Check file path case sensitivity
- Ensure branch/tag exists

**Configuration Parse Errors**  
- Validate configuration file format
- Check file encoding (must be UTF-8)
- Use online validators for JSON/YAML/TOML

**Network Timeouts**
- Verify network connectivity to Git server
- Consider using tokens for better rate limits
- Increase polling intervals for watch operations

## License

Mozilla Public License 2.0 - see the [LICENSE](LICENSE.md) file for details.

---

argus-provider-redis • an AGILira library

Documentation

Overview

Package git provides a high-performance Git remote configuration provider for Argus.

Overview

This package implements the Argus RemoteConfigProvider interface to enable real-time configuration loading and monitoring from Git repositories (GitHub, GitLab, Bitbucket, self-hosted). The provider leverages Git's native capabilities for efficient configuration management with comprehensive security validation and GitOps best practices.

The implementation follows high-performance design principles with connection pooling, shallow clones, efficient polling mechanisms, and minimal memory allocations during runtime operations. It's designed for production environments where security and reliability matter.

Key Features

  • GitOps Configuration Management: Load configs from Git repositories with full versioning
  • Multi-Platform Support: GitHub, GitLab, Bitbucket, and self-hosted Git servers
  • Multiple Authentication Methods: Personal tokens, SSH keys, basic auth
  • Real-time Polling: Efficient repository monitoring for configuration changes
  • Branch/Tag/Commit Support: Flexible reference targeting (main, v1.2.3, commit SHA)
  • Format Detection: JSON, YAML, TOML configuration file support
  • Security Hardened: Red-team tested against SSRF, path traversal, and injection attacks
  • Performance Optimized: Shallow clones, connection reuse, and caching mechanisms
  • Thread-Safe Operations: Concurrent access with proper synchronization
  • Graceful Shutdown: Clean resource management and connection cleanup

URL Format and Configuration

The provider accepts Git URLs in the following format:

git://host.com/user/repo.git#config/file.json[?query_params]

Where query_params can include:

  • ref=main: Specify Git reference (branch, tag, or commit SHA)
  • token=ghp_xxxx: GitHub/GitLab personal access token
  • ssh_key=/path/to/key: Path to SSH private key for authentication
  • poll=30s: Custom polling interval for watch operations

The URL fragment (#) specifies the configuration file path within the repository.

Examples

Basic configuration loading from GitHub:

import (
    "context"
    "log"

    "github.com/agilira/argus"
    git "github.com/agilira/argus-provider-git"
)

func main() {
    // Register the Git provider with Argus
    provider, err := git.GetProvider()
    if err != nil {
        log.Fatal("Failed to create Git provider:", err)
    }

    if err := argus.RegisterRemoteProvider("git", provider); err != nil {
        log.Fatal("Failed to register provider:", err)
    }

    // Load configuration from GitHub repository
    configURL := "git://github.com/company/configs.git#production/app.json?ref=main"
    config, err := argus.LoadRemoteConfig(configURL)
    if err != nil {
        log.Fatal("Configuration loading failed:", err)
    }

    log.Printf("Configuration loaded: %+v", config)
}

Real-time configuration monitoring with Git polling:

func watchConfiguration() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
    defer cancel()

    // Start watching for Git repository changes
    configURL := "git://github.com/company/configs.git#production/app.json?" +
        "ref=main&poll=30s&token=ghp_your_token_here"

    configChan, err := argus.WatchRemoteConfigWithContext(ctx, configURL)
    if err != nil {
        log.Fatal("Watch startup failed:", err)
    }

    // Handle real-time configuration updates
    go func() {
        for newConfig := range configChan {
            log.Printf("Git configuration updated: %+v", newConfig)
            // Apply new configuration to your application
        }
    }()

    <-ctx.Done()
}

SSH authentication with private keys:

sshURL := "git://git.company.com/devops/configs.git#staging/database.yml?" +
    "ref=v2.1.0&ssh_key=/home/user/.ssh/deploy_key"

config, err := argus.LoadRemoteConfig(sshURL)
if err != nil {
    log.Fatal("SSH authentication failed:", err)
}

GitLab with personal access token:

gitlabURL := "git://gitlab.example.com/infrastructure/configs.git#k8s/app.toml?" +
    "ref=production&token=glpat_your_gitlab_token"

config, err := argus.LoadRemoteConfig(gitlabURL)
if err != nil {
    log.Fatal("GitLab configuration loading failed:", err)
}

Configuration File Formats

The provider supports multiple configuration formats with automatic detection:

JSON configuration:

{
  "service_name": "my-service",
  "port": 8080,
  "database": {
    "host": "db.example.com",
    "port": 5432,
    "ssl": true
  },
  "features": {
    "enable_metrics": true,
    "enable_tracing": false
  }
}

YAML configuration:

service_name: my-service
port: 8080
database:
  host: db.example.com
  port: 5432
  ssl: true
features:
  enable_metrics: true
  enable_tracing: false

TOML configuration:

service_name = "my-service"
port = 8080

[database]
host = "db.example.com"
port = 5432
ssl = true

[features]
enable_metrics = true
enable_tracing = false

Security Features

The provider implements comprehensive security validation to protect against:

  • SSRF (Server-Side Request Forgery): Blocks localhost, private networks, metadata servers
  • Path Traversal Attacks: Validates file paths and prevents directory traversal
  • Git URL Injection: Strict URL parsing and validation
  • SSH Key Security: Validates SSH key file permissions (0600 or stricter)
  • Repository Size Limits: Prevents DoS through large repository cloning
  • Authentication Token Security: Secure handling of credentials and tokens

Security best practices implemented:

  • Input validation with URL decoding to prevent encoding bypasses
  • Whitelist-based host validation (blocks 127.0.0.1, 10.x.x.x, 192.168.x.x, etc.)
  • File path sanitization to prevent access to sensitive files
  • Timeout controls to prevent resource exhaustion
  • Memory usage limits for large files

Performance Characteristics

The provider is optimized for high-performance production environments:

  • Shallow Clones: Only fetches necessary commits for minimal network transfer
  • Connection Reuse: HTTP/SSH connection pooling for reduced overhead
  • Efficient Polling: Smart polling with exponential backoff for watch operations
  • Memory Management: Careful resource cleanup prevents memory leaks
  • Concurrent Safety: Thread-safe operations using proper synchronization
  • Caching Strategy: Authentication object caching and repository metadata caching

Benchmarks show minimal overhead for configuration loading and efficient polling, making it suitable for latency-sensitive and high-throughput applications.

Authentication Methods

The provider supports multiple authentication methods for different Git platforms:

GitHub Personal Access Token:

git://github.com/user/repo.git#config.json?token=ghp_xxxxxxxxxxxx

GitLab Personal Access Token:

git://gitlab.com/user/repo.git#config.json?token=glpat_xxxxxxxxxxxx

SSH Key Authentication:

git://github.com/user/repo.git#config.json?ssh_key=/path/to/private/key

HTTP Basic Authentication:

git://username:password@git.example.com/user/repo.git#config.json

GitOps Integration

The provider enables full GitOps workflows by treating Git repositories as the single source of truth for configuration:

  • Version Control: All configuration changes are tracked in Git history
  • Branch-based Environments: Use branches for dev/staging/production configs
  • Tag-based Releases: Pin configurations to specific Git tags
  • Pull Request Workflow: Review configuration changes through Git workflows
  • Rollback Support: Easy rollback to previous configurations using Git references
  • Audit Trail: Complete audit trail through Git commit history

Error Handling and Resilience

The provider implements comprehensive error handling with structured error types:

  • ARGUS_INVALID_CONFIG: Malformed Git URLs or invalid parameters
  • ARGUS_CONFIG_NOT_FOUND: Configuration file not found in repository
  • ARGUS_IO_ERROR: File reading or Git operation errors
  • ARGUS_AUTH_ERROR: Authentication failures (SSH keys, tokens, credentials)
  • ARGUS_SECURITY_ERROR: Security validation failures (SSRF, path traversal)
  • ARGUS_RETRY_EXHAUSTED: All retry attempts failed for Git operations

Watch operations include intelligent retry mechanisms with exponential backoff and jitter, ensuring resilient behavior in unstable network conditions.

Testing Support

The provider includes comprehensive testing capabilities:

  • Unit tests with 100% coverage of security validations
  • Integration tests using real Git repositories
  • Fuzz testing for security vulnerability discovery
  • SSH authentication testing with permission validation
  • Performance benchmarks and memory usage tests
  • Concurrent operation testing for race condition detection

Example testing setup:

func TestGitConfiguration(t *testing.T) {
    provider := &GitProvider{}

    // Test with real repository
    configURL := "git://github.com/agilira/test-configs.git#test.json?ref=main"
    config, err := provider.Load(context.Background(), configURL)

    assert.NoError(t, err)
    assert.NotNil(t, config)
}

Fuzz Testing and Security Validation

The provider includes professional fuzz testing capabilities to discover security vulnerabilities and edge cases:

  • URL Validation Fuzzing: Tests Git URL parsing against malicious inputs
  • Host Validation Fuzzing: Tests SSRF protection against bypass attempts
  • Path Traversal Fuzzing: Tests file path validation against directory traversal
  • Authentication Fuzzing: Tests credential handling and SSH key validation
  • Parser Fuzzing: Tests configuration file parsing against malformed content

Fuzz tests can be executed with:

make fuzz  # Runs comprehensive fuzz test suite

Architecture and Design Patterns

The implementation follows Go best practices and design patterns:

  • Interface Implementation: Clean implementation of Argus RemoteConfigProvider
  • Dependency Injection: No circular dependencies with Argus core
  • Factory Pattern: GetProvider() function for clean instantiation
  • Resource Management: Proper cleanup and lifecycle management
  • Error Wrapping: Structured error handling with context preservation
  • Thread Safety: Proper synchronization for concurrent operations
  • Configuration Caching: Multi-layer caching for performance optimization

The provider is designed as a standalone library that integrates seamlessly with Argus while maintaining independence for testing and development.

Compatibility and Support

System Requirements:

  • Go 1.25+ (utilizes latest performance and security features)
  • Git 2.25+ (requires modern Git features for efficient operations)
  • Linux/macOS/Windows (full cross-platform compatibility)
  • Network access to Git repositories (GitHub, GitLab, self-hosted)

Git Platform Support:

  • GitHub.com and GitHub Enterprise
  • GitLab.com and self-hosted GitLab
  • Bitbucket Cloud and Server
  • Self-hosted Git servers (Gitea, Forgejo, etc.)
  • Any Git-compatible repository hosting

Production Deployment Considerations

For production deployments, consider:

  • Authentication Security: Use personal access tokens or SSH keys, never passwords
  • Network Security: Ensure Git repositories are accessible from application environment
  • Rate Limiting: Be aware of Git provider rate limits for API calls
  • Caching Strategy: Configure appropriate polling intervals to balance freshness and performance
  • Error Monitoring: Implement monitoring for Git authentication and network errors
  • Repository Access: Use read-only deploy keys or tokens with minimal required permissions
  • Backup Strategy: Ensure Git repositories have proper backup and disaster recovery
  • Security Hardening: Regularly rotate access tokens and SSH keys

License and Contribution

This package is licensed under the Mozilla Public License 2.0 (MPL-2.0). For contribution guidelines, bug reports, and feature requests, visit: https://github.com/agilira/argus-provider-git

Copyright (c) 2025 AGILira - A. Giordano Series: AGILira System Libraries SPDX-License-Identifier: MPL-2.0

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type GitProvider

type GitProvider struct {
	// contains filtered or unexported fields
}

GitProvider implements RemoteConfigProvider for Git repositories

This provider supports: - Loading JSON/YAML/TOML configurations from Git repositories - Public and private repositories (GitHub, GitLab, self-hosted) - Multiple authentication methods (HTTP basic auth, tokens, SSH keys) - Polling-based watching for configuration updates - Branch, tag, and commit-specific configuration loading - Secure validation against malicious repositories and paths

URL Format Examples:

git://github.com/user/repo.git/config/app.json?ref=main&auth=token:ghp_xxx
https://gitlab.com/user/repo.git/configs/prod.yaml?ref=v1.0.0&auth=basic:MYUSER:MYPASS
ssh://git@bitbucket.org/user/repo.git/config.json?ref=develop&key=/path/to/key
git+ssh://custom-git.example.com/repo.git/app.toml?ref=feature-branch

func (*GitProvider) Close

func (g *GitProvider) Close() error

Close cleanly shuts down the provider and releases resources

func (*GitProvider) GetMetrics

func (g *GitProvider) GetMetrics() map[string]interface{}

GetMetrics returns current metrics as a map for monitoring systems

func (*GitProvider) HealthCheck

func (g *GitProvider) HealthCheck(ctx context.Context, configURL string) error

HealthCheck performs a health check on the Git repository

func (*GitProvider) Load

func (g *GitProvider) Load(ctx context.Context, configURL string) (map[string]interface{}, error)

Load loads configuration from a Git repository

func (*GitProvider) Name

func (g *GitProvider) Name() string

Name returns the human-readable name of this provider

func (*GitProvider) Scheme

func (g *GitProvider) Scheme() string

Scheme returns the URL scheme this provider handles

func (*GitProvider) Validate

func (g *GitProvider) Validate(configURL string) error

Validate validates that the provider can handle the given URL

func (*GitProvider) Watch

func (g *GitProvider) Watch(ctx context.Context, configURL string) (<-chan map[string]interface{}, error)

Watch starts watching for configuration changes in a Git repository

type GitURL

type GitURL struct {
	RepoURL      string            // Base repository URL
	FilePath     string            // Path to configuration file within repo
	Reference    string            // Git reference (branch, tag, commit)
	AuthType     string            // Authentication type (token, basic, key)
	AuthData     map[string]string // Authentication data
	PollInterval time.Duration     // Custom polling interval for watch
}

GitURL represents a parsed Git configuration URL

type RemoteConfigProvider

type RemoteConfigProvider interface {
	// Name returns a human-readable name for this provider (used for debugging and logging)
	Name() string

	// Scheme returns the URL scheme this provider handles (e.g., "git")
	Scheme() string

	// Load loads configuration from the remote source
	// The URL contains the full connection information including credentials
	// Returns parsed configuration as map[string]interface{}
	Load(ctx context.Context, configURL string) (map[string]interface{}, error)

	// Watch starts watching for configuration changes
	// Returns a channel that sends new configurations when they change
	// Uses polling mechanism for detecting repository updates
	Watch(ctx context.Context, configURL string) (<-chan map[string]interface{}, error)

	// Validate validates that the provider can handle the given URL
	// Performs comprehensive URL parsing and validation without connecting
	Validate(configURL string) error

	// HealthCheck performs a health check on the remote source
	// Verifies Git repository accessibility and authentication
	HealthCheck(ctx context.Context, configURL string) error
}

RemoteConfigProvider defines the interface for remote configuration sources. This interface is copied here to avoid importing argus (which would create a circular dependency). The provider is completely standalone and implements this interface. When imported, Argus will call the registration function.

func GetProvider

func GetProvider() RemoteConfigProvider

GetProvider returns a new instance of the Git provider

This function is called by Argus during the provider registration process. It returns a fresh instance of the provider that Argus will register and use for handling git:// URLs.

Jump to

Keyboard shortcuts

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