diff --git a/collector.example.yaml b/collector.example.yaml index b434929..717b223 100644 --- a/collector.example.yaml +++ b/collector.example.yaml @@ -1,50 +1,62 @@ -# Configuration for AI Engineering Metrics pipeline -# This file follows the current schema where everything is organized into pipelines +# AI Engineering Metrics Collector Configuration Example +# This example shows how to collect Claude usage metrics and AI readiness metrics pipelines: - - # Pipeline 1: Main AI metrics collection pipeline + # Pipeline 1: Claude Usage Metrics with User Filtering + - users: + type: getdx + config: + api_key: ${env.GETDX_WEB_API_KEY} collectors: - - name: bedrock-s3 # of the tool as it appears in GetDX + - name: claude type: bedrock enabled: true config: bucket: my-bedrock-logs-bucket - prefix: bedrock-logs/ - # local_path: /tmp/bedrock-logs # Optional: local directory for temporary file storage + prefix: AWSLogs/123456789012/BedrockModelInvocationLogs/us-east-1/ + costs: + region: us-east-1 + discount: 0% + user_mapping: + type: regex + config: + regex: "arn:aws:sts::123456789012:assumed-role/MyRole/(.*@company.com)" + replacement: "$1" + publishers: + - type: getdx + config: + api_base_url: https://api.getdx.com + api_token: ${env.GETDX_API_KEY} + tools: + - claude + + # Pipeline 2: AI Readiness Metrics (no user filtering needed) + - collectors: + - name: github-ai-readiness + type: github + enabled: true + config: + app_id: ${env.GITHUB_APP_ID} + private_key: ${env.GITHUB_PRIVATE_KEY} + scan_all_organizations: true + organization_filter: + - "my-org" user_mapping: type: passthrough config: {} - # Alternative user mapping options: - # type: static - # config: - # session-123: user@example.com - # session-456: another@example.com - # type: regex - # config: - # regex: 'session-(.+)' - # replacement: 'user-$1@example.com' - publishers: - - name: getdx - type: getdx - enabled: true + - type: getdx-ai-enabled-repos config: - api_url: https://api.getdx.com/v1/metrics - api_key: ${GETDX_API_KEY} + api_base_url: https://api.getdx.com + api_token: ${env.GETDX_API_KEY} tools: - - claude - - # User filtering configuration - users: - type: static - config: - user_ids: - - user@example.com # Include specific users - - admin@example.com - - service-account-123 - # Add more user IDs as needed - # Alternatively, use GetDX API to get the list of users - # type: getdx - # config: - # api_key: ${GETDX_WEB_API_KEY} + - ai-readiness + - ai-readiness-summary +# Alternative user filtering options for Pipeline 1: +# users: +# type: static +# config: +# user_ids: +# - user1@company.com +# - user2@company.com \ No newline at end of file diff --git a/go.mod b/go.mod index be199f1..d7b413f 100644 --- a/go.mod +++ b/go.mod @@ -43,6 +43,7 @@ require ( github.com/go-playground/validator/v10 v10.27.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-yaml v1.18.0 // indirect + github.com/golang-jwt/jwt/v5 v5.3.1 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect @@ -64,6 +65,7 @@ require ( golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc // indirect golang.org/x/mod v0.25.0 // indirect golang.org/x/net v0.42.0 // indirect + golang.org/x/oauth2 v0.34.0 // indirect golang.org/x/sys v0.35.0 // indirect golang.org/x/text v0.27.0 // indirect golang.org/x/tools v0.34.0 // indirect diff --git a/go.sum b/go.sum index 963c10d..f2a1f26 100644 --- a/go.sum +++ b/go.sum @@ -63,6 +63,8 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/google/cel-go v0.26.1 h1:iPbVVEdkhTX++hpe3lzSk7D3G3QSYqLGoHOcEio+UXQ= github.com/google/cel-go v0.26.1/go.mod h1:A9O8OU9rdvrK5MQyrqfIxo1a0u4g3sF8KB6PUIaryMM= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= @@ -122,6 +124,8 @@ golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w= golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= +golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= +golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/pkg/collector/collectors.go b/pkg/collector/collectors.go index 5ecc260..cd4a58e 100644 --- a/pkg/collector/collectors.go +++ b/pkg/collector/collectors.go @@ -101,6 +101,8 @@ func NewCollector(cfg CollectorConfig, userList users.UsersList) (Collector, err c := NewBedrockCollector(s3Client, localPath, bucketName, prefix, cfg.Name, mapper, userList) return c, nil + case "github": + return NewGitHubCollector(cfg, userList) default: return nil, fmt.Errorf("unknown collector type: %s", cfg.Type) } diff --git a/pkg/collector/github.go b/pkg/collector/github.go new file mode 100644 index 0000000..d2e7edf --- /dev/null +++ b/pkg/collector/github.go @@ -0,0 +1,594 @@ +package collector + +import ( + "context" + "fmt" + "strconv" + "strings" + "time" + + "github.com/adevinta/ai-engineering-metrics/pkg/lcel" + "github.com/adevinta/ai-engineering-metrics/pkg/logging" + "github.com/adevinta/ai-engineering-metrics/pkg/mapper" + "github.com/adevinta/ai-engineering-metrics/pkg/users" + "github.com/google/go-github/v75/github" + "github.com/sirupsen/logrus" +) + +// GitHubCollector collects AI readiness metrics from GitHub repositories +type GitHubCollector struct { + client *github.Client + repositories []string + aiIndicators []string + scanAllRepos bool + scanAllOrganizations bool // New: scan all organizations user has access to + organizationFilter []string // Optional: filter organizations when scanning + mapper mapper.UserIDMapper + filter users.UsersList + // GitHub App authentication fields + githubApp *GitHubAppAuth // GitHub App authentication handler + installations []*Installation // GitHub App installations cache +} + +var _ Collector = (*GitHubCollector)(nil) + +// RepositoryMetrics holds AI readiness data for a single repository +type RepositoryMetrics struct { + Repository string `json:"repository"` + Organization string `json:"organization"` + IsAIReady bool `json:"is_ai_ready"` + AIIndicatorsFound []string `json:"ai_indicators_found"` + ScanTimestamp time.Time `json:"scan_timestamp"` + RepositoryMetadata struct { + Private bool `json:"private"` + Language *string `json:"language"` + LastPush time.Time `json:"last_push"` + StarCount int `json:"star_count"` + ForkCount int `json:"fork_count"` + } `json:"repository_metadata"` +} + +// OrganizationSummaryMetrics holds aggregated AI readiness data for an organization +type OrganizationSummaryMetrics struct { + Organization string `json:"organization"` + TotalReposScanned int `json:"total_repos_scanned"` + AIReadyRepos int `json:"ai_ready_repos"` + AIReadinessPercent float64 `json:"ai_readiness_percentage"` + ScanTimestamp time.Time `json:"scan_timestamp"` +} + +// NewGitHubCollector creates a new GitHub collector +func NewGitHubCollector(cfg CollectorConfig, userList users.UsersList) (Collector, error) { + // GitHub App authentication is required + if err := validateGitHubAppConfig(cfg.Config); err != nil { + return nil, fmt.Errorf("GitHub App configuration required: %w", err) + } + + // Extract GitHub base URL (optional, defaults to public GitHub) + var baseURL string + if baseURLRaw, ok := cfg.Config["github_base_url"].(string); ok { + expandedBaseURL, err := lcel.ExpandEnv(baseURLRaw) + if err != nil { + return nil, fmt.Errorf("failed to expand github_base_url: %w", err) + } + baseURL = expandedBaseURL + } + + // Extract app ID + appIDRaw := cfg.Config["app_id"] + var appID int64 + switch v := appIDRaw.(type) { + case string: + parsed, err := strconv.ParseInt(v, 10, 64) + if err != nil { + return nil, fmt.Errorf("app_id must be a valid integer: %w", err) + } + appID = parsed + case int: + appID = int64(v) + case int64: + appID = v + case float64: + appID = int64(v) + default: + return nil, fmt.Errorf("app_id must be a number") + } + + // Extract and expand private key + privateKeyRaw, ok := cfg.Config["private_key"].(string) + if !ok { + return nil, fmt.Errorf("private_key must be a string") + } + + privateKey, err := lcel.ExpandEnv(privateKeyRaw) + if err != nil { + return nil, fmt.Errorf("failed to expand private_key: %w", err) + } + + if privateKey == "" { + return nil, fmt.Errorf("private_key cannot be empty") + } + + // Create GitHub App auth handler + logger := logging.LoggerFromCtx(context.Background()).WithField("component", "github_app_auth") + githubApp, err := NewGitHubAppAuthWithBaseURL(appID, privateKey, baseURL, logger) + if err != nil { + return nil, fmt.Errorf("failed to create GitHub App authentication: %w", err) + } + + // Create a basic client for now (will be replaced with installation-specific clients during collection) + client := github.NewClient(nil) + + // Set custom base URL for GitHub Enterprise + if baseURL != "" { + if !strings.HasSuffix(baseURL, "/") { + baseURL += "/" + } + client, err = client.WithEnterpriseURLs(baseURL, baseURL) + if err != nil { + return nil, fmt.Errorf("failed to set GitHub Enterprise URL: %w", err) + } + } + + // Check for scan_all_repos option + scanAllRepos := false + if scanAllRaw, ok := cfg.Config["scan_all_repos"].(bool); ok { + scanAllRepos = scanAllRaw + } + + // Check for scan_all_organizations option + scanAllOrganizations := false + if scanAllOrgsRaw, ok := cfg.Config["scan_all_organizations"].(bool); ok { + scanAllOrganizations = scanAllOrgsRaw + } + + // Extract repository list (optional if scan_all_repos is true) + var repositories []string + if reposRaw, ok := cfg.Config["repositories"].([]interface{}); ok { + for i, repo := range reposRaw { + repoStr, ok := repo.(string) + if !ok { + return nil, fmt.Errorf("repository at index %d is not a string", i) + } + if !strings.Contains(repoStr, "/") { + return nil, fmt.Errorf("repository '%s' must be in format 'owner/repo'", repoStr) + } + repositories = append(repositories, repoStr) + } + } + + // Validate that at least one scanning method is specified + if !scanAllRepos && !scanAllOrganizations && len(repositories) == 0 { + return nil, fmt.Errorf("one of 'repositories' list, 'scan_all_repos: true', or 'scan_all_organizations: true' must be specified") + } + + // Extract organization filter for scan_all_repos mode + var organizationFilter []string + if orgFilterRaw, ok := cfg.Config["organization_filter"].([]interface{}); ok { + for i, org := range orgFilterRaw { + orgStr, ok := org.(string) + if !ok { + return nil, fmt.Errorf("organization_filter at index %d is not a string", i) + } + organizationFilter = append(organizationFilter, orgStr) + } + } + + // Extract AI indicators (optional, defaults to CLAUDE.md variations) + var aiIndicators []string + if indicatorsRaw, ok := cfg.Config["ai_indicators"].([]interface{}); ok { + for i, indicator := range indicatorsRaw { + indicatorStr, ok := indicator.(string) + if !ok { + return nil, fmt.Errorf("ai_indicator at index %d is not a string", i) + } + aiIndicators = append(aiIndicators, indicatorStr) + } + } else { + // Default AI indicators + aiIndicators = []string{"CLAUDE.md", "claude.md", "Claude.md", "AGENTS.md", "agents.md", ".github/copilot-instructions.md"} + } + + // Create user mapper + userMapper, err := mapper.NewUserIDMapper(cfg.Mapper) + if err != nil { + return nil, fmt.Errorf("failed to create user mapper: %w", err) + } + + return &GitHubCollector{ + client: client, + repositories: repositories, + aiIndicators: aiIndicators, + scanAllRepos: scanAllRepos, + scanAllOrganizations: scanAllOrganizations, + organizationFilter: organizationFilter, + mapper: userMapper, + filter: userList, + githubApp: githubApp, + }, nil +} + +// Name returns the collector's name +func (g *GitHubCollector) Name() string { + return "github" +} + +// Collect scans configured repositories for AI readiness indicators and returns metrics +func (g *GitHubCollector) Collect(ctx context.Context, start, end time.Time) (map[ToolUsage]Metric, error) { + ctx = logging.WithLoggingFields(ctx, logrus.Fields{ + "component": "github_collector", + "collector": "github", + "repositories": len(g.repositories), + "ai_indicators": len(g.aiIndicators), + "scan_all_repos": g.scanAllRepos, + "scan_all_organizations": g.scanAllOrganizations, + }) + logger := logging.LoggerFromCtx(ctx) + + logger.Info("starting github ai readiness collection") + + // Initialize GitHub App installations + logger.Info("using GitHub App authentication") + installations, err := g.githubApp.ListInstallations(ctx) + if err != nil { + return nil, fmt.Errorf("failed to list GitHub App installations: %w", err) + } + g.installations = installations + + logger.WithField("installations_count", len(installations)).Info("GitHub App installations loaded") + for _, installation := range installations { + logger.WithFields(logrus.Fields{ + "installation_id": installation.ID, + "account": installation.Account, + "repositories": len(installation.Repositories), + }).Debug("installation loaded") + } + + scanTime := time.Now() + metrics := make(map[ToolUsage]Metric) + orgSummaries := make(map[string]*OrganizationSummaryMetrics) + + // Get list of repositories to scan + var repositoriesToScan []string + + if g.scanAllOrganizations { + orgRepos, err := g.getAllOrganizationRepositories(ctx) + if err != nil { + return nil, fmt.Errorf("failed to get all organization repositories: %w", err) + } + repositoriesToScan = orgRepos + logger.WithField("discovered_org_repos", len(orgRepos)).Info("discovered all organization repositories") + } else if g.scanAllRepos { + allRepos, err := g.getAllAccessibleRepositories(ctx) + if err != nil { + return nil, fmt.Errorf("failed to get all accessible repositories: %w", err) + } + repositoriesToScan = allRepos + logger.WithField("discovered_repos", len(allRepos)).Info("discovered all accessible repositories") + } else { + repositoriesToScan = g.repositories + } + + // Combine with explicitly configured repositories (avoid duplicates) + if (g.scanAllRepos || g.scanAllOrganizations) && len(g.repositories) > 0 { + repoSet := make(map[string]struct{}) + for _, repo := range repositoriesToScan { + repoSet[repo] = struct{}{} + } + for _, repo := range g.repositories { + repoSet[repo] = struct{}{} + } + repositoriesToScan = make([]string, 0, len(repoSet)) + for repo := range repoSet { + repositoriesToScan = append(repositoriesToScan, repo) + } + } + + logger.WithField("total_repos_to_scan", len(repositoriesToScan)).Info("processing repositories") + + // Process each repository + for _, repoName := range repositoriesToScan { + parts := strings.SplitN(repoName, "/", 2) + if len(parts) != 2 { + logger.WithField("repository", repoName).Error("invalid repository format, skipping") + continue + } + + owner, repo := parts[0], parts[1] + + logger.WithFields(logrus.Fields{ + "owner": owner, + "repo": repo, + }).Debug("scanning repository") + + // Check AI readiness + isReady, indicators, repoInfo, err := g.scanRepository(ctx, owner, repo) + if err != nil { + logger.WithFields(logrus.Fields{ + "owner": owner, + "repo": repo, + "error": err, + }).Error("failed to scan repository, skipping") + continue + } + + // Create repository metrics + repoMetrics := RepositoryMetrics{ + Repository: repoName, + Organization: owner, + IsAIReady: isReady, + AIIndicatorsFound: indicators, + ScanTimestamp: scanTime, + } + + // Add repository metadata + if repoInfo != nil { + repoMetrics.RepositoryMetadata.Private = repoInfo.GetPrivate() + repoMetrics.RepositoryMetadata.Language = repoInfo.Language + repoMetrics.RepositoryMetadata.StarCount = repoInfo.GetStargazersCount() + repoMetrics.RepositoryMetadata.ForkCount = repoInfo.GetForksCount() + if repoInfo.PushedAt != nil { + repoMetrics.RepositoryMetadata.LastPush = repoInfo.PushedAt.Time + } + } + + // Map user ID (repository name) + mappedUserID, err := g.mapper.Map(ctx, repoName) + if err != nil { + logger.WithField("repository", repoName).WithError(err).Error("failed to map user ID") + mappedUserID = repoName // fallback to original + } + + // Check if user should be included + if g.filter != nil && !g.filter.Include(mappedUserID) { + logger.WithField("repository", repoName).Debug("repository not in user filter, skipping") + continue + } + + // Add to metrics + toolUsage := ToolUsage{ + UserID: mappedUserID, + ToolName: "ai-readiness", + } + + metrics[toolUsage] = Metric{ + UserID: mappedUserID, + ToolName: "ai-readiness", + Metrics: map[string]any{ + "repository": repoMetrics.Repository, + "organization": repoMetrics.Organization, + "is_ai_ready": repoMetrics.IsAIReady, + "ai_indicators_found": repoMetrics.AIIndicatorsFound, + "scan_timestamp": repoMetrics.ScanTimestamp, + "repository_metadata": repoMetrics.RepositoryMetadata, + }, + } + + // Update organization summary + if orgSummary, exists := orgSummaries[owner]; exists { + orgSummary.TotalReposScanned++ + if isReady { + orgSummary.AIReadyRepos++ + } + } else { + orgSummaries[owner] = &OrganizationSummaryMetrics{ + Organization: owner, + TotalReposScanned: 1, + AIReadyRepos: 0, + ScanTimestamp: scanTime, + } + if isReady { + orgSummaries[owner].AIReadyRepos = 1 + } + } + } + + // Add organization summary metrics + for org, summary := range orgSummaries { + if summary.TotalReposScanned > 0 { + summary.AIReadinessPercent = (float64(summary.AIReadyRepos) / float64(summary.TotalReposScanned)) * 100 + } + + // Map organization name + mappedOrgID, err := g.mapper.Map(ctx, org) + if err != nil { + logger.WithField("organization", org).WithError(err).Error("failed to map organization ID") + mappedOrgID = org // fallback to original + } + + // Check if organization should be included + if g.filter != nil && !g.filter.Include(mappedOrgID) { + logger.WithField("organization", org).Debug("organization not in user filter, skipping summary") + continue + } + + toolUsage := ToolUsage{ + UserID: mappedOrgID, + ToolName: "ai-readiness-summary", + } + + metrics[toolUsage] = Metric{ + UserID: mappedOrgID, + ToolName: "ai-readiness-summary", + Metrics: map[string]any{ + "organization": summary.Organization, + "total_repos_scanned": summary.TotalReposScanned, + "ai_ready_repos": summary.AIReadyRepos, + "ai_readiness_percentage": summary.AIReadinessPercent, + "scan_timestamp": summary.ScanTimestamp, + }, + } + } + + logger.WithFields(logrus.Fields{ + "total_metrics": len(metrics), + "organizations": len(orgSummaries), + "repositories": len(g.repositories), + }).Info("github ai readiness collection completed") + + return metrics, nil +} + +// getAllOrganizationRepositories fetches all repositories from all organizations the authenticated user has access to +func (g *GitHubCollector) getAllOrganizationRepositories(ctx context.Context) ([]string, error) { + logger := logging.LoggerFromCtx(ctx) + + // Use GitHub App installations to get repositories + var allRepos []string + for _, installation := range g.installations { + // Apply organization filter if specified + if len(g.organizationFilter) > 0 && !g.isOrganizationAllowed(installation.Account) { + logger.WithField("organization", installation.Account).Debug("skipping organization - not in filter") + continue + } + + logger.WithFields(logrus.Fields{ + "installation_id": installation.ID, + "account": installation.Account, + "repositories": len(installation.Repositories), + }).Debug("adding installation repositories") + + allRepos = append(allRepos, installation.Repositories...) + } + + logger.WithField("total_org_repos", len(allRepos)).Debug("completed GitHub App organization repository discovery") + return allRepos, nil +} + +// getAllAccessibleRepositories fetches all repositories accessible through GitHub App installations +func (g *GitHubCollector) getAllAccessibleRepositories(ctx context.Context) ([]string, error) { + logger := logging.LoggerFromCtx(ctx) + + // GitHub App authentication uses installation-based repository discovery + var allRepos []string + for _, installation := range g.installations { + // Apply organization filter if specified + if len(g.organizationFilter) > 0 && !g.isOrganizationAllowed(installation.Account) { + logger.WithField("organization", installation.Account).Debug("skipping installation - not in filter") + continue + } + + logger.WithFields(logrus.Fields{ + "installation_id": installation.ID, + "account": installation.Account, + "repositories": len(installation.Repositories), + }).Debug("adding installation repositories") + + allRepos = append(allRepos, installation.Repositories...) + } + + logger.WithField("total_accessible_repos", len(allRepos)).Debug("completed GitHub App repository discovery") + return allRepos, nil +} + +// isOrganizationAllowed checks if an organization is in the allowed filter +func (g *GitHubCollector) isOrganizationAllowed(org string) bool { + if len(g.organizationFilter) == 0 { + return true // No filter means all organizations are allowed + } + + for _, allowedOrg := range g.organizationFilter { + if allowedOrg == org { + return true + } + } + return false +} + +// getClientForRepository returns the appropriate GitHub client for the given repository owner +func (g *GitHubCollector) getClientForRepository(ctx context.Context, owner string) *github.Client { + // Find the installation for this owner + for _, installation := range g.installations { + if installation.Account == owner { + // Refresh token if needed + if err := g.githubApp.RefreshInstallationToken(ctx, installation); err != nil { + // Log the error but continue with potentially expired token + logging.LoggerFromCtx(ctx).WithFields(logrus.Fields{ + "installation_id": installation.ID, + "account": installation.Account, + "error": err, + }).Warn("failed to refresh installation token") + } + + // Create client with installation access token + return g.githubApp.CreateInstallationClient(ctx, installation) + } + } + + // Fallback to default client if no installation found + logging.LoggerFromCtx(ctx).WithField("owner", owner).Warn("no GitHub App installation found for owner, using default client") + return g.client +} + +// scanRepository checks a single repository for AI readiness indicators +func (g *GitHubCollector) scanRepository(ctx context.Context, owner, repo string) (bool, []string, *github.Repository, error) { + logger := logging.LoggerFromCtx(ctx) + + // Get the appropriate client for this repository + client := g.getClientForRepository(ctx, owner) + + // Get repository information + repoInfo, _, err := client.Repositories.Get(ctx, owner, repo) + if err != nil { + return false, nil, nil, fmt.Errorf("failed to get repository info: %w", err) + } + + var foundIndicators []string + + // Check for AI indicators in the repository root + for _, indicator := range g.aiIndicators { + exists, err := g.checkFileExists(ctx, client, owner, repo, indicator) + if err != nil { + logger.WithFields(logrus.Fields{ + "owner": owner, + "repo": repo, + "indicator": indicator, + "error": err, + }).Warn("failed to check file existence") + continue + } + + if exists { + foundIndicators = append(foundIndicators, indicator) + } + } + + isReady := len(foundIndicators) > 0 + + logger.WithFields(logrus.Fields{ + "owner": owner, + "repo": repo, + "is_ai_ready": isReady, + "indicators_found": len(foundIndicators), + }).Debug("repository scan completed") + + return isReady, foundIndicators, repoInfo, nil +} + +// checkFileExists checks if a file exists in the repository root using GitHub Contents API +func (g *GitHubCollector) checkFileExists(ctx context.Context, client *github.Client, owner, repo, filename string) (bool, error) { + _, _, _, err := client.Repositories.GetContents(ctx, owner, repo, filename, nil) + if err != nil { + // GitHub API returns 404 if file doesn't exist + if isNotFoundError(err) { + return false, nil + } + return false, err + } + return true, nil +} + +// isNotFoundError checks if the error is a 404 Not Found error from GitHub API +func isNotFoundError(err error) bool { + if err == nil { + return false + } + + // Check for GitHub's ErrorResponse with 404 status + if ghErr, ok := err.(*github.ErrorResponse); ok { + return ghErr.Response.StatusCode == 404 + } + + // Fallback: check error message + return strings.Contains(err.Error(), "404") +} diff --git a/pkg/collector/github_app_auth.go b/pkg/collector/github_app_auth.go new file mode 100644 index 0000000..1dfb0dc --- /dev/null +++ b/pkg/collector/github_app_auth.go @@ -0,0 +1,373 @@ +package collector + +import ( + "context" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "fmt" + "strconv" + "strings" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/google/go-github/v75/github" + "github.com/sirupsen/logrus" + "golang.org/x/oauth2" +) + +// GitHubAppAuth handles GitHub App authentication flow +type GitHubAppAuth struct { + appID int64 + privateKey *rsa.PrivateKey + client *github.Client + logger *logrus.Entry + baseURL string // GitHub Enterprise base URL (empty for public GitHub) +} + +// Installation represents a GitHub App installation +type Installation struct { + ID int64 + Account string + AccessToken string + ExpiresAt time.Time + Repositories []string // Repository names accessible to this installation +} + +// NewGitHubAppAuth creates a new GitHub App authentication client +func NewGitHubAppAuth(appID int64, privateKeyPEM string, logger *logrus.Entry) (*GitHubAppAuth, error) { + return NewGitHubAppAuthWithBaseURL(appID, privateKeyPEM, "", logger) +} + +// NewGitHubAppAuthWithBaseURL creates a new GitHub App authentication client with custom base URL +func NewGitHubAppAuthWithBaseURL(appID int64, privateKeyPEM string, baseURL string, logger *logrus.Entry) (*GitHubAppAuth, error) { + // Parse private key + privateKey, err := parsePrivateKey(privateKeyPEM) + if err != nil { + return nil, fmt.Errorf("failed to parse private key: %w", err) + } + + // Create initial client with no authentication (will be enhanced with JWT) + client := github.NewClient(nil) + + // Set custom base URL for GitHub Enterprise + if baseURL != "" { + if !strings.HasSuffix(baseURL, "/") { + baseURL += "/" + } + client, err = client.WithEnterpriseURLs(baseURL, baseURL) + if err != nil { + return nil, fmt.Errorf("failed to set GitHub Enterprise URL: %w", err) + } + } + + return &GitHubAppAuth{ + appID: appID, + privateKey: privateKey, + client: client, + logger: logger, + baseURL: baseURL, + }, nil +} + +// parsePrivateKey parses RSA private key from PEM format or base64 encoded PEM +func parsePrivateKey(privateKeyInput string) (*rsa.PrivateKey, error) { + privateKeyPEM := privateKeyInput + + // Check if input looks like base64 encoded data (no PEM headers and only base64 characters) + if !strings.Contains(privateKeyInput, "-----BEGIN") && !strings.Contains(privateKeyInput, "-----END") { + // Try to decode as base64 + decoded, err := base64.StdEncoding.DecodeString(strings.TrimSpace(privateKeyInput)) + if err != nil { + // If base64 decoding fails, try base64 URL encoding + decoded, err = base64.URLEncoding.DecodeString(strings.TrimSpace(privateKeyInput)) + if err != nil { + return nil, fmt.Errorf("input appears to be base64 but failed to decode: %w", err) + } + } + privateKeyPEM = string(decoded) + } + + block, _ := pem.Decode([]byte(privateKeyPEM)) + if block == nil { + return nil, fmt.Errorf("failed to decode PEM block (input may be invalid PEM format or incorrectly encoded)") + } + + // Try PKCS#1 format first + if privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil { + return privateKey, nil + } + + // Try PKCS#8 format + key, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("failed to parse private key: %w", err) + } + + rsaKey, ok := key.(*rsa.PrivateKey) + if !ok { + return nil, fmt.Errorf("private key is not RSA format") + } + + return rsaKey, nil +} + +// createClientWithAuth creates a GitHub client with authentication and proper base URL +func (auth *GitHubAppAuth) createClientWithAuth(ctx context.Context, token string) (*github.Client, error) { + ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}) + tc := oauth2.NewClient(ctx, ts) + client := github.NewClient(tc) + + // Set custom base URL for GitHub Enterprise if configured + if auth.baseURL != "" { + baseURL := auth.baseURL + if !strings.HasSuffix(baseURL, "/") { + baseURL += "/" + } + var err error + client, err = client.WithEnterpriseURLs(baseURL, baseURL) + if err != nil { + return nil, fmt.Errorf("failed to set GitHub Enterprise URL: %w", err) + } + } + + return client, nil +} + +// generateJWT creates a JWT token for GitHub App authentication +func (auth *GitHubAppAuth) generateJWT() (string, error) { + now := time.Now() + + token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ + "iss": auth.appID, // Issuer: GitHub App ID + "iat": now.Unix(), // Issued at + "exp": now.Add(10 * time.Minute).Unix(), // Expires in 10 minutes (GitHub max) + }) + + tokenString, err := token.SignedString(auth.privateKey) + if err != nil { + return "", fmt.Errorf("failed to sign JWT token: %w", err) + } + + return tokenString, nil +} + +// ListInstallations fetches all installations for the GitHub App +func (auth *GitHubAppAuth) ListInstallations(ctx context.Context) ([]*Installation, error) { + // Generate JWT for app authentication + jwtToken, err := auth.generateJWT() + if err != nil { + return nil, fmt.Errorf("failed to generate JWT token: %w", err) + } + + // Create authenticated client with JWT + client, err := auth.createClientWithAuth(ctx, jwtToken) + if err != nil { + return nil, fmt.Errorf("failed to create authenticated client: %w", err) + } + + // List all installations + opts := &github.ListOptions{PerPage: 100} + var allInstallations []*github.Installation + + auth.logger.Debug("fetching GitHub App installations") + + for { + installations, resp, err := client.Apps.ListInstallations(ctx, opts) + if err != nil { + return nil, fmt.Errorf("failed to list installations: %w", err) + } + + allInstallations = append(allInstallations, installations...) + + if resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + + auth.logger.WithField("installations_found", len(allInstallations)).Debug("fetched GitHub App installations") + + // Convert to our Installation struct and generate access tokens + var installations []*Installation + for _, install := range allInstallations { + installation := &Installation{ + ID: install.GetID(), + Account: install.GetAccount().GetLogin(), + } + + // Generate access token for this installation + accessToken, expiresAt, err := auth.generateInstallationAccessToken(ctx, install.GetID()) + if err != nil { + auth.logger.WithFields(logrus.Fields{ + "installation_id": install.GetID(), + "account": installation.Account, + "error": err, + }).Warn("failed to generate access token for installation, skipping") + continue + } + + installation.AccessToken = accessToken + installation.ExpiresAt = expiresAt + + // Get repositories for this installation + repositories, err := auth.getInstallationRepositories(ctx, accessToken, install.GetID()) + if err != nil { + auth.logger.WithFields(logrus.Fields{ + "installation_id": install.GetID(), + "account": installation.Account, + "error": err, + }).Warn("failed to get installation repositories") + repositories = []string{} // Continue with empty repository list + } + installation.Repositories = repositories + + installations = append(installations, installation) + } + + auth.logger.WithField("successful_installations", len(installations)).Info("successfully authenticated installations") + + return installations, nil +} + +// generateInstallationAccessToken creates an access token for a specific installation +func (auth *GitHubAppAuth) generateInstallationAccessToken(ctx context.Context, installationID int64) (string, time.Time, error) { + // Generate JWT for app authentication + jwtToken, err := auth.generateJWT() + if err != nil { + return "", time.Time{}, fmt.Errorf("failed to generate JWT token: %w", err) + } + + // Create authenticated client with JWT + client, err := auth.createClientWithAuth(ctx, jwtToken) + if err != nil { + return "", time.Time{}, fmt.Errorf("failed to create authenticated client: %w", err) + } + + // Create installation access token + token, _, err := client.Apps.CreateInstallationToken(ctx, installationID, nil) + if err != nil { + return "", time.Time{}, fmt.Errorf("failed to create installation token: %w", err) + } + + return token.GetToken(), token.GetExpiresAt().Time, nil +} + +// getInstallationRepositories fetches repositories accessible by an installation +func (auth *GitHubAppAuth) getInstallationRepositories(ctx context.Context, accessToken string, installationID int64) ([]string, error) { + // Create client with installation access token + client, err := auth.createClientWithAuth(ctx, accessToken) + if err != nil { + return nil, fmt.Errorf("failed to create authenticated client: %w", err) + } + + opts := &github.ListOptions{PerPage: 100} + var repositories []string + + for { + repos, resp, err := client.Apps.ListRepos(ctx, opts) + if err != nil { + return nil, fmt.Errorf("failed to list installation repositories: %w", err) + } + + for _, repo := range repos.Repositories { + repositories = append(repositories, repo.GetFullName()) + } + + if resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + + auth.logger.WithFields(logrus.Fields{ + "installation_id": installationID, + "repositories": len(repositories), + }).Debug("fetched installation repositories") + + return repositories, nil +} + +// CreateInstallationClient creates a GitHub client authenticated with an installation access token +func (auth *GitHubAppAuth) CreateInstallationClient(ctx context.Context, installation *Installation) *github.Client { + client, err := auth.createClientWithAuth(ctx, installation.AccessToken) + if err != nil { + // Log error but return a basic client to maintain backward compatibility + auth.logger.WithError(err).Warn("failed to create client with base URL, falling back to default") + ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: installation.AccessToken}) + tc := oauth2.NewClient(ctx, ts) + return github.NewClient(tc) + } + return client +} + +// RefreshInstallationToken refreshes an installation access token if it's expired or about to expire +func (auth *GitHubAppAuth) RefreshInstallationToken(ctx context.Context, installation *Installation) error { + // Check if token is expired or expires within 5 minutes + if time.Until(installation.ExpiresAt) > 5*time.Minute { + return nil // Token is still valid + } + + auth.logger.WithFields(logrus.Fields{ + "installation_id": installation.ID, + "account": installation.Account, + "expires_at": installation.ExpiresAt, + }).Debug("refreshing installation access token") + + accessToken, expiresAt, err := auth.generateInstallationAccessToken(ctx, installation.ID) + if err != nil { + return fmt.Errorf("failed to refresh installation token: %w", err) + } + + installation.AccessToken = accessToken + installation.ExpiresAt = expiresAt + + auth.logger.WithFields(logrus.Fields{ + "installation_id": installation.ID, + "account": installation.Account, + "new_expires_at": installation.ExpiresAt, + }).Debug("successfully refreshed installation access token") + + return nil +} + +// validateGitHubAppConfig validates GitHub App configuration parameters +func validateGitHubAppConfig(config map[string]any) error { + // Check for app_id + appIDRaw, hasAppID := config["app_id"] + if !hasAppID { + return fmt.Errorf("app_id is required for GitHub App authentication") + } + + // Handle app_id as string or number + var appIDInt int64 + switch v := appIDRaw.(type) { + case string: + parsed, err := strconv.ParseInt(v, 10, 64) + if err != nil { + return fmt.Errorf("app_id must be a valid integer: %w", err) + } + appIDInt = parsed + case int: + appIDInt = int64(v) + case int64: + appIDInt = v + case float64: + appIDInt = int64(v) + default: + return fmt.Errorf("app_id must be a number or string, got %T", appIDRaw) + } + + if appIDInt <= 0 { + return fmt.Errorf("app_id must be a positive integer") + } + + // Check for private_key + _, hasPrivateKey := config["private_key"] + if !hasPrivateKey { + return fmt.Errorf("private_key is required for GitHub App authentication") + } + + return nil +} diff --git a/pkg/collector/github_app_auth_test.go b/pkg/collector/github_app_auth_test.go new file mode 100644 index 0000000..30edb55 --- /dev/null +++ b/pkg/collector/github_app_auth_test.go @@ -0,0 +1,200 @@ +package collector + +import ( + "encoding/base64" + "testing" + + "github.com/sirupsen/logrus" +) + +func TestValidateGitHubAppConfig(t *testing.T) { + tests := []struct { + name string + config map[string]any + expectError bool + }{ + { + name: "valid config with integer app_id", + config: map[string]any{ + "app_id": 123456, + "private_key": "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + }, + expectError: false, + }, + { + name: "valid config with string app_id", + config: map[string]any{ + "app_id": "123456", + "private_key": "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + }, + expectError: false, + }, + { + name: "missing app_id", + config: map[string]any{ + "private_key": "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + }, + expectError: true, + }, + { + name: "missing private_key", + config: map[string]any{ + "app_id": 123456, + }, + expectError: true, + }, + { + name: "invalid app_id type", + config: map[string]any{ + "app_id": []string{"invalid"}, + "private_key": "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + }, + expectError: true, + }, + { + name: "zero app_id", + config: map[string]any{ + "app_id": 0, + "private_key": "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + }, + expectError: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateGitHubAppConfig(tt.config) + if (err != nil) != tt.expectError { + t.Errorf("validateGitHubAppConfig() error = %v, expectError %v", err, tt.expectError) + } + }) + } +} + +func TestParsePrivateKey(t *testing.T) { + // Sample PEM private key for testing (this is a mock key, not a real one) + samplePEM := `-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAqFO5xwz5SXP8YOlrJmBbwg7lW7jUfUKs9mFl4v8X7qyC2wE8 +Sample Key Content (truncated for safety) +-----END RSA PRIVATE KEY-----` + + // Base64 encode the sample PEM + base64EncodedPEM := base64.StdEncoding.EncodeToString([]byte(samplePEM)) + + tests := []struct { + name string + privateKey string + expectError bool + }{ + { + name: "empty key", + privateKey: "", + expectError: true, + }, + { + name: "invalid PEM", + privateKey: "not a pem key", + expectError: true, + }, + { + name: "invalid key data", + privateKey: "-----BEGIN RSA PRIVATE KEY-----\ninvalid\n-----END RSA PRIVATE KEY-----", + expectError: true, + }, + { + name: "base64 encoded PEM", + privateKey: base64EncodedPEM, + expectError: true, // Will still error because this is not a real key, but should pass base64 decoding + }, + { + name: "invalid base64", + privateKey: "not_valid_base64!@#", + expectError: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := parsePrivateKey(tt.privateKey) + if (err != nil) != tt.expectError { + t.Errorf("parsePrivateKey() error = %v, expectError %v", err, tt.expectError) + } + }) + } +} + +func TestNewGitHubAppAuth(t *testing.T) { + tests := []struct { + name string + appID int64 + privateKey string + expectError bool + }{ + { + name: "invalid private key", + appID: 123456, + privateKey: "invalid key", + expectError: true, + }, + { + name: "zero app ID", + appID: 0, + privateKey: "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + expectError: true, // parsePrivateKey will fail on invalid key format + }, + } + + logger := logrus.NewEntry(logrus.New()) + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := NewGitHubAppAuth(tt.appID, tt.privateKey, logger) + if (err != nil) != tt.expectError { + t.Errorf("NewGitHubAppAuth() error = %v, expectError %v", err, tt.expectError) + } + }) + } +} + +func TestNewGitHubAppAuthWithBaseURL(t *testing.T) { + tests := []struct { + name string + appID int64 + privateKey string + baseURL string + expectError bool + }{ + { + name: "valid with enterprise base URL", + appID: 123456, + privateKey: "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + baseURL: "https://github.enterprise.com/api/v3", + expectError: true, // Will fail on key parsing but should not fail on base URL + }, + { + name: "valid with empty base URL (public GitHub)", + appID: 123456, + privateKey: "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + baseURL: "", + expectError: true, // Will fail on key parsing but should not fail on base URL + }, + { + name: "invalid base URL should still work (let GitHub client handle it)", + appID: 123456, + privateKey: "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + baseURL: "not-a-valid-url", + expectError: true, // Will fail on key parsing, base URL validation is deferred to GitHub client + }, + } + + logger := logrus.NewEntry(logrus.New()) + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := NewGitHubAppAuthWithBaseURL(tt.appID, tt.privateKey, tt.baseURL, logger) + if (err != nil) != tt.expectError { + t.Errorf("NewGitHubAppAuthWithBaseURL() error = %v, expectError %v", err, tt.expectError) + } + }) + } +} diff --git a/pkg/collector/github_test.go b/pkg/collector/github_test.go new file mode 100644 index 0000000..296099d --- /dev/null +++ b/pkg/collector/github_test.go @@ -0,0 +1,494 @@ +package collector + +import ( + "context" + "net/http" + "testing" + "time" + + "github.com/adevinta/ai-engineering-metrics/pkg/mapper" + "github.com/google/go-github/v75/github" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNewGitHubCollector(t *testing.T) { + tests := []struct { + name string + config CollectorConfig + wantErr bool + errMsg string + }{ + { + name: "valid configuration with repositories", + config: CollectorConfig{ + Config: map[string]any{ + "app_id": 123456, + "private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----", + "repositories": []interface{}{ + "owner/repo1", + "owner/repo2", + }, + }, + Mapper: mapper.MapperConfig{ + Type: "passthrough", + Config: map[string]any{}, + }, + }, + wantErr: true, // Will fail due to invalid private key, but validates config structure + errMsg: "failed to parse private key", + }, + { + name: "valid configuration with scan_all_repos", + config: CollectorConfig{ + Config: map[string]any{ + "app_id": 123456, + "private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----", + "scan_all_repos": true, + }, + Mapper: mapper.MapperConfig{ + Type: "passthrough", + Config: map[string]any{}, + }, + }, + wantErr: true, // Will fail due to invalid private key, but validates config structure + errMsg: "failed to parse private key", + }, + { + name: "missing private_key", + config: CollectorConfig{ + Config: map[string]any{ + "app_id": 123456, + "scan_all_repos": true, + }, + Mapper: mapper.MapperConfig{ + Type: "passthrough", + Config: map[string]any{}, + }, + }, + wantErr: true, + errMsg: "private_key is required", + }, + { + name: "missing GitHub App credentials", + config: CollectorConfig{ + Config: map[string]any{ + "repositories": []interface{}{"owner/repo"}, + }, + }, + wantErr: true, + errMsg: "GitHub App configuration required", + }, + { + name: "invalid app_id type", + config: CollectorConfig{ + Config: map[string]any{ + "app_id": []string{"invalid"}, + "private_key": "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + "repositories": []interface{}{"owner/repo"}, + }, + }, + wantErr: true, + errMsg: "app_id must be a number", + }, + { + name: "no scanning method specified", + config: CollectorConfig{ + Config: map[string]any{ + "scan_all_repos": false, + "scan_all_organizations": false, + // no repositories, app_id, or private_key specified + }, + }, + wantErr: true, + errMsg: "app_id is required", + }, + { + name: "invalid repository format", + config: CollectorConfig{ + Config: map[string]any{ + "repositories": []interface{}{ + "invalid-repo-format", + }, + }, + }, + wantErr: true, + errMsg: "app_id is required", + }, + { + name: "empty private_key", + config: CollectorConfig{ + Config: map[string]any{ + "app_id": 123456, + "private_key": "", + "repositories": []interface{}{"owner/repo"}, + }, + }, + wantErr: true, + errMsg: "private_key cannot be empty", + }, + { + name: "invalid private_key format", + config: CollectorConfig{ + Config: map[string]any{ + "app_id": 123456, + "private_key": "not-a-valid-key", + "repositories": []interface{}{"owner/repo"}, + }, + }, + wantErr: true, + errMsg: "failed to parse private key", + }, + { + name: "zero app_id", + config: CollectorConfig{ + Config: map[string]any{ + "app_id": 0, + "private_key": "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + "repositories": []interface{}{ + "owner/repo", + }, + }, + }, + wantErr: true, + errMsg: "app_id must be a positive integer", + }, + { + name: "valid GitHub App configuration", + config: CollectorConfig{ + Config: map[string]any{ + "app_id": "123456", + "private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAqFO5xwz5SX...sample...key...-----END RSA PRIVATE KEY-----", + "repositories": []interface{}{"owner/repo"}, + }, + }, + wantErr: true, // Will fail due to invalid private key format, but config parsing should pass + errMsg: "failed to parse private key", + }, + { + name: "missing app_id with private_key", + config: CollectorConfig{ + Config: map[string]any{ + "private_key": "-----BEGIN RSA PRIVATE KEY-----\ntest\n-----END RSA PRIVATE KEY-----", + "repositories": []interface{}{"owner/repo"}, + }, + }, + wantErr: true, + errMsg: "GitHub App configuration required", + }, + { + name: "missing private_key with app_id", + config: CollectorConfig{ + Config: map[string]any{ + "app_id": 123456, + "repositories": []interface{}{"owner/repo"}, + }, + }, + wantErr: true, + errMsg: "GitHub App configuration required", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + collector, err := NewGitHubCollector(tt.config, nil) + + if tt.wantErr { + assert.Error(t, err) + assert.Contains(t, err.Error(), tt.errMsg) + assert.Nil(t, collector) + } else { + assert.NoError(t, err) + assert.NotNil(t, collector) + assert.Equal(t, "github", collector.Name()) + + ghCollector := collector.(*GitHubCollector) + assert.NotNil(t, ghCollector.client) + assert.NotEmpty(t, ghCollector.aiIndicators) + } + }) + } +} + +func TestGitHubCollector_isOrganizationAllowed(t *testing.T) { + tests := []struct { + name string + filter []string + org string + allowed bool + }{ + { + name: "no filter - all allowed", + filter: []string{}, + org: "any-org", + allowed: true, + }, + { + name: "org in filter", + filter: []string{"allowed-org", "another-org"}, + org: "allowed-org", + allowed: true, + }, + { + name: "org not in filter", + filter: []string{"allowed-org", "another-org"}, + org: "blocked-org", + allowed: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + collector := &GitHubCollector{ + organizationFilter: tt.filter, + } + + result := collector.isOrganizationAllowed(tt.org) + assert.Equal(t, tt.allowed, result) + }) + } +} + +func TestGitHubCollector_checkFileExists(t *testing.T) { + tests := []struct { + name string + statusCode int + wantExists bool + wantErr bool + }{ + { + name: "file exists", + statusCode: http.StatusOK, + wantExists: true, + wantErr: false, + }, + { + name: "file not found", + statusCode: http.StatusNotFound, + wantExists: false, + wantErr: false, + }, + { + name: "api error", + statusCode: http.StatusInternalServerError, + wantExists: false, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Create a mock GitHub client that returns the specified status code + client := github.NewClient(nil) + + collector := &GitHubCollector{ + client: client, + } + _ = collector // Avoid unused variable error + + // Note: This would require more complex mocking in a real implementation + // For now, we'll just test the error handling logic + t.Skip("Requires GitHub API mocking - integration test recommended") + }) + } +} + +func TestRepositoryMetrics_Structure(t *testing.T) { + // Test that the metrics structure is correctly formatted + now := time.Now() + repoMetrics := RepositoryMetrics{ + Repository: "owner/repo", + Organization: "owner", + IsAIReady: true, + AIIndicatorsFound: []string{"CLAUDE.md"}, + ScanTimestamp: now, + } + + repoMetrics.RepositoryMetadata.Private = false + repoMetrics.RepositoryMetadata.StarCount = 100 + repoMetrics.RepositoryMetadata.ForkCount = 25 + repoMetrics.RepositoryMetadata.LastPush = now + + // Verify structure can be converted to map[string]any for metrics + metricsMap := map[string]any{ + "repository": repoMetrics.Repository, + "organization": repoMetrics.Organization, + "is_ai_ready": repoMetrics.IsAIReady, + "ai_indicators_found": repoMetrics.AIIndicatorsFound, + "scan_timestamp": repoMetrics.ScanTimestamp, + "repository_metadata": repoMetrics.RepositoryMetadata, + } + + assert.Equal(t, "owner/repo", metricsMap["repository"]) + assert.Equal(t, "owner", metricsMap["organization"]) + assert.Equal(t, true, metricsMap["is_ai_ready"]) + assert.Equal(t, []string{"CLAUDE.md"}, metricsMap["ai_indicators_found"]) + assert.Equal(t, now, metricsMap["scan_timestamp"]) +} + +func TestOrganizationSummaryMetrics_Structure(t *testing.T) { + // Test that the organization summary structure is correctly formatted + now := time.Now() + orgSummary := OrganizationSummaryMetrics{ + Organization: "test-org", + TotalReposScanned: 10, + AIReadyRepos: 7, + AIReadinessPercent: 70.0, + ScanTimestamp: now, + } + + // Verify structure can be converted to map[string]any for metrics + metricsMap := map[string]any{ + "organization": orgSummary.Organization, + "total_repos_scanned": orgSummary.TotalReposScanned, + "ai_ready_repos": orgSummary.AIReadyRepos, + "ai_readiness_percentage": orgSummary.AIReadinessPercent, + "scan_timestamp": orgSummary.ScanTimestamp, + } + + assert.Equal(t, "test-org", metricsMap["organization"]) + assert.Equal(t, 10, metricsMap["total_repos_scanned"]) + assert.Equal(t, 7, metricsMap["ai_ready_repos"]) + assert.Equal(t, 70.0, metricsMap["ai_readiness_percentage"]) + assert.Equal(t, now, metricsMap["scan_timestamp"]) +} + +// Integration test structure for manual testing with real GitHub API +func TestGitHubCollector_Integration(t *testing.T) { + // Skip this test in CI/CD - only for manual testing + t.Skip("Integration test - requires GitHub App credentials") + + // This test would be run manually with: + // GITHUB_APP_ID=123456 GITHUB_PRIVATE_KEY="$(cat key.pem)" go test -run TestGitHubCollector_Integration + + config := CollectorConfig{ + Config: map[string]any{ + "app_id": "${env.GITHUB_APP_ID}", + "private_key": "${env.GITHUB_PRIVATE_KEY}", + "repositories": []interface{}{ + "adevinta/ai-engineering-metrics", // This repo has a CLAUDE.md file + }, + }, + Mapper: mapper.MapperConfig{ + Type: "passthrough", + Config: map[string]any{}, + }, + } + + collector, err := NewGitHubCollector(config, nil) + require.NoError(t, err) + + ctx := context.Background() + start := time.Now().Add(-24 * time.Hour) + end := time.Now() + + metrics, err := collector.Collect(ctx, start, end) + require.NoError(t, err) + + // Verify we got metrics + assert.Greater(t, len(metrics), 0) + + // Look for repository and summary metrics + var foundRepo, foundSummary bool + for toolUsage, metric := range metrics { + if toolUsage.ToolName == "ai-readiness" { + foundRepo = true + assert.Contains(t, metric.Metrics, "repository") + assert.Contains(t, metric.Metrics, "is_ai_ready") + } + if toolUsage.ToolName == "ai-readiness-summary" { + foundSummary = true + assert.Contains(t, metric.Metrics, "organization") + assert.Contains(t, metric.Metrics, "ai_readiness_percentage") + } + } + + assert.True(t, foundRepo, "Should find repository metrics") + assert.True(t, foundSummary, "Should find organization summary metrics") +} + +// Test for scan all organizations functionality +func TestGitHubCollector_ScanAllOrganizations(t *testing.T) { + t.Skip("Integration test - requires GitHub App credentials and careful testing") + + // This would test the scan_all_organizations functionality + config := CollectorConfig{ + Config: map[string]any{ + "app_id": "${env.GITHUB_APP_ID}", + "private_key": "${env.GITHUB_PRIVATE_KEY}", + "scan_all_organizations": true, + "organization_filter": []interface{}{ + "adevinta", // Only scan adevinta organization + }, + }, + Mapper: mapper.MapperConfig{ + Type: "passthrough", + Config: map[string]any{}, + }, + } + + collector, err := NewGitHubCollector(config, nil) + require.NoError(t, err) + + ctx := context.Background() + start := time.Now().Add(-24 * time.Hour) + end := time.Now() + + metrics, err := collector.Collect(ctx, start, end) + require.NoError(t, err) + + // Should have found repositories from the organization + assert.Greater(t, len(metrics), 0) + + // All repository metrics should be from filtered organizations + for toolUsage, metric := range metrics { + if toolUsage.ToolName == "ai-readiness" { + org, ok := metric.Metrics["organization"].(string) + require.True(t, ok) + assert.Equal(t, "adevinta", org) + } + } +} + +// Test for scan all repos functionality +func TestGitHubCollector_ScanAllRepos(t *testing.T) { + t.Skip("Integration test - requires GitHub App credentials and careful testing") + + // This would test the scan_all_repos functionality + config := CollectorConfig{ + Config: map[string]any{ + "app_id": "${env.GITHUB_APP_ID}", + "private_key": "${env.GITHUB_PRIVATE_KEY}", + "scan_all_repos": true, + "organization_filter": []interface{}{ + "adevinta", // Only scan adevinta repos + }, + }, + Mapper: mapper.MapperConfig{ + Type: "passthrough", + Config: map[string]any{}, + }, + } + + collector, err := NewGitHubCollector(config, nil) + require.NoError(t, err) + + ctx := context.Background() + start := time.Now().Add(-24 * time.Hour) + end := time.Now() + + metrics, err := collector.Collect(ctx, start, end) + require.NoError(t, err) + + // Should have found multiple repositories + assert.Greater(t, len(metrics), 1) + + // All repository metrics should be from filtered organizations + for toolUsage, metric := range metrics { + if toolUsage.ToolName == "ai-readiness" { + org, ok := metric.Metrics["organization"].(string) + require.True(t, ok) + assert.Equal(t, "adevinta", org) + } + } +} diff --git a/pkg/dx/client.go b/pkg/dx/client.go index 4d73fe2..38f4ed5 100644 --- a/pkg/dx/client.go +++ b/pkg/dx/client.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "fmt" + "io" "net/http" "net/url" "time" @@ -78,6 +79,9 @@ func (c *dxClient) post(url string, values url.Values, input, out any) error { "payload_size": len(data), }).Info("sending dx api request") + // Debug log the request payload + logger.WithField("request_payload", string(data)).Debug("dx api request payload") + requestStart := time.Now() resp, err := c.Do(req) duration := time.Since(requestStart) @@ -94,7 +98,16 @@ func (c *dxClient) post(url string, values url.Values, input, out any) error { }).Info("received dx api response") if resp.StatusCode != http.StatusOK { - logger.WithField("status_code", resp.StatusCode).Error("dx api returned non-200 status") + // Read the response body for debugging + body, err := io.ReadAll(resp.Body) + if err != nil { + logger.WithError(err).Error("failed to read error response body") + } else { + logger.WithFields(logrus.Fields{ + "status_code": resp.StatusCode, + "response_body": string(body), + }).Error("dx api returned non-200 status") + } return fmt.Errorf("unexpected status code: %d", resp.StatusCode) } diff --git a/pkg/dx/datacloud_api.go b/pkg/dx/datacloud_api.go index 54739ec..e500b28 100644 --- a/pkg/dx/datacloud_api.go +++ b/pkg/dx/datacloud_api.go @@ -81,3 +81,29 @@ type DXAIMetricResponse struct { type DXAIMetricsResponse struct { Data []DXAIMetricResponse `json:"data"` } + +// DXCustomMetric represents a custom metric in GetDX format +type DXCustomMetric struct { + Reference string `json:"reference"` + Key string `json:"key"` + Value float64 `json:"value"` + Metadata map[string]any `json:"metadata,omitempty"` + Timestamp string `json:"timestamp"` +} + +type DXCustomMetricResponse struct { + ID string `json:"id"` + Reference string `json:"reference"` + Key string `json:"key"` + Value float64 `json:"value"` + Metadata map[string]any `json:"metadata,omitempty"` + Timestamp string `json:"timestamp"` +} + +func (c *DatacloudAPIClient) PushCustomMetric(ctx context.Context, metric DXCustomMetric) (DXCustomMetricResponse, error) { + resp := DXCustomMetricResponse{} + if err := c.dxClient.post(fmt.Sprintf("%s/api/customMetrics.push", c.apiURL), nil, metric, &resp); err != nil { + return DXCustomMetricResponse{}, err + } + return resp, nil +} diff --git a/pkg/pipeline/pipeline.go b/pkg/pipeline/pipeline.go index 42cf3f0..5c35791 100644 --- a/pkg/pipeline/pipeline.go +++ b/pkg/pipeline/pipeline.go @@ -46,7 +46,7 @@ func NewPipelines(cfg Config) ([]Pipeline, error) { type PipelineConfig struct { Collectors []collector.CollectorConfig `yaml:"collectors"` Publishers []publisher.PublisherConfig `yaml:"publishers"` - Users users.UserList `yaml:"users"` + Users *users.UserList `yaml:"users,omitempty"` } type Pipeline struct { @@ -58,9 +58,16 @@ type Pipeline struct { func NewPipeline(cfg PipelineConfig) (Pipeline, error) { pipeline := Pipeline{} - userList, err := users.NewUserList(cfg.Users) - if err != nil { - return Pipeline{}, fmt.Errorf("failed to create user list: %w", err) + var userList users.UsersList + if cfg.Users != nil { + var err error + userList, err = users.NewUserList(*cfg.Users) + if err != nil { + return Pipeline{}, fmt.Errorf("failed to create user list: %w", err) + } + } else { + // Default to allow all users when no user filtering is specified + userList = users.NewAllowAllUserFilter() } pipeline.Users = userList diff --git a/pkg/pipeline/pipeline_test.go b/pkg/pipeline/pipeline_test.go new file mode 100644 index 0000000..d40e3ab --- /dev/null +++ b/pkg/pipeline/pipeline_test.go @@ -0,0 +1,61 @@ +package pipeline + +import ( + "testing" + + "github.com/adevinta/ai-engineering-metrics/pkg/collector" + "github.com/adevinta/ai-engineering-metrics/pkg/publisher" + "github.com/adevinta/ai-engineering-metrics/pkg/users" + "github.com/stretchr/testify/assert" +) + +func TestPipelineWithOptionalUsers(t *testing.T) { + tests := []struct { + name string + config PipelineConfig + expectErr bool + checkUserFilter func(users.UsersList) bool + }{ + { + name: "pipeline with users field", + config: PipelineConfig{ + Users: &users.UserList{ + Type: "all", + Config: map[string]interface{}{}, + }, + Collectors: []collector.CollectorConfig{}, + Publishers: []publisher.PublisherConfig{}, + }, + expectErr: false, + checkUserFilter: func(ul users.UsersList) bool { + return ul.Include("any-user") + }, + }, + { + name: "pipeline without users field (optional)", + config: PipelineConfig{ + Users: nil, // No users field + Collectors: []collector.CollectorConfig{}, + Publishers: []publisher.PublisherConfig{}, + }, + expectErr: false, + checkUserFilter: func(ul users.UsersList) bool { + return ul.Include("any-user") // Should default to allow all + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + pipeline, err := NewPipeline(tt.config) + + if tt.expectErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + assert.NotNil(t, pipeline.Users) + assert.True(t, tt.checkUserFilter(pipeline.Users)) + } + }) + } +} diff --git a/pkg/publisher/getdx_ai_enabled_repos.go b/pkg/publisher/getdx_ai_enabled_repos.go new file mode 100644 index 0000000..ea26c70 --- /dev/null +++ b/pkg/publisher/getdx_ai_enabled_repos.go @@ -0,0 +1,249 @@ +package publisher + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/adevinta/ai-engineering-metrics/pkg/collector" + "github.com/adevinta/ai-engineering-metrics/pkg/dx" + "github.com/adevinta/ai-engineering-metrics/pkg/lcel" + "github.com/adevinta/ai-engineering-metrics/pkg/logging" + "github.com/adevinta/ai-engineering-metrics/pkg/users" + "github.com/sirupsen/logrus" +) + +// GetDXAIEnabledReposPublisher publishes ai-readiness metrics as GetDX custom metrics +type GetDXAIEnabledReposPublisher struct { + *dx.DatacloudAPIClient + name string + userList users.UsersList + tools map[string]struct{} +} + +func NewGetDXAIEnabledReposPublisher(cfg map[string]any, userList users.UsersList) (*GetDXAIEnabledReposPublisher, error) { + apiKey, ok := cfg["api_token"].(string) + if !ok { + return nil, fmt.Errorf("api_token is not a string") + } + apiKey, err := lcel.ExpandEnv(apiKey) + if err != nil { + return nil, fmt.Errorf("failed to expand api key: %w", err) + } + apiURL, ok := cfg["api_base_url"].(string) + if !ok { + return nil, fmt.Errorf("api_base_url is not a string") + } + tools, ok := cfg["tools"].([]any) + if !ok { + return nil, fmt.Errorf("tools is missing or not a list") + } + toolsMap := make(map[string]struct{}) + for _, tool := range tools { + toolString, ok := tool.(string) + if !ok { + return nil, fmt.Errorf("tool is not a string") + } + toolsMap[toolString] = struct{}{} + } + dxClient, err := dx.NewDatacloudAPIClient(dx.WithDatacloudAPIKey(apiKey), dx.WithDatacloudAPIURL(apiURL)) + if err != nil { + return nil, fmt.Errorf("failed to create DX client: %w", err) + } + return &GetDXAIEnabledReposPublisher{ + DatacloudAPIClient: dxClient, + userList: userList, + tools: toolsMap, + }, nil +} + +// Name returns the publisher's name +func (p *GetDXAIEnabledReposPublisher) Name() string { + return "getdx-ai-enabled-repos" +} + +// Publish sends ai-readiness metrics as custom metrics to GetDX +func (p *GetDXAIEnabledReposPublisher) Publish(ctx context.Context, start, end time.Time, metrics map[collector.ToolUsage]collector.Metric) error { + ctx = logging.WithLoggingFields(ctx, logrus.Fields{ + "component": "getdx_ai_enabled_repos_publisher", + "publisher": "getdx-ai-enabled-repos", + "start_date": formatDate(start), + "end_date": formatDate(end), + "input_metrics": len(metrics), + "configured_tools": len(p.tools), + }) + logger := logging.LoggerFromCtx(ctx) + + logger.Info("starting dx custom metric publishing") + + publishedCount := 0 + errors := make([]error, 0) + + for key, metric := range metrics { + // Only process ai-readiness metrics + if !strings.HasPrefix(key.ToolName, "ai-readiness") { + continue + } + + // Check if tool is configured to be published + if _, ok := p.tools[key.ToolName]; !ok { + continue + } + + customMetrics, err := p.convertToCustomMetrics(key, metric, start) + if err != nil { + logger.WithError(err).WithFields(logrus.Fields{ + "user_id": key.UserID, + "tool_name": key.ToolName, + }).Warn("failed to convert metric to custom format") + errors = append(errors, err) + continue + } + + // Send each custom metric + for _, customMetric := range customMetrics { + publishStart := time.Now() + _, err := p.PushCustomMetric(ctx, customMetric) + duration := time.Since(publishStart) + + if err != nil { + logger.WithError(err).WithFields(logrus.Fields{ + "duration_ms": duration.Milliseconds(), + "reference": customMetric.Reference, + "key": customMetric.Key, + }).Error("failed to push custom metric to dx") + errors = append(errors, err) + continue + } + + publishedCount++ + logger.WithFields(logrus.Fields{ + "duration_ms": duration.Milliseconds(), + "reference": customMetric.Reference, + "key": customMetric.Key, + "value": customMetric.Value, + }).Debug("successfully pushed custom metric") + } + } + + logger.WithFields(logrus.Fields{ + "published_metrics": publishedCount, + "errors": len(errors), + }).Info("completed dx custom metric publishing") + + if len(errors) > 0 { + return fmt.Errorf("failed to publish %d metrics: %v", len(errors), errors[0]) + } + + return nil +} + +// convertToCustomMetrics converts ai-readiness metrics to GetDX custom metric format +func (p *GetDXAIEnabledReposPublisher) convertToCustomMetrics(key collector.ToolUsage, metric collector.Metric, timestamp time.Time) ([]dx.DXCustomMetric, error) { + timestampStr := timestamp.Format(time.RFC3339) + var customMetrics []dx.DXCustomMetric + + switch key.ToolName { + case "ai-readiness": + // Individual repository metrics + repository, ok := metric.Metrics["repository"].(string) + if !ok { + return nil, fmt.Errorf("repository field missing or not a string") + } + organization, ok := metric.Metrics["organization"].(string) + if !ok { + return nil, fmt.Errorf("organization field missing or not a string") + } + isAIReady, ok := metric.Metrics["is_ai_ready"].(bool) + if !ok { + return nil, fmt.Errorf("is_ai_ready field missing or not a boolean") + } + + // Convert boolean to float64 (1.0 for true, 0.0 for false) + readinessValue := 0.0 + if isAIReady { + readinessValue = 1.0 + } + + // Create the custom metric + customMetrics = append(customMetrics, dx.DXCustomMetric{ + Reference: fmt.Sprintf("ai-readiness-%s", sanitizeKey(organization)), + Key: fmt.Sprintf("repository_ai_ready_%s", sanitizeKey(repository)), + Value: readinessValue, + Metadata: map[string]any{ + "source": "ai-metrics-collector", + "repository": repository, + "organization": organization, + }, + Timestamp: timestampStr, + }) + + case "ai-readiness-summary": + // Organizational summary metrics + organization, ok := metric.Metrics["organization"].(string) + if !ok { + return nil, fmt.Errorf("organization field missing or not a string") + } + + // Total repositories scanned + if totalRepos, ok := metric.Metrics["total_repos_scanned"].(int); ok { + customMetrics = append(customMetrics, dx.DXCustomMetric{ + Reference: fmt.Sprintf("ai-readiness-summary-%s", sanitizeKey(organization)), + Key: "total_repos_scanned", + Value: float64(totalRepos), + Metadata: map[string]any{ + "source": "ai-metrics-collector", + "organization": organization, + "metric_type": "count", + }, + Timestamp: timestampStr, + }) + } + + // AI ready repositories count + if aiReadyRepos, ok := metric.Metrics["ai_ready_repos"].(int); ok { + customMetrics = append(customMetrics, dx.DXCustomMetric{ + Reference: fmt.Sprintf("ai-readiness-summary-%s", sanitizeKey(organization)), + Key: "ai_ready_repos", + Value: float64(aiReadyRepos), + Metadata: map[string]any{ + "source": "ai-metrics-collector", + "organization": organization, + "metric_type": "count", + }, + Timestamp: timestampStr, + }) + } + + // AI readiness percentage + if readinessPercent, ok := metric.Metrics["ai_readiness_percentage"].(float64); ok { + customMetrics = append(customMetrics, dx.DXCustomMetric{ + Reference: fmt.Sprintf("ai-readiness-summary-%s", sanitizeKey(organization)), + Key: "ai_readiness_percentage", + Value: readinessPercent, + Metadata: map[string]any{ + "source": "ai-metrics-collector", + "organization": organization, + "metric_type": "percentage", + }, + Timestamp: timestampStr, + }) + } + + default: + return nil, fmt.Errorf("unsupported tool name: %s", key.ToolName) + } + + return customMetrics, nil +} + +// sanitizeKey converts repository names to valid metric keys +func sanitizeKey(repository string) string { + // Replace special characters with underscores + result := strings.ReplaceAll(repository, "/", "_") + result = strings.ReplaceAll(result, "-", "_") + result = strings.ReplaceAll(result, ".", "_") + result = strings.ToLower(result) + return result +} diff --git a/pkg/publisher/getdx_ai_enabled_repos_reference_test.go b/pkg/publisher/getdx_ai_enabled_repos_reference_test.go new file mode 100644 index 0000000..044d85d --- /dev/null +++ b/pkg/publisher/getdx_ai_enabled_repos_reference_test.go @@ -0,0 +1,90 @@ +package publisher + +import ( + "testing" + "time" + + "github.com/adevinta/ai-engineering-metrics/pkg/collector" + "github.com/stretchr/testify/assert" +) + +func TestReference_Sanitization(t *testing.T) { + publisher := &GetDXAIEnabledReposPublisher{ + tools: map[string]struct{}{ + "ai-readiness": {}, + "ai-readiness-summary": {}, + }, + } + + tests := []struct { + name string + orgName string + expectedRef string + toolName string + }{ + { + name: "organization with hyphens", + orgName: "claude-code-actions", + expectedRef: "ai-readiness-summary-claude_code_actions", + toolName: "ai-readiness-summary", + }, + { + name: "organization with dots", + orgName: "my.org.com", + expectedRef: "ai-readiness-summary-my_org_com", + toolName: "ai-readiness-summary", + }, + { + name: "repository reference with special chars", + orgName: "test-org", + expectedRef: "ai-readiness-test_org", + toolName: "ai-readiness", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var metrics map[string]any + if tt.toolName == "ai-readiness-summary" { + metrics = map[string]any{ + "organization": tt.orgName, + "total_repos_scanned": 10, + "ai_ready_repos": 5, + "ai_readiness_percentage": 50.0, + } + } else { + metrics = map[string]any{ + "repository": "test/repo", + "organization": tt.orgName, + "is_ai_ready": true, + "files_found": []string{"CLAUDE.md"}, + } + } + + toolUsage := collector.ToolUsage{ + UserID: "test@example.com", + ToolName: tt.toolName, + } + + metric := collector.Metric{ + UserID: "test@example.com", + ToolName: tt.toolName, + Metrics: metrics, + } + + customMetrics, err := publisher.convertToCustomMetrics(toolUsage, metric, time.Now()) + assert.NoError(t, err) + assert.NotEmpty(t, customMetrics) + + // Check that at least one metric has the expected reference + found := false + for _, cm := range customMetrics { + if cm.Reference == tt.expectedRef { + found = true + break + } + } + assert.True(t, found, "Expected reference %s not found in custom metrics", tt.expectedRef) + }) + } +} diff --git a/pkg/publisher/getdx_ai_enabled_repos_test.go b/pkg/publisher/getdx_ai_enabled_repos_test.go new file mode 100644 index 0000000..13ca339 --- /dev/null +++ b/pkg/publisher/getdx_ai_enabled_repos_test.go @@ -0,0 +1,224 @@ +package publisher + +import ( + "testing" + "time" + + "github.com/adevinta/ai-engineering-metrics/pkg/collector" + "github.com/adevinta/ai-engineering-metrics/pkg/users" + "github.com/stretchr/testify/assert" +) + +func TestNewGetDXAIEnabledReposPublisher(t *testing.T) { + tests := []struct { + name string + config map[string]any + expectError bool + }{ + { + name: "valid config", + config: map[string]any{ + "api_token": "test-token", + "api_base_url": "https://test.getdx.net", + "tools": []any{"ai-readiness", "ai-readiness-summary"}, + }, + expectError: false, + }, + { + name: "missing api_token", + config: map[string]any{ + "api_base_url": "https://test.getdx.net", + "tools": []any{"ai-readiness"}, + }, + expectError: true, + }, + { + name: "missing api_base_url", + config: map[string]any{ + "api_token": "test-token", + "tools": []any{"ai-readiness"}, + }, + expectError: true, + }, + { + name: "missing tools", + config: map[string]any{ + "api_token": "test-token", + "api_base_url": "https://test.getdx.net", + }, + expectError: true, + }, + } + + userList := &users.StaticUserFilter{} + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := NewGetDXAIEnabledReposPublisher(tt.config, userList) + if (err != nil) != tt.expectError { + t.Errorf("NewGetDXAIEnabledReposPublisher() error = %v, expectError %v", err, tt.expectError) + } + }) + } +} + +func TestConvertToCustomMetrics(t *testing.T) { + publisher := &GetDXAIEnabledReposPublisher{} + timestamp := time.Date(2026, 2, 3, 10, 0, 0, 0, time.UTC) + + tests := []struct { + name string + toolUsage collector.ToolUsage + metric collector.Metric + expectedCount int + expectedError bool + expectedValues []float64 + }{ + { + name: "ai-readiness metric", + toolUsage: collector.ToolUsage{ + UserID: "user@example.com", + ToolName: "ai-readiness", + }, + metric: collector.Metric{ + UserID: "user@example.com", + ToolName: "ai-readiness", + Metrics: map[string]any{ + "repository": "org/repo1", + "organization": "testorg", + "is_ai_ready": true, + "ai_indicators_found": []string{"CLAUDE.md"}, + }, + }, + expectedCount: 1, + expectedError: false, + expectedValues: []float64{1.0}, // true converts to 1.0 + }, + { + name: "ai-readiness metric - not ready", + toolUsage: collector.ToolUsage{ + UserID: "user@example.com", + ToolName: "ai-readiness", + }, + metric: collector.Metric{ + UserID: "user@example.com", + ToolName: "ai-readiness", + Metrics: map[string]any{ + "repository": "org/repo2", + "organization": "testorg", + "is_ai_ready": false, + "ai_indicators_found": []string{}, + }, + }, + expectedCount: 1, + expectedError: false, + expectedValues: []float64{0.0}, // false converts to 0.0 + }, + { + name: "ai-readiness-summary metric", + toolUsage: collector.ToolUsage{ + UserID: "org@example.com", + ToolName: "ai-readiness-summary", + }, + metric: collector.Metric{ + UserID: "org@example.com", + ToolName: "ai-readiness-summary", + Metrics: map[string]any{ + "organization": "testorg", + "total_repos_scanned": 100, + "ai_ready_repos": 75, + "ai_readiness_percentage": 75.0, + }, + }, + expectedCount: 3, + expectedError: false, + expectedValues: []float64{100.0, 75.0, 75.0}, + }, + { + name: "invalid tool name", + toolUsage: collector.ToolUsage{ + UserID: "user@example.com", + ToolName: "invalid-tool", + }, + metric: collector.Metric{ + UserID: "user@example.com", + ToolName: "invalid-tool", + Metrics: map[string]any{}, + }, + expectedCount: 0, + expectedError: true, + }, + { + name: "ai-readiness-summary metric with special chars in org name", + toolUsage: collector.ToolUsage{ + UserID: "special-org@example.com", + ToolName: "ai-readiness-summary", + }, + metric: collector.Metric{ + UserID: "special-org@example.com", + ToolName: "ai-readiness-summary", + Metrics: map[string]any{ + "organization": "claude-code-actions", // Org name with hyphens + "total_repos_scanned": 50, + "ai_ready_repos": 25, + "ai_readiness_percentage": 50.0, + }, + }, + expectedCount: 3, + expectedError: false, + expectedValues: []float64{50.0, 25.0, 50.0}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + customMetrics, err := publisher.convertToCustomMetrics(tt.toolUsage, tt.metric, timestamp) + + if (err != nil) != tt.expectedError { + t.Errorf("convertToCustomMetrics() error = %v, expectedError %v", err, tt.expectedError) + return + } + + if err == nil { + assert.Equal(t, tt.expectedCount, len(customMetrics)) + + if len(customMetrics) > 0 && len(tt.expectedValues) > 0 { + for i, expectedValue := range tt.expectedValues { + if i < len(customMetrics) { + assert.Equal(t, expectedValue, customMetrics[i].Value) + assert.Equal(t, timestamp.Format(time.RFC3339), customMetrics[i].Timestamp) + assert.Contains(t, customMetrics[i].Metadata, "source") + assert.Equal(t, "ai-metrics-collector", customMetrics[i].Metadata["source"]) + // Verify user_id is not included + assert.NotContains(t, customMetrics[i].Metadata, "user_id") + } + } + } + } + }) + } +} + +func TestSanitizeKey(t *testing.T) { + tests := []struct { + input string + expected string + }{ + {"org/repo-name", "org_repo_name"}, + {"My-Repo.Test", "my_repo_test"}, + {"simple", "simple"}, + {"org/sub/repo-with.dots", "org_sub_repo_with_dots"}, + } + + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + result := sanitizeKey(tt.input) + assert.Equal(t, tt.expected, result) + }) + } +} + +func TestGetDXAIEnabledReposPublisher_Name(t *testing.T) { + publisher := &GetDXAIEnabledReposPublisher{} + assert.Equal(t, "getdx-ai-enabled-repos", publisher.Name()) +} diff --git a/pkg/publisher/publisher.go b/pkg/publisher/publisher.go index fec161b..f289ef1 100644 --- a/pkg/publisher/publisher.go +++ b/pkg/publisher/publisher.go @@ -33,6 +33,12 @@ func NewPublisher(cfg PublisherConfig, userList users.UsersList) (Publisher, err return nil, fmt.Errorf("failed to create publisher: %w", err) } return p, nil + case "getdx-ai-enabled-repos": + p, err := NewGetDXAIEnabledReposPublisher(cfg.Config, userList) + if err != nil { + return nil, fmt.Errorf("failed to create ai-enabled-repos getdx publisher: %w", err) + } + return p, nil default: return nil, fmt.Errorf("unknown publisher type: %s", cfg.Type) } diff --git a/pkg/users/filter.go b/pkg/users/filter.go index 5181788..54e4ca7 100644 --- a/pkg/users/filter.go +++ b/pkg/users/filter.go @@ -12,12 +12,31 @@ type UsersList interface { List() []string } +// AllowAllUserFilter allows all users - used when no user filtering is needed +type AllowAllUserFilter struct{} + +var _ UsersList = &AllowAllUserFilter{} + +func NewAllowAllUserFilter() *AllowAllUserFilter { + return &AllowAllUserFilter{} +} + +func (f *AllowAllUserFilter) Include(userID string) bool { + return true // Allow all users +} + +func (f *AllowAllUserFilter) List() []string { + return []string{} // Empty list since we allow all +} + func NewUserList(cfg UserList) (UsersList, error) { switch cfg.Type { case "static": return NewStaticUserList(cfg.Config) case "getdx": return NewGetDXUsers(cfg.Config) + case "all": + return NewAllowAllUserFilter(), nil default: return nil, fmt.Errorf("unknown filter type: %s", cfg.Type) } diff --git a/pkg/users/filter_test.go b/pkg/users/filter_test.go new file mode 100644 index 0000000..1bbebeb --- /dev/null +++ b/pkg/users/filter_test.go @@ -0,0 +1,37 @@ +package users + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestAllowAllUserFilter(t *testing.T) { + filter := NewAllowAllUserFilter() + + // Test that all users are included + assert.True(t, filter.Include("user1@example.com")) + assert.True(t, filter.Include("user2@company.org")) + assert.True(t, filter.Include("repository-name")) + assert.True(t, filter.Include("organization-name")) + assert.True(t, filter.Include("any-string-at-all")) + + // Test that List() returns empty slice (since we allow all) + list := filter.List() + assert.Empty(t, list) +} + +func TestNewUserListWithAllType(t *testing.T) { + cfg := UserList{ + Type: "all", + Config: map[string]interface{}{}, + } + + userList, err := NewUserList(cfg) + assert.NoError(t, err) + assert.NotNil(t, userList) + + // Verify it behaves like AllowAllUserFilter + assert.True(t, userList.Include("any-user")) + assert.Empty(t, userList.List()) +} diff --git a/webhook.example.yaml b/webhook.example.yaml index 156ee37..8d2f045 100644 --- a/webhook.example.yaml +++ b/webhook.example.yaml @@ -1,12 +1,21 @@ +# GitHub Webhook Configuration +# This configuration handles GitHub webhooks for real-time event tracking +# Note: Webhook authentication is independent of collector authentication methods + github: + # GitHub webhook secret for verifying webhook authenticity webhook_secret: ${env.GITHUB_WEBHOOK_SECRET} - if: ${headers["X-GitHub-Event"][0] == "pull_request" || headers["X-GitHub-Event"][0] == "pull_request_review"} + + # Pass-through configuration: Forward events to GetDX pass_thru: - if: ${method == "POST"} url: https://${env.NAMESPACE}.getdx.net/webhooks/github method: ${method} + + # DX tracking configuration dx: track_event: + # Track pull request opened events - api_key: ${env.GETDX_API_KEY} if: ${body.action == "opened"} event_name: github.pull_request.${body.action} @@ -16,4 +25,6 @@ github: repository: ${body.repository.name} pull_request: ${body.pull_request.number} pull_request_url: ${body.pull_request.html_url} - pull_request_title: ${body.pull_request.title} \ No newline at end of file + pull_request_title: ${body.pull_request.title} + organization: ${body.repository.owner.login} + repository_full_name: ${body.repository.full_name} \ No newline at end of file