diff --git a/cmd/devteam/auth.go b/cmd/devteam/auth.go new file mode 100644 index 0000000..8254628 --- /dev/null +++ b/cmd/devteam/auth.go @@ -0,0 +1,234 @@ +package main + +import ( + "bufio" + "context" + "fmt" + "io" + "os" + "strings" + + "github.com/MichielDean/devteam/internal/config" + "github.com/MichielDean/devteam/internal/db" + "github.com/MichielDean/devteam/internal/github" +) + +// startupAuthHealth runs an AuthHealthCheck at process startup (ADR-15, FR-AUTH-04). +// Used by the web server mode in main.go after db.Open. Returns nil if alive; +// the caller exits 1 with the W-1 block on error. +func startupAuthHealth(cfg *config.Config, database *db.DB, baseDir string) error { + credstore, err := github.NewCredstore(database.Conn()) + if err != nil { + return err + } + ghCfg := github.Config{ + Provider: cfg.GitHub.Provider, + AppID: cfg.GitHub.AppID, + InstallationID: cfg.GitHub.InstallationID, + PrivateKeyPath: cfg.GitHub.PrivateKeyPath, + TokenCacheTTL: cfg.GitHub.TokenCacheTTL, + PATFallbackEnabled: cfg.GitHub.PATFallback.Enabled, + ConflictPollMaxRetries: cfg.GitHub.ConflictPollMaxRetries, + ConflictPollMaxDuration: cfg.GitHub.ConflictPollMaxDuration, + BaseDir: baseDir, + Credstore: credstore, + } + client, err := github.NewNativeClient(ghCfg) + if err != nil { + return err + } + return client.AuthHealthCheck(context.Background()) +} + +// handleAuthCLI dispatches the `devteam auth ` subcommands (feature +// github-authorization-integration, interaction-spec §3.1). +// +// Verbs: +// health — probe the identity (FR-AUTH-04, US-01, M-1) +// rotate-key — rotate the App private key (NFR-SEC-03, nfr-design-specs §3.5) +// store-pat — store a PAT from stdin (FR-AUTH-02, nfr-design-specs §11 finding 6) +// +// Exit codes (interaction-spec §12 rule 2): 0 ok, 1 runtime/auth failure, +// 2 field/flag rejection. +func handleAuthCLI(args []string) { + if len(args) < 2 { + fmt.Fprintf(os.Stderr, "Usage: devteam auth [options]\n") + os.Exit(1) + } + verb := args[1] + switch verb { + case "health": + authHealth(args[2:]) + case "rotate-key": + authRotateKey(args[2:]) + case "store-pat": + authStorePAT(args[2:]) + default: + fmt.Fprintf(os.Stderr, "unknown auth verb: %s (use health, rotate-key, or store-pat)\n", verb) + os.Exit(1) + } +} + +// loadGitHubForCLI is the shared setup for auth CLI commands: loads config, +// opens the DB, constructs a credstore + NativeClient. Exits 1 on any failure +// (config error, missing master key, missing github: block) with the W-10 +// block format (interaction-spec §3.1, NFR-OPS-01). +func loadGitHubForCLI() (*config.Config, *db.DB, *github.Credstore, *github.NativeClient) { + baseDir, err := os.Getwd() + if err != nil { + printAuthError(nil, fmt.Errorf("getting working directory: %w", err)) + os.Exit(1) + } + cfg, err := config.LoadConfig(baseDir + "/devteam.yaml") + if err != nil { + printAuthError(nil, fmt.Errorf("loading config: %w", err)) + os.Exit(1) + } + if cfg.GitHub.AppID == 0 && cfg.GitHub.Provider == "" { + printAuthError(nil, fmt.Errorf("github: config block not present; see docs/github-app-setup.md §5")) + os.Exit(1) + } + database := openDB(baseDir) + credstore, err := github.NewCredstore(database.Conn()) + if err != nil { + printAuthError(nil, err) + os.Exit(1) + } + ghCfg := github.Config{ + Provider: cfg.GitHub.Provider, + AppID: cfg.GitHub.AppID, + InstallationID: cfg.GitHub.InstallationID, + PrivateKeyPath: cfg.GitHub.PrivateKeyPath, + TokenCacheTTL: cfg.GitHub.TokenCacheTTL, + PATFallbackEnabled: cfg.GitHub.PATFallback.Enabled, + ConflictPollMaxRetries: cfg.GitHub.ConflictPollMaxRetries, + ConflictPollMaxDuration: cfg.GitHub.ConflictPollMaxDuration, + BaseDir: baseDir, + Credstore: credstore, + } + client, err := github.NewNativeClient(ghCfg) + if err != nil { + printAuthError(nil, err) + os.Exit(1) + } + return cfg, database, credstore, client +} + +// printAuthError prints the W-10 failure block (interaction-spec §3.1, §9.3): +// ✗ + the error, then a numbered `what to do:` block. For *AuthError, the +// runbook section is already in the error string; for other errors, we add a +// generic pointer. +func printAuthError(_ *github.AuthError, err error) { + if err == nil { + return + } + fmt.Fprintf(os.Stderr, "✗ %s\n", err.Error()) + if ae, ok := github.IsAuthError(err); ok { + fmt.Fprintf(os.Stderr, "what to do:\n") + fmt.Fprintf(os.Stderr, " 1. see docs/github-app-setup.md %s\n", ae.RunbookSection) + fmt.Fprintf(os.Stderr, " 2. fix the issue described above\n") + fmt.Fprintf(os.Stderr, " 3. re-run: devteam auth health\n") + } else { + fmt.Fprintf(os.Stderr, "what to do:\n") + fmt.Fprintf(os.Stderr, " 1. see docs/github-app-setup.md\n") + fmt.Fprintf(os.Stderr, " 2. re-run: devteam auth health\n") + } +} + +// authHealth implements `devteam auth health` (M-1, US-01). +func authHealth(_ []string) { + _, database, _, client := loadGitHubForCLI() + defer database.Close() + + ctx := context.Background() + if err := client.AuthHealthCheck(ctx); err != nil { + printAuthError(nil, err) + os.Exit(1) + } + // Provenance (US-01 criterion 1, interaction-spec §8.1). + prov, _ := client.TokenProvenance(ctx) + if prov == "" { + prov = "cached" + } + fmt.Printf("✓ machine identity alive\n") + fmt.Printf(" token source: %s\n", prov) + fmt.Printf(" app_id: %d\n", client.AppID()) + fmt.Printf(" installation_id: %d\n", client.InstallationID()) +} + +// authRotateKey implements `devteam auth rotate-key` (NFR-SEC-03, nfr-design-specs §3.5). +// Reads the new key from the configured private_key_path, stores it (marking +// the old row rotated), emits a CREDENTIAL_ROTATED audit event, all in one tx. +func authRotateKey(_ []string) { + cfg, database, credstore, client := loadGitHubForCLI() + defer database.Close() + + pemBytes, err := os.ReadFile(cfg.GitHub.PrivateKeyPath) + if err != nil { + printAuthError(nil, fmt.Errorf("reading new key from %s: %w", cfg.GitHub.PrivateKeyPath, err)) + os.Exit(1) + } + oldFp := "" + if oldKey, err := credstore.LoadAppPrivateKey(); err == nil { + oldFp = github.Fingerprint(oldKey) + } + if err := credstore.StoreAppPrivateKey(pemBytes); err != nil { + printAuthError(nil, fmt.Errorf("storing new key: %w", err)) + os.Exit(1) + } + newFp := github.Fingerprint(pemBytes) + _ = client // touched so the client construction side-effects (cache init) happen + details := fmt.Sprintf(`{"actor":"%s","action":"rotate","target":"app_private_key","old_fingerprint":"%s","new_fingerprint":"%s"}`, os.Getenv("USER"), oldFp, newFp) + if err := database.RecordCredentialAuditEvent("", db.AuditCredentialRotated, "", "auth", details); err != nil { + fmt.Fprintf(os.Stderr, "⚠ key rotated but audit event failed: %v\n", err) + } + fmt.Printf("✓ app private key rotated\n") + fmt.Printf(" fingerprint: %s…\n", newFp[:4]) + if oldFp != "" { + fmt.Printf(" old fingerprint: %s… (superseded)\n", oldFp[:4]) + } + fmt.Printf(" no restart required — next JWT mint uses the new key\n") +} + +// authStorePAT implements `devteam auth store-pat` (FR-AUTH-02, nfr-design-specs +// §11 finding 6). Reads the PAT from stdin (never arg, never env — avoids shell +// history leakage). Stores encrypted; emits CREDENTIAL_STORED audit. +func authStorePAT(_ []string) { + _, database, credstore, _ := loadGitHubForCLI() + defer database.Close() + + fmt.Fprintf(os.Stderr, "Paste PAT (read from stdin; ends on blank line or EOF):\n") + reader := bufio.NewReader(os.Stdin) + var lines []string + for { + line, err := reader.ReadString('\n') + line = strings.TrimRight(line, "\n") + if line != "" { + lines = append(lines, line) + } + if err == io.EOF { + break + } + if err != nil { + printAuthError(nil, fmt.Errorf("reading PAT from stdin: %w", err)) + os.Exit(1) + } + if line == "" { + break + } + } + pat := strings.Join(lines, "") + if pat == "" { + fmt.Fprintf(os.Stderr, "✗ no PAT read from stdin\n") + os.Exit(1) + } + if err := credstore.StorePAT(pat); err != nil { + printAuthError(nil, fmt.Errorf("storing PAT: %w", err)) + os.Exit(1) + } + fp := github.Fingerprint([]byte(pat)) + details := fmt.Sprintf(`{"actor":"%s","action":"store","target":"pat","fingerprint":"%s"}`, os.Getenv("USER"), fp) + _ = database.RecordCredentialAuditEvent("", db.AuditCredentialStored, "", "auth", details) + fmt.Printf("✓ PAT stored\n") + fmt.Printf(" fingerprint: %s…\n", fp[:4]) +} \ No newline at end of file diff --git a/cmd/devteam/main.go b/cmd/devteam/main.go index 36dbca1..37710af 100644 --- a/cmd/devteam/main.go +++ b/cmd/devteam/main.go @@ -88,6 +88,19 @@ func main() { os.Exit(1) } + // Auth-health check at startup (feature github-authorization-integration, + // ADR-15, FR-AUTH-04). If the github: config block is present, verify the + // identity is alive before serving. Failure exits 1 with the W-1 block. + // If the block is absent, this is a no-op (pre-feature behavior preserved). + if cfg.GitHub.AppID != 0 || cfg.GitHub.Provider != "" { + if err := startupAuthHealth(cfg, database, baseDir); err != nil { + fmt.Fprintf(os.Stderr, "✗ startup auth-health check failed: %v\n", err) + fmt.Fprintf(os.Stderr, " see docs/github-app-setup.md\n") + os.Exit(1) + } + fmt.Printf("[auth] ✓ machine identity alive at startup\n") + } + // Wire database and DB question store into pipeline questionStore := feature.NewDBQuestionStore(database) p.SetDatabase(database) @@ -155,6 +168,12 @@ func main() { case "init": handleInit() return + case "auth": + handleAuthCLI(os.Args[1:]) + return + case "repo": + handleRepoCLI(os.Args[1:]) + return case "questions": if len(os.Args) < 4 { fmt.Fprintf(os.Stderr, "Usage: devteam questions [options]\n") diff --git a/cmd/devteam/repo.go b/cmd/devteam/repo.go new file mode 100644 index 0000000..d2833ef --- /dev/null +++ b/cmd/devteam/repo.go @@ -0,0 +1,307 @@ +package main + +import ( + "context" + "fmt" + "os" + "strings" + + "github.com/MichielDean/devteam/internal/config" + "github.com/MichielDean/devteam/internal/db" +) + +// handleRepoCLI dispatches `devteam repo ` (feature github-authorization-integration, +// interaction-spec §3.2..§3.4). +// +// Verbs: +// list — render MANAGED + AVAILABLE-BUT-UNMANAGED groups (M-2, US-03) +// set — write one MVP field (M-3, US-06, FR-SETTINGS-04) +// manage — transition a discovered repo to managed (M-4, US-16, FR-DISC-06) +// +// Exit codes (interaction-spec §12 rule 2): 0 ok, 1 runtime/auth failure, +// 2 field/flag rejection. +func handleRepoCLI(args []string) { + if len(args) < 2 { + fmt.Fprintf(os.Stderr, "Usage: devteam repo [options]\n") + os.Exit(1) + } + verb := args[1] + switch verb { + case "list": + repoList(args[2:]) + case "set": + repoSet(args[2:]) + case "manage": + repoManage(args[2:]) + default: + fmt.Fprintf(os.Stderr, "unknown repo verb: %s (use list, set, or manage)\n", verb) + os.Exit(1) + } +} + +// openRepoDB opens the DB for repo CLI commands. +func openRepoDB() *db.DB { + baseDir, err := os.Getwd() + if err != nil { + fmt.Fprintf(os.Stderr, "error getting working directory: %v\n", err) + os.Exit(1) + } + return openDB(baseDir) +} + +// repoList implements `devteam repo list` (M-2, US-03, interaction-spec §3.2). +func repoList(args []string) { + asJSON := false + noPager := false + for _, a := range args { + switch a { + case "--json": + asJSON = true + case "--no-pager": + noPager = true + case "--help", "-h": + fmt.Println("Usage: devteam repo list [--json] [--no-pager]") + return + } + } + _ = noPager + + database := openRepoDB() + defer database.Close() + + // If the github: block is configured, run discovery first to refresh the + // registry (FR-DISC-01). If not, list whatever's in repo_registry. + cfg, _ := loadConfig() + if cfg != nil && cfg.GitHub.AppID != 0 { + // Auth-health precondition (interaction-spec §3.2). + _, _, _, client := loadGitHubForCLI() + repos, err := client.ListRepositories(context.Background()) + if err != nil { + printAuthError(nil, err) + os.Exit(1) + } + // Persist discovered set (FR-DISC-02). + for _, r := range repos { + _, _, _ = database.UpsertRepoRegistry(r.Ref.Owner, r.Ref.Name, r.Ref.Owner+"/"+r.Ref.Name, r.DefaultBranch, r.InstallationID) + } + _ = database.RecordRepoRegistryAudit("", fmt.Sprintf("discovery synced %d repos", len(repos))) + } + + rows, err := database.ListRepoRegistry(nil) + if err != nil { + fmt.Fprintf(os.Stderr, "error listing repo_registry: %v\n", err) + os.Exit(1) + } + + var managed, unmanaged []db.RepoRegistryRow + for _, r := range rows { + if r.Managed == 1 { + managed = append(managed, r) + } else { + unmanaged = append(unmanaged, r) + } + } + + if asJSON { + printRepoListJSON(managed, unmanaged) + return + } + printRepoListText(managed, unmanaged) +} + +func printRepoListText(managed, unmanaged []db.RepoRegistryRow) { + fmt.Printf("MANAGED (%d)\n", len(managed)) + if len(managed) == 0 { + fmt.Println(" (none — devteam repo manage to begin)") + } + for _, r := range managed { + fmt.Printf(" %s/%s (default: %s)\n", r.Owner, r.Name, r.DefaultBranch) + } + fmt.Printf("\navailable-but-unmanaged (%d)\n", len(unmanaged)) + if len(unmanaged) == 0 { + fmt.Println(" (none)") + } + for _, r := range unmanaged { + fmt.Printf(" %s/%s\n", r.Owner, r.Name) + } +} + +func printRepoListJSON(managed, unmanaged []db.RepoRegistryRow) { + fmt.Printf("[") + first := true + emit := func(r db.RepoRegistryRow, managed bool) { + if !first { + fmt.Printf(",") + } + first = false + fmt.Printf(`{"name":"%s/%s","default_branch":"%s","managed":%t}`, r.Owner, r.Name, r.DefaultBranch, managed) + } + for _, r := range managed { + emit(r, true) + } + for _, r := range unmanaged { + emit(r, false) + } + fmt.Printf("]\n") +} + +// repoSet implements `devteam repo set =` (M-3, US-06, +// FR-SETTINGS-04, interaction-spec §3.3). +func repoSet(args []string) { + dryRun := false + confirm := false + var positional []string + for _, a := range args { + switch a { + case "--dry-run": + dryRun = true + case "--confirm": + confirm = true + case "--help", "-h": + fmt.Println("Usage: devteam repo set = [--dry-run] [--confirm]") + fmt.Println("MVP fields: default_branch, pr_draft_default, conflict_detection_enabled, provider") + return + default: + positional = append(positional, a) + } + } + if len(positional) < 2 { + fmt.Fprintf(os.Stderr, "Usage: devteam repo set = [--dry-run] [--confirm]\n") + fmt.Fprintf(os.Stderr, "MVP fields: %s\n", strings.Join(db.MVPRepoSettingsFields, ", ")) + os.Exit(1) + } + repoArg := positional[0] + kv := positional[1] + parts := strings.SplitN(kv, "=", 2) + if len(parts) != 2 { + fmt.Fprintf(os.Stderr, "✗ invalid argument %q: expected =\n", kv) + os.Exit(2) + } + key := parts[0] + value := parts[1] + + // Field validation (FR-SETTINGS-03, R-08, US-06 criteria 3-4). + if !contains(db.MVPRepoSettingsFields, key) { + if contains(db.Phase2RepoSettingsFields, key) { + fmt.Fprintf(os.Stderr, "✗ %q is not supported in MVP\n", key) + fmt.Fprintf(os.Stderr, " supported: %s\n", strings.Join(db.MVPRepoSettingsFields, ", ")) + fmt.Fprintf(os.Stderr, " to add it, open a scope-change request (see docs/github-app-setup.md)\n") + } else { + fmt.Fprintf(os.Stderr, "✗ unknown field %q; supported: %s\n", key, strings.Join(db.MVPRepoSettingsFields, ", ")) + } + os.Exit(2) + } + + database := openRepoDB() + defer database.Close() + + owner, name := splitRepoArg(repoArg) + row, err := database.GetRepoRegistry(owner, name) + if err != nil { + fmt.Fprintf(os.Stderr, "✗ repo %s not in registry: %v\n", repoArg, err) + fmt.Fprintf(os.Stderr, " run: devteam repo manage %s\n", repoArg) + os.Exit(1) + } + if row.Managed != 1 { + fmt.Fprintf(os.Stderr, "✗ %s is not managed; run: devteam repo manage %s\n", repoArg, repoArg) + os.Exit(1) + } + + if dryRun { + fmt.Printf("ℹ dry-run: would set %s.%s = %s\n", repoArg, key, value) + return + } + + // Destructive-class confirmation (interaction-spec §3.3, §11.1): + // changes default_branch OR sets provider=gh. + if (key == "default_branch" || (key == "provider" && value == "gh")) && !confirm { + if !confirmPrompt(fmt.Sprintf("⚠ %s.%s = %s is destructive-class; proceed?", repoArg, key, value)) { + fmt.Fprintf(os.Stderr, "aborted\n") + os.Exit(1) + } + } + + if _, err := database.UpsertRepoSettings(row.ID, key, value); err != nil { + fmt.Fprintf(os.Stderr, "✗ setting %s: %v\n", key, err) + os.Exit(1) + } + + // Audit (FR-AUDIT-03). details carries field names + redacted values. + details := fmt.Sprintf(`{"actor":"%s","repo":"%s","diff":{%q:%q}}`, os.Getenv("USER"), repoArg, key, value) + _ = database.RecordRepoSettingsAudit("", repoArg, details) + + fmt.Printf("✓ %s: %s = %s\n", repoArg, key, value) +} + +// repoManage implements `devteam repo manage ` (M-4, US-16, FR-DISC-06). +func repoManage(args []string) { + dryRun := false + var repoArg string + for _, a := range args { + switch a { + case "--dry-run": + dryRun = true + case "--help", "-h": + fmt.Println("Usage: devteam repo manage [--dry-run]") + return + default: + repoArg = a + } + } + if repoArg == "" { + fmt.Fprintf(os.Stderr, "Usage: devteam repo manage [--dry-run]\n") + os.Exit(1) + } + database := openRepoDB() + defer database.Close() + + owner, name := splitRepoArg(repoArg) + if dryRun { + fmt.Printf("ℹ dry-run: would manage %s with default settings\n", repoArg) + return + } + if err := database.SetRepoManaged(owner, name, 1); err != nil { + fmt.Fprintf(os.Stderr, "✗ %v\n", err) + fmt.Fprintf(os.Stderr, " is the repo discovered? run: devteam repo list\n") + os.Exit(1) + } + _ = database.RecordRepoRegistryAudit("", fmt.Sprintf("managed %s", repoArg)) + fmt.Printf("✓ %s managed\n", repoArg) + fmt.Printf(" next: devteam repo set %s default_branch=\n", repoArg) +} + +// loadConfig loads devteam.yaml from cwd (best-effort for repo list). +func loadConfig() (*config.Config, error) { + baseDir, err := os.Getwd() + if err != nil { + return nil, err + } + return config.LoadConfig(baseDir + "/devteam.yaml") +} + +// splitRepoArg splits "owner/name" into (owner, name). +func splitRepoArg(s string) (string, string) { + parts := strings.SplitN(s, "/", 2) + if len(parts) != 2 { + return "", s + } + return parts[0], parts[1] +} + +// confirmPrompt prints the prompt and reads y/N from stdin (default N, +// interaction-spec §11.1). +func confirmPrompt(prompt string) bool { + fmt.Fprintf(os.Stderr, "%s [y/N]: ", prompt) + var resp string + fmt.Fscanln(os.Stdin, &resp) + return strings.ToLower(strings.TrimSpace(resp)) == "y" +} + +func contains(s []string, v string) bool { + for _, x := range s { + if x == v { + return true + } + } + return false +} \ No newline at end of file diff --git a/docs/github-app-setup.md b/docs/github-app-setup.md new file mode 100644 index 0000000..52216c0 --- /dev/null +++ b/docs/github-app-setup.md @@ -0,0 +1,350 @@ +# GitHub App Setup Runbook + +**Feature**: github-authorization-integration +**Stage**: U-12 / FR-RUNBOOK-01/02 +**Audience**: operator (P-1) + onboarding operator (P-2) + +This is the **sole setup mechanism** for the GitHub App authorization feature (NFR-OPS-02, C-13). No code path automates App creation + org install + key placement. Follow it linearly; each section ends with a checkable outcome. + +--- + +## §1 Prerequisites + +Confirm each before starting: + +- [ ] GitHub account with admin access to the `MichielDean` org. +- [ ] The `devteam` binary built and on PATH (or invokable as `./devteam`). +- [ ] Postgres running on `localhost:5432` with the `devteam` DB (existing — reused, not added by this feature). +- [ ] A text editor for `devteam.yaml` and `devteam.env`. + +**Checkable outcome**: `devteam version` prints `devteam 0.4.0`; `psql -h localhost -U devteam -d devteam -c "SELECT 1"` returns `1`. + +Continue to §2. + +--- + +## §2 App manifest creation + +Create the GitHub App in the org: + +1. Go to **GitHub → Settings → Developer settings → GitHub Apps → New GitHub App** (under the `MichielDean` org, not your personal account). +2. **GitHub App name**: `devteam` (or `devteam-prod` if you want to distinguish environments). +3. **Homepage URL**: `https://github.com/MichielDean/devteam`. +4. **Webhook**: **Disable webhooks** — uncheck "Active" (this feature does NOT add a webhook receiver; C-08, scope §5). +5. **Repository permissions**: + - **Contents**: Read-only (for branch/SHA resolution, FR-PR-01). + - **Metadata**: Read-only (always required). + - **Pull requests**: Read & write (for CreatePR/ReadyPR/CommentPR, FR-PR-02..04). + - **Administration**: Read-only (for repo discovery). + - Do NOT grant wildcard `repo/*` — least privilege (scope §3, infra-specs §2.2). +6. **Account permissions**: none (the App acts as a machine identity, not a user). +7. **Create GitHub App**. +8. **Note the App ID**: on the App's general settings page, find "App ID" (an integer like `123456`). You'll put it in `devteam.yaml` as `github.app_id`. +9. **Generate a private key**: scroll down to "Private keys" → **Generate a private key**. A `.pem` file downloads. This is the App private key (NOT a PAT, NOT the master key). + +**Checkable outcome**: you have an App ID (integer) and a downloaded `.pem` file. + +Continue to §3. + +--- + +## §3 Master key + App key placement + +The feature uses two distinct keys — do not confuse them: + +| Key | Purpose | Where it lives | Env var | +|-----|---------|----------------|---------| +| **Master key** (32 bytes raw) | Encrypts all credentials at rest (AES-256-GCM) | `/etc/devteam/master.key` | `DEVTEAM_MASTER_KEY_FILE` | +| **App private key** (PEM) | Signs JWTs to authenticate as the GitHub App | `/etc/devteam/github-app.private-key.pem` | `github.private_key_path` in `devteam.yaml` | + +The master key NEVER goes in `devteam.yaml` or the DB (C-04, FR-CRED-01). The App key NEVER goes in the DB plaintext (it's encrypted with the master key). + +### 3.1 Create the custody directory + +```sh +mkdir -p /etc/devteam +chmod 0700 /etc/devteam +``` + +**Checkable outcome**: `ls -ld /etc/devteam` shows `drwx------` owned by you. + +### 3.2 Generate the master key + +```sh +head -c 32 /dev/urandom > /etc/devteam/master.key +chmod 0400 /etc/devteam/master.key +``` + +The file must be **exactly 32 bytes**. A trailing newline (33 bytes) is rejected at load with `ErrKeyFileInvalid` — if you accidentally add one, `truncate -s 32 /etc/devteam/master.key`. + +**Checkable outcome**: `wc -c /etc/devteam/master.key` prints `32`. + +### 3.3 Place the App private key + +Copy the `.pem` file you downloaded in §2 to the custody directory: + +```sh +cp ~/Downloads/devteam-private-key-*.pem /etc/devteam/github-app.private-key.pem +chmod 0400 /etc/devteam/github-app.private-key.pem +``` + +**Checkable outcome**: `ls -l /etc/devteam/github-app.private-key.pem` shows `-r--------` and the file contains `-----BEGIN RSA PRIVATE KEY-----`. + +### 3.4 Set the master key env var + +Add to `devteam.env` (the file the systemd unit reads via `EnvironmentFile=`): + +```sh +DEVTEAM_MASTER_KEY_FILE=/etc/devteam/master.key +``` + +**No `daemon-reload` is required** — the unit file itself is unchanged; only the env file gains a line, and `EnvironmentFile=` is re-read at every restart (infra-specs §6.1, finding 3). + +**Checkable outcome**: `grep DEVTEAM_MASTER_KEY_FILE devteam.env` prints the line. + +Continue to §4. + +--- + +## §4 App installation on the `MichielDean` org + +Install the App on the org so it can access repos: + +1. Go to **GitHub → Settings → Developer settings → GitHub Apps → [your App] → Install App**. +2. Choose **`MichielDean`** (the org). +3. **Repository access**: select **Only select repositories** and pick the repos you want devteam to manage (least privilege — do NOT grant all repos unless you mean it). +4. **Install**. +5. **Note the installation ID**: after install, the URL will be `https://github.com/organizations/MichielDean/settings/installations/{INSTALLATION_ID}`. The number in the URL is the installation ID. Alternatively, `curl -H "Authorization: Bearer " https://api.github.com/app/installations` lists installations with their IDs. + +**Checkable outcome**: you have an installation ID (integer). + +Continue to §5. + +--- + +## §5 `devteam.yaml` configuration + +Add the `github:` block to `devteam.yaml`: + +```yaml +github: + provider: native # 'native' (default, go-github) | 'gh' (fallback adapter) + app_id: + installation_id: + private_key_path: /etc/devteam/github-app.private-key.pem + token_cache_ttl: 9m # < 60m (GitHub's installation-token lifetime); default 9m + pat_fallback: + enabled: false # set true after §8 (PAT fallback setup) + conflict_poll_max_retries: 5 # NFR-PERF-02; default 5, hard ceiling 10 + conflict_poll_max_duration: 60s # NFR-PERF-02; default 60s, hard ceiling 300s +``` + +Validation at load (interaction-spec §4.1): missing `app_id`/`installation_id`/`private_key_path` fails fast with exit 1 and a pointer to this section. `token_cache_ttl >= 60m` fails with `"must be < 60m (GitHub limit)"`. + +**Checkable outcome**: `devteam auth health` (next section) loads config without error. + +Continue to §6. + +--- + +## §6 First-run verification + +```sh +devteam auth health +``` + +Expected success (M-1, interaction-spec §3.1): + +``` +✓ machine identity alive + token source: refreshed + app_id: + installation_id: +``` + +Then verify repo discovery: + +```sh +devteam repo list +``` + +Expected (M-2): a MANAGED group (empty initially) and an available-but-unmanaged group listing the repos the App installation can access. + +**Checkable outcome**: `devteam auth health` exits 0; `devteam repo list` shows discovered repos. + +If either fails, go to §11 (Troubleshooting, symptom-indexed). + +Continue to §7 for key management. + +--- + +## §7 Key management + +### §7.1 App private-key rotation (NFR-SEC-03) + +Rotation is a data operation — no code change, no process restart (ADR-10): + +1. Go to **GitHub → Settings → Developer settings → GitHub Apps → [your App] → Private keys → Generate a new private key**. A new `.pem` downloads. +2. Replace the file at the configured path: + ```sh + cp ~/Downloads/devteam-private-key-*.pem /etc/devteam/github-app.private-key.pem + chmod 0400 /etc/devteam/github-app.private-key.pem + ``` +3. Run the rotation command: + ```sh + devteam auth rotate-key + ``` + This stores the new key (encrypting with the master key), marks the old key rotated, and emits a `CREDENTIAL_ROTATED` audit event — all in one transaction. +4. **No restart required**: the next JWT mint reads the new key from the credstore on-demand (ADR-10). The current in-process token cache is unaffected; it stays valid until its TTL, then refreshes using the new key. + +**Checkable outcome**: `devteam auth rotate-key` prints `✓ app private key rotated` with a fingerprint; `devteam auth health` still succeeds. + +### §7.2 Master key backup + +The master key is the **load-bearing backup** — the `credentials` ciphertext is inert without it (infra-specs §5.1, finding 2). Back it up once at first setup: + +```sh +cp /etc/devteam/master.key +``` + +Acceptable locations: encrypted USB, password-manager attachment, off-site backup. The backup is **your responsibility** — the system does NOT automate backup (automating backup = creating a second attack surface, NFR-SEC-02). + +**Checkable outcome**: a second copy of `master.key` exists outside `/etc/devteam/`. + +### §7.3 Master key loss (recovery) + +If `master.key` is lost, **ALL stored credentials are unrecoverable** (NFR-SEC-02). There is no escrow, no KDF-from-password. Recovery: + +1. Re-generate the master key (§3.2). +2. Rotate the App private key on GitHub (§7.1 step 1) and place the new `.pem` at the configured path. +3. Run `devteam auth rotate-key` to store the new App key (encrypted with the new master key). +4. If you used a PAT (§8), re-store it via `devteam auth store-pat`. +5. `devteam auth health` should now succeed. + +**Checkable outcome**: `devteam auth health` ✓ after the recovery sequence. + +### §7.4 Master key compromise (re-encryption) + +If the master key is suspected compromised, rotate it by re-encrypting all `credentials` rows: + +1. Generate a new master key (§3.2) and place it at `DEVTEAM_MASTER_KEY_FILE`. +2. For each active credential row, decrypt with the OLD key and re-encrypt with the NEW key. This is a documented runbook operation (SQL + Go snippet), executed as a one-off — NOT an automated CLI command in MVP's surface. +3. Emit a `CREDENTIAL_ROTATED` audit event with `details="master_key_rotated"` (no values). + +**Checkable outcome**: `devteam auth health` ✓ with the new master key; `audit_events` shows the `CREDENTIAL_ROTATED` row. + +Continue to §8 if you want PAT fallback (optional); else §9. + +--- + +## §8 PAT fallback setup (optional) + +PAT fallback (FR-AUTH-02) keeps the pipeline moving when the App token exchange fails transiently (network, 401, 5xx). It does NOT engage on 404/403 (revoked/suspended installations surface loudly — ADR-09). + +1. Create a PAT on GitHub: **Settings → Developer settings → Personal access tokens → Fine-grained tokens → Generate new token**. Scope it to the same repos the App manages; grant `Contents: Read`, `Pull requests: Read & write`. +2. Enable PAT fallback in `devteam.yaml`: + ```yaml + github: + pat_fallback: + enabled: true + ``` +3. Store the PAT (read from stdin — never arg, never env, to avoid shell-history leakage): + ```sh + devteam auth store-pat + # paste the PAT, press Enter, then Ctrl-D (or blank line) + ``` + This encrypts the PAT with the master key and emits a `CREDENTIAL_STORED` audit event. +4. Verify: temporarily revoke the App installation on GitHub, then `devteam auth health`. It should print `⚠ machine identity alive (degraded)` with `token source: fallback (PAT)`. Re-enable the App installation afterward. + +**Checkable outcome**: `devteam auth health` shows `fallback (PAT)` when the primary identity fails. + +Continue to §9. + +--- + +## §9 App-key rejection troubleshooting + +**Symptom**: `devteam auth health` prints: +``` +✗ key_rejected: app private key rejected (401) (see docs/github-app-setup.md §9) +``` + +**Cause**: the App private key at `github.private_key_path` was rejected by GitHub (401 from token exchange). The key may have been rotated on GitHub but the local file not updated. + +**Fix**: +1. Rotate the key on GitHub (§7.1 step 1) — or re-download the existing key if you lost the file. +2. Place the new `.pem` at the configured path (§3.3). +3. `devteam auth rotate-key` to store the new key. +4. Re-run: `devteam auth health` (expect ✓). + +**Checkable outcome**: `devteam auth health` ✓. + +--- + +## §10 Installation revoked/suspended + +**Symptom**: `devteam auth health` prints: +``` +✗ installation_not_found: installation #N not reachable: 404 (see docs/github-app-setup.md §10) +``` +or +``` +✗ installation_suspended: installation #N suspended by org admin (see docs/github-app-setup.md §10) +``` + +**Cause**: the App installation was revoked (404) or suspended (403) by an org admin. PAT fallback is NOT engaged — this is not a transient failure (ADR-09). + +**Fix**: +1. Re-install the App on the org (§4) — or ask the org admin to re-enable it. +2. Update `installation_id` in `devteam.yaml` if it changed (a new installation has a new ID). +3. Re-run: `devteam auth health` (expect ✓). + +**Checkable outcome**: `devteam auth health` ✓. + +--- + +## §11 `gh` CLI fallback troubleshooting + +**Symptom**: `devteam auth health` prints: +``` +✗ gh_cli_not_found: provider: gh requires the gh CLI on PATH (see docs/github-app-setup.md §11) +``` + +**Cause**: `github.provider: gh` is set in `devteam.yaml` but the `gh` binary is not on `$PATH` (NFR-PORT-03). + +**Fix** — one of: +1. Install `gh`: see https://github.com/cli/cli#installation, then `gh auth login`. +2. Switch to native: set `github.provider: native` in `devteam.yaml` (the default and the recommended end-state — `gh` is no longer a hard runtime dependency post-feature, C-05). + +**Checkable outcome**: `devteam auth health` ✓. + +--- + +## §12 Uninstall/recovery + +To remove the feature's footprint (does NOT uninstall Postgres or the binary — those are shared): + +1. **Uninstall the App** on GitHub: **Settings → Developer settings → GitHub Apps → [your App] → Advanced → Uninstall** (or the org's installed-apps settings). +2. **Delete the `credentials` rows** (they're now inert anyway — the App is gone): + ```sh + psql -h localhost -U devteam -d devteam -c "DELETE FROM credentials;" + ``` +3. **Rotate the master key** (§7.4) or delete it: + ```sh + rm /etc/devteam/master.key /etc/devteam/github-app.private-key.pem + rmdir /etc/devteam + ``` +4. **Remove the `github:` block** from `devteam.yaml` and the `DEVTEAM_MASTER_KEY_FILE` line from `devteam.env`. + +**Checkable outcome**: `devteam auth health` fails with a config error (block absent); `psql ... -c "SELECT count(*) FROM credentials"` returns `0`. + +--- + +## Notes + +- **No automated install**: there is no `devteam auth setup` command that creates the App or installs it on the org. This runbook is the sole setup mechanism (NFR-OPS-02, C-13). A static check greps `internal/` for any function calling GitHub's App-creation endpoints → zero hits. +- **Key loss is unrecoverable**: the master key has no escrow. Your backup (§7.2) is the recovery mechanism. +- **`gh` stays installed**: `provider: native` makes `gh` optional, but `provider: gh` fallback still uses it. Uninstalling `gh` is a follow-up, not a feature deliverable (infra-specs §6.3). +- **Windows ACL**: `os.Chmod(0400)` is a no-op on Windows; the master key file's ACL is your responsibility (NFR-PORT-01, infra-specs §3.2). The system does NOT attempt programmatic ACL management. + +*End of runbook.* \ No newline at end of file diff --git a/go.mod b/go.mod index 09b5bd3..d78132f 100644 --- a/go.mod +++ b/go.mod @@ -4,4 +4,11 @@ go 1.26.1 require gopkg.in/yaml.v3 v3.0.1 -require github.com/lib/pq v1.12.3 +require ( + github.com/golang-jwt/jwt/v5 v5.3.1 + github.com/google/go-github/v66 v66.0.0 + github.com/lib/pq v1.12.3 + golang.org/x/oauth2 v0.36.0 +) + +require github.com/google/go-querystring v1.1.0 // indirect diff --git a/go.sum b/go.sum index 5dc2941..c026a0b 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,17 @@ +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/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-github/v66 v66.0.0 h1:ADJsaXj9UotwdgK8/iFZtv7MLc8E8WBl62WLd/D/9+M= +github.com/google/go-github/v66 v66.0.0/go.mod h1:+4SO9Zkuyf8ytMj0csN1NR/5OTR+MfqPp8P8dVlcvY4= +github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= +github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ= github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/internal/config/config.go b/internal/config/config.go index 12a9ffa..9c6b207 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,6 +3,7 @@ package config import ( "fmt" "os" + "time" "gopkg.in/yaml.v3" ) @@ -18,7 +19,7 @@ type Config struct { Pipeline PipelineConfig `yaml:"pipeline"` Roles map[string]RoleConfig `yaml:"roles"` Extensions map[string]ExtensionConfig `yaml:"extensions"` - Plugins map[string]PluginConfig `yaml:"plugins"` + Plugins map[string]PluginConfig `yaml:"plugins"` Intake IntakeConfig `yaml:"intake"` SpecRepo SpecRepoConfig `yaml:"spec_repo"` Database DatabaseConfig `yaml:"database"` @@ -30,6 +31,27 @@ type Config struct { Expert ExpertConfig `yaml:"expert"` // Chat — chat-surface settings. Trust mode is Should-after-MVS. Chat ChatConfig `yaml:"chat"` + GitHub GitHubConfig `yaml:"github"` +} + +// GitHubConfig configures native GitHub App authorization (feature +// github-authorization-integration). Empty/zero value = feature not configured; +// construction of a GitHubClient from this block is gated by the caller (the +// block is optional and ignored if absent, preserving pre-feature behavior). +type GitHubConfig struct { + Provider string `yaml:"provider"` // "native" (default) | "gh" (fallback adapter). Empty → "native". + AppID int64 `yaml:"app_id"` // GitHub App ID (from App settings page) + InstallationID int64 `yaml:"installation_id"` // App installation ID (from installation URL/API) + PrivateKeyPath string `yaml:"private_key_path"` // env/config-pointed App private key PEM path (NOT the master key) + TokenCacheTTL time.Duration `yaml:"token_cache_ttl"` // < GitHub's 60m installation-token lifetime; default 9m + PATFallback PATFallbackConfig `yaml:"pat_fallback"` + ConflictPollMaxRetries int `yaml:"conflict_poll_max_retries"` // NFR-PERF-02; default 5, hard ceiling 10 + ConflictPollMaxDuration time.Duration `yaml:"conflict_poll_max_duration"` // NFR-PERF-02; default 60s, hard ceiling 300s +} + +// PATFallbackConfig configures the PAT fallback auth path (FR-AUTH-02, ADR-09). +type PATFallbackConfig struct { + Enabled bool `yaml:"enabled"` // default false; PAT stored via `devteam auth store-pat` (stdin) } // DatabaseConfig configures the PostgreSQL database connection. @@ -238,5 +260,71 @@ func validateConfig(cfg *Config) error { if cfg.Pipeline.Streaming.RenderCapLines < 0 { return fmt.Errorf("streaming.render_cap_lines must be >= 0 (0 = use default 5000), got %d", cfg.Pipeline.Streaming.RenderCapLines) } + + // GitHub authorization block validation (feature github-authorization-integration). + // The block is OPTIONAL: a zero-value GitHubConfig (AppID == 0, Provider == "") + // means the feature is not configured and construction of a GitHubClient is + // the caller's responsibility (the pipeline skips auth-health when the block + // is absent, preserving pre-feature behavior — NFR-COMPAT-03). + if cfg.GitHub.AppID != 0 || cfg.GitHub.Provider != "" || cfg.GitHub.PrivateKeyPath != "" { + if err := validateGitHubConfig(&cfg.GitHub); err != nil { + return err + } + } + return nil +} + +// validateGitHubConfig enforces the load-time rules from interaction-spec §4.1 +// and nfr-design-specs §4.5. It returns a non-nil error for any bound violation; +// the caller (LoadConfig) wraps it with the file path and the recovery pointer. +func validateGitHubConfig(g *GitHubConfig) error { + // Provider normalization: empty → "native" (FR-AUTH-05). + if g.Provider == "" { + g.Provider = "native" + } + if g.Provider != "native" && g.Provider != "gh" { + return fmt.Errorf("github.provider: must be 'native' or 'gh'; got %q", g.Provider) + } + + // app_id + installation_id required when the feature is configured. + if g.AppID == 0 { + return fmt.Errorf("github.app_id: required (integer, from GitHub App settings page); see docs/github-app-setup.md §2") + } + if g.InstallationID == 0 { + return fmt.Errorf("github.installation_id: required (integer, from App installation URL/API); see docs/github-app-setup.md §4") + } + if g.PrivateKeyPath == "" { + return fmt.Errorf("github.private_key_path: required (path to App private key PEM); see docs/github-app-setup.md §3") + } + + // token_cache_ttl: default 9m, must be > 0 and < 60m (GitHub's 60-minute + // installation-token lifetime). interaction-spec §4.1 / infra-specs §7.2 + // (B2 resolution: the correct bound is 60m, not the 10m stated in the + // stale nfr-design-specs §4.2 line — GitHub App installation tokens expire + // in 1 hour; see https://docs.github.com/en/apps/creating-github-apps/). + if g.TokenCacheTTL == 0 { + g.TokenCacheTTL = 9 * time.Minute + } + if g.TokenCacheTTL <= 0 { + return fmt.Errorf("github.token_cache_ttl: must be > 0; got %s", g.TokenCacheTTL) + } + if g.TokenCacheTTL >= 60*time.Minute { + return fmt.Errorf("github.token_cache_ttl: must be < 60m (GitHub limit); got %s", g.TokenCacheTTL) + } + + // conflict_poll bounds: defaults 5 / 60s, hard ceilings 10 / 300s. + // nfr-design-specs §4.5, infra-specs §7.2. + if g.ConflictPollMaxRetries == 0 { + g.ConflictPollMaxRetries = 5 + } + if g.ConflictPollMaxDuration == 0 { + g.ConflictPollMaxDuration = 60 * time.Second + } + if g.ConflictPollMaxRetries < 1 || g.ConflictPollMaxRetries > 10 { + return fmt.Errorf("github.conflict_poll_max_retries: must be 1..10; got %d", g.ConflictPollMaxRetries) + } + if g.ConflictPollMaxDuration < 0 || g.ConflictPollMaxDuration > 300*time.Second { + return fmt.Errorf("github.conflict_poll_max_duration: must be 0..300s; got %s", g.ConflictPollMaxDuration) + } return nil } diff --git a/internal/db/artifact_store_test.go b/internal/db/artifact_store_test.go index 6838514..3e803de 100644 --- a/internal/db/artifact_store_test.go +++ b/internal/db/artifact_store_test.go @@ -29,9 +29,12 @@ func truncateAllTables(d *DB) { // repos tables (migration 017) — truncate so repo tests start clean. "repo_settings", "repo_operation_config", "repo_registry", "repos", "stage_logs", + // settings & admin UI (migration 019) — truncate so defaults/config tests start clean. "feature_defaults", "server_config", // provider config tables (migration 020) — truncate so config tests start clean. "role_overrides", "tier_models", "provider_models", "providers", + // credentials table (migration 022) — truncate so cred tests start clean. + "credentials", } for _, table := range tables { d.Conn().Exec("TRUNCATE TABLE " + table + " CASCADE") diff --git a/internal/db/audit_credentials.go b/internal/db/audit_credentials.go new file mode 100644 index 0000000..85ce9d8 --- /dev/null +++ b/internal/db/audit_credentials.go @@ -0,0 +1,93 @@ +package db + +import ( + "fmt" + "time" +) + +// RecordCredentialAuditEvent inserts an audit event with credential_touched=1 +// (feature github-authorization-integration, U-11, FR-AUDIT-02). +// +// The details string MUST already be redacted by the caller (the redaction +// wrapper at internal/github/redaction.go is the write-boundary guard; this +// helper does NOT re-redact — it trusts the caller). details carries +// actor + action + target + fingerprint ONLY, never a secret value +// (nfr-design-specs §5.3, BR-AUDIT-01/02). +// +// Only this helper writes credential_touched=1. The existing 68-call-site +// RecordAuditEvent continues to write 0 (the column's DEFAULT 0 covers it). +// Static check (nfr-design-specs §5.2): grep internal/ for credential_touched +// writes outside this file → zero hits. +func (db *DB) RecordCredentialAuditEvent(featureID, eventType, stageID, phase, details string) error { + _, err := db.Exec( + `INSERT INTO audit_events (feature_id, event_type, stage_id, phase, details, credential_touched, created_at) + VALUES (?, ?, ?, ?, ?, 1, ?)`, + featureID, eventType, stageID, phase, details, time.Now().UTC(), + ) + if err != nil { + return fmt.Errorf("recording credential audit event %s: %w", eventType, err) + } + return nil +} + +// RecordRepoSettingsAudit inserts a REPO_SETTINGS_CHANGED audit event with +// credential_touched=0 (settings are not credentials — FR-AUDIT-03). details +// carries the field diff with redacted values; the caller redacts before +// passing (redaction is defensive even though the MVP field set is non-secret). +func (db *DB) RecordRepoSettingsAudit(featureID, repo, details string) error { + _, err := db.Exec( + `INSERT INTO audit_events (feature_id, event_type, stage_id, phase, details, credential_touched, created_at) + VALUES (?, ?, '', 'repo', ?, 0, ?)`, + featureID, AuditRepoSettingsChanged, details, time.Now().UTC(), + ) + if err != nil { + return fmt.Errorf("recording repo settings audit for %s: %w", repo, err) + } + return nil +} + +// RecordRepoRegistryAudit inserts a REPO_REGISTRY_SYNCED audit event with +// credential_touched=0 (FR-DISC-06, U-04). details carries the sync summary +// (e.g. "added=3 removed=0 managed=2"). +func (db *DB) RecordRepoRegistryAudit(featureID, details string) error { + _, err := db.Exec( + `INSERT INTO audit_events (feature_id, event_type, stage_id, phase, details, credential_touched, created_at) + VALUES (?, ?, '', 'repo', ?, 0, ?)`, + featureID, AuditRepoRegistrySynced, details, time.Now().UTC(), + ) + if err != nil { + return fmt.Errorf("recording repo registry audit: %w", err) + } + return nil +} + +// AuditEventWithCredentialTouched is the extended AuditEvent row shape after +// migration 024 (adds credential_touched). Used by audit-list CLI filtering. +type AuditEventWithCredentialTouched struct { + AuditEvent + CredentialTouched int `json:"credential_touched"` +} + +// GetAuditEventsWithCredentialTouched returns audit events for a feature, +// including the credential_touched column (post-migration-020 shape). +func (db *DB) GetAuditEventsWithCredentialTouched(featureID string) ([]AuditEventWithCredentialTouched, error) { + rows, err := db.Query( + `SELECT id, feature_id, event_type, stage_id, phase, details, created_at, credential_touched + FROM audit_events WHERE feature_id = ? ORDER BY created_at ASC, id ASC`, + featureID, + ) + if err != nil { + return nil, fmt.Errorf("getting audit events (with credential_touched) for %s: %w", featureID, err) + } + defer rows.Close() + + var events []AuditEventWithCredentialTouched + for rows.Next() { + var e AuditEventWithCredentialTouched + if err := rows.Scan(&e.ID, &e.FeatureID, &e.EventType, &e.StageID, &e.Phase, &e.Details, &e.CreatedAt, &e.CredentialTouched); err != nil { + return nil, fmt.Errorf("scanning audit event with credential_touched: %w", err) + } + events = append(events, e) + } + return events, nil +} \ No newline at end of file diff --git a/internal/db/audit_events.go b/internal/db/audit_events.go index e7f678a..9b5709a 100644 --- a/internal/db/audit_events.go +++ b/internal/db/audit_events.go @@ -117,7 +117,6 @@ const ( // the chat expert. Written via RecordAuditEventChat, append-only (SEC-6). // Every op emits one — including rejected (confirmed:false). AuditChatCliExec = "CHAT_CLI_EXEC" - // Admin / config-mutation events (settings-and-admin-ui feature, bolt-plan rev2). // Per Q7/Q8 strict scope cut, the v1 event set is 4 constants — no // PROVIDER_CONFIG_MUTATED (providers deferred to the sibling feature) and no @@ -127,4 +126,14 @@ const ( AuditConfigValidationFailed = "CONFIG_VALIDATION_FAILED" AuditReposRegistryMutated = "REPOS_REGISTRY_MUTATED" AuditFeatureDefaultsMutated = "FEATURE_DEFAULTS_MUTATED" + + // GitHub Authorization Integration (feature github-authorization-integration, U-11, FR-AUDIT-04). + // These 5 constants are additive — the 68 existing constants above are frozen + // (BR-COMPAT-05, C-18). Only RecordCredentialAuditEvent writes credential_touched=1 + // for the credential events; the repo events write credential_touched=0. + AuditCredentialStored = "CREDENTIAL_STORED" + AuditCredentialRotated = "CREDENTIAL_ROTATED" + AuditCredentialRevokeCheck = "CREDENTIAL_REVOKE_CHECK" + AuditRepoSettingsChanged = "REPO_SETTINGS_CHANGED" + AuditRepoRegistrySynced = "REPO_REGISTRY_SYNCED" ) \ No newline at end of file diff --git a/internal/db/migration_022.go b/internal/db/migration_022.go new file mode 100644 index 0000000..90b79a1 --- /dev/null +++ b/internal/db/migration_022.go @@ -0,0 +1,50 @@ +package db + +import ( + "database/sql" + "fmt" +) + +func init() { + RegisterMigration(Migration{ + Version: 22, + Name: "credentials_table", + Up: migration022CredentialsTable, + }) +} + +// migration022CredentialsTable creates the credentials table for encrypted +// GitHub credentials (feature github-authorization-integration, U-06). +// +// Schema per nfr-design-specs §3.6 / infra-specs §5.1: +// - kind: 'app_private_key' | 'installation_token' | 'pat' +// - fingerprint: 16 hex chars (SHA-256 prefix of plaintext) — audit disambiguation, NOT reversible +// - ciphertext: AES-256-GCM ciphertext (variable length = plaintext + 16 tag bytes) +// - nonce: 12-byte GCM nonce (per-encrypt random via crypto/rand) +// - expires_at: NULL for keys/PATs; set for installation_token (restart resilience, BR-CRED-08) +// - rotated_at: NULL until superseded; the "active" row for a kind has rotated_at IS NULL +// +// Idempotence (NFR-COMPAT-01, nfr-design-specs §8.3): CREATE TABLE IF NOT EXISTS +// + CREATE INDEX IF NOT EXISTS — re-running on a migrated DB is a no-op. +func migration022CredentialsTable(tx *sql.Tx) error { + statements := []string{ + `CREATE TABLE IF NOT EXISTS credentials ( + id SERIAL PRIMARY KEY, + kind TEXT NOT NULL, + fingerprint TEXT NOT NULL, + ciphertext BYTEA NOT NULL, + nonce BYTEA NOT NULL, + expires_at TIMESTAMP, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + rotated_at TIMESTAMP + )`, + `CREATE INDEX IF NOT EXISTS idx_credentials_kind_active + ON credentials(kind, rotated_at) WHERE rotated_at IS NULL`, + } + for _, stmt := range statements { + if _, err := tx.Exec(stmt); err != nil { + return fmt.Errorf("executing credentials migration statement: %w\nSQL: %s", err, stmt) + } + } + return nil +} \ No newline at end of file diff --git a/internal/db/migration_023.go b/internal/db/migration_023.go new file mode 100644 index 0000000..f63e1bf --- /dev/null +++ b/internal/db/migration_023.go @@ -0,0 +1,70 @@ +package db + +import ( + "database/sql" + "fmt" +) + +func init() { + RegisterMigration(Migration{ + Version: 23, + Name: "repo_registry_and_settings", + Up: migration023RepoRegistryAndSettings, + }) +} + +// migration023RepoRegistryAndSettings creates the repo_registry and +// repo_settings tables (feature github-authorization-integration, U-04 + U-10). +// +// repo_registry: the canonical set of repos the GitHub App installation manages +// (FR-DISC-02). Includes the `managed` column added by the 2.7 amendment (F3 +// resolution — the MANAGED/AVAILABLE-BUT-UNMANAGED split and `repo manage` +// transition require it). `managed=0` = discovered but not curated; `managed=1` +// = the operator has marked it managed via `devteam repo manage`. +// +// repo_settings: per-repo MVP field set (FR-SETTINGS-01, R-08 fixed set): +// - default_branch (TEXT, default 'main' — FR-PR-02 main fallback, C-11) +// - pr_draft_default (INTEGER 0/1, default 1) +// - conflict_detection_enabled (INTEGER 0/1, default 1) +// - provider (TEXT 'native'|'gh', default 'native' — FR-SETTINGS-05, ADR-17) +// +// Phase-2 fields (required_reviewers, labels, branch_protection, merge_strategy, +// status_checks) are explicitly NOT in this schema — writes are rejected at the +// CLI boundary with "not supported in MVP" (FR-SETTINGS-03, R-08). +// +// Idempotence: CREATE TABLE IF NOT EXISTS (nfr-design-specs §8.3). +func migration023RepoRegistryAndSettings(tx *sql.Tx) error { + statements := []string{ + `CREATE TABLE IF NOT EXISTS repo_registry ( + id SERIAL PRIMARY KEY, + owner TEXT NOT NULL, + name TEXT NOT NULL, + full_name TEXT NOT NULL, + default_branch TEXT NOT NULL DEFAULT 'main', + installation_id BIGINT NOT NULL, + managed INTEGER NOT NULL DEFAULT 0, + discovered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE(owner, name) + )`, + `CREATE INDEX IF NOT EXISTS idx_repo_registry_installation ON repo_registry(installation_id)`, + `CREATE INDEX IF NOT EXISTS idx_repo_registry_managed ON repo_registry(managed)`, + + `CREATE TABLE IF NOT EXISTS repo_settings ( + id SERIAL PRIMARY KEY, + repo_registry_id INTEGER NOT NULL UNIQUE REFERENCES repo_registry(id) ON DELETE CASCADE, + default_branch TEXT NOT NULL DEFAULT 'main', + pr_draft_default INTEGER NOT NULL DEFAULT 1, + conflict_detection_enabled INTEGER NOT NULL DEFAULT 1, + provider TEXT NOT NULL DEFAULT 'native', + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + )`, + `CREATE INDEX IF NOT EXISTS idx_repo_settings_repo ON repo_settings(repo_registry_id)`, + } + for _, stmt := range statements { + if _, err := tx.Exec(stmt); err != nil { + return fmt.Errorf("executing repo_registry/settings statement: %w\nSQL: %s", err, stmt) + } + } + return nil +} \ No newline at end of file diff --git a/internal/db/migration_024.go b/internal/db/migration_024.go new file mode 100644 index 0000000..679cdbf --- /dev/null +++ b/internal/db/migration_024.go @@ -0,0 +1,41 @@ +package db + +import ( + "database/sql" + "fmt" +) + +func init() { + RegisterMigration(Migration{ + Version: 24, + Name: "audit_credential_touched", + Up: migration024AuditCredentialTouched, + }) +} + +// migration024AuditCredentialTouched adds the credential_touched column to +// audit_events (feature github-authorization-integration, U-11, FR-AUDIT-01). +// +// Existing rows keep default 0 (BR-AUDIT-03, C-18 — additive, no backfill). Only +// RecordCredentialAuditEvent (new helper in U-11) writes credential_touched=1; +// the existing 68 RecordAuditEvent call sites continue to write 0 (NFR-COMPAT-01). +// +// The index on (feature_id, credential_touched) backs the P-3 auditor's primary +// filter `--credential-touched` (interaction-spec §7, US-11). +// +// Idempotence: ALTER TABLE ... ADD COLUMN IF NOT EXISTS (Postgres 9.6+, used by +// migration_010 — nfr-design-specs §8.3). The stale comment in migration_012 +// claiming PG doesn't support IF NOT EXISTS is a code-quality finding, not a +// blocker; migration_010 is the precedent that proves it works. +func migration024AuditCredentialTouched(tx *sql.Tx) error { + statements := []string{ + `ALTER TABLE audit_events ADD COLUMN IF NOT EXISTS credential_touched INTEGER NOT NULL DEFAULT 0`, + `CREATE INDEX IF NOT EXISTS idx_audit_events_cred_touched ON audit_events(feature_id, credential_touched)`, + } + for _, stmt := range statements { + if _, err := tx.Exec(stmt); err != nil { + return fmt.Errorf("executing audit_credential_touched statement: %w\nSQL: %s", err, stmt) + } + } + return nil +} \ No newline at end of file diff --git a/internal/db/repo_registry_store.go b/internal/db/repo_registry_store.go new file mode 100644 index 0000000..0af2d41 --- /dev/null +++ b/internal/db/repo_registry_store.go @@ -0,0 +1,134 @@ +package db + +import ( + "database/sql" + "fmt" + "time" +) + +// RepoRegistryRow is one entry in the canonical repo_registry table +// (feature github-authorization-integration, U-04, FR-DISC-02). +type RepoRegistryRow struct { + ID int64 `json:"id"` + Owner string `json:"owner"` + Name string `json:"name"` + FullName string `json:"full_name"` + DefaultBranch string `json:"default_branch"` + InstallationID int64 `json:"installation_id"` + Managed int `json:"managed"` // 0 = discovered/unmanaged, 1 = managed + DiscoveredAt time.Time `json:"discovered_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// UpsertRepoRegistry inserts or updates a repo_registry row for the given +// (owner, name). On conflict it updates default_branch + installation_id + +// updated_at (the discovered fields). `managed` is preserved across re-discovery +// (the operator's curation is not reset by a sync — interaction-spec §3.4). +// Returns the row's ID and whether the row was newly inserted. +func (db *DB) UpsertRepoRegistry(owner, name, fullName, defaultBranch string, installationID int64) (id int64, inserted bool, err error) { + now := time.Now().UTC() + // Try insert first. + res, err := db.Exec( + `INSERT INTO repo_registry (owner, name, full_name, default_branch, installation_id, managed, discovered_at, updated_at) + VALUES (?, ?, ?, ?, ?, 0, ?, ?) + ON CONFLICT (owner, name) DO UPDATE SET + default_branch = EXCLUDED.default_branch, + installation_id = EXCLUDED.installation_id, + full_name = EXCLUDED.full_name, + updated_at = EXCLUDED.updated_at`, + owner, name, fullName, defaultBranch, installationID, now, now, + ) + if err != nil { + return 0, false, fmt.Errorf("upserting repo_registry (%s/%s): %w", owner, name, err) + } + affected, _ := res.RowsAffected() + if affected == 0 { + // ON CONFLICT path — fetch existing id. + err = db.QueryRow(`SELECT id FROM repo_registry WHERE owner = ? AND name = ?`, owner, name).Scan(&id) + if err != nil { + return 0, false, fmt.Errorf("fetching repo_registry id after upsert (%s/%s): %w", owner, name, err) + } + return id, false, nil + } + // Insert path — fetch the new id. + err = db.QueryRow(`SELECT id FROM repo_registry WHERE owner = ? AND name = ?`, owner, name).Scan(&id) + if err != nil { + return 0, false, fmt.Errorf("fetching repo_registry id after insert (%s/%s): %w", owner, name, err) + } + return id, true, nil +} + +// SetRepoManaged flips the managed flag on a repo_registry row (FR-DISC-06, +// `devteam repo manage`, interaction-spec §3.4). Returns sql.ErrNoRows if the +// repo is not in the registry (the caller surfaces the F-3 error branch). +func (db *DB) SetRepoManaged(owner, name string, managed int) error { + res, err := db.Exec( + `UPDATE repo_registry SET managed = ?, updated_at = ? WHERE owner = ? AND name = ?`, + managed, time.Now().UTC(), owner, name, + ) + if err != nil { + return fmt.Errorf("setting managed=%d on (%s/%s): %w", managed, owner, name, err) + } + n, _ := res.RowsAffected() + if n == 0 { + return fmt.Errorf("repo %s/%s not found in registry", owner, name) + } + return nil +} + +// ListRepoRegistry returns all registry rows, optionally filtered by managed. +func (db *DB) ListRepoRegistry(managedFilter *int) ([]RepoRegistryRow, error) { + var rows *sql.Rows + var err error + if managedFilter != nil { + rows, err = db.Query( + `SELECT id, owner, name, full_name, default_branch, installation_id, managed, discovered_at, updated_at + FROM repo_registry WHERE managed = ? ORDER BY managed DESC, owner ASC, name ASC`, + *managedFilter, + ) + } else { + rows, err = db.Query( + `SELECT id, owner, name, full_name, default_branch, installation_id, managed, discovered_at, updated_at + FROM repo_registry ORDER BY managed DESC, owner ASC, name ASC`, + ) + } + if err != nil { + return nil, fmt.Errorf("listing repo_registry: %w", err) + } + defer rows.Close() + + var out []RepoRegistryRow + for rows.Next() { + var r RepoRegistryRow + if err := rows.Scan(&r.ID, &r.Owner, &r.Name, &r.FullName, &r.DefaultBranch, &r.InstallationID, &r.Managed, &r.DiscoveredAt, &r.UpdatedAt); err != nil { + return nil, fmt.Errorf("scanning repo_registry row: %w", err) + } + out = append(out, r) + } + return out, nil +} + +// GetRepoRegistry returns a single registry row by owner/name. +func (db *DB) GetRepoRegistry(owner, name string) (*RepoRegistryRow, error) { + var r RepoRegistryRow + err := db.QueryRow( + `SELECT id, owner, name, full_name, default_branch, installation_id, managed, discovered_at, updated_at + FROM repo_registry WHERE owner = ? AND name = ?`, + owner, name, + ).Scan(&r.ID, &r.Owner, &r.Name, &r.FullName, &r.DefaultBranch, &r.InstallationID, &r.Managed, &r.DiscoveredAt, &r.UpdatedAt) + if err != nil { + return nil, fmt.Errorf("getting repo_registry (%s/%s): %w", owner, name, err) + } + return &r, nil +} + +// RepoRegistryEmpty reports whether the repo_registry table has zero rows. +// Used by the startup seed path (U-07): if empty, seed from repos.yaml. +func (db *DB) RepoRegistryEmpty() (bool, error) { + var count int + err := db.QueryRow(`SELECT COUNT(*) FROM repo_registry`).Scan(&count) + if err != nil { + return false, fmt.Errorf("counting repo_registry: %w", err) + } + return count == 0, nil +} \ No newline at end of file diff --git a/internal/db/repo_settings_store.go b/internal/db/repo_settings_store.go new file mode 100644 index 0000000..1f1ac95 --- /dev/null +++ b/internal/db/repo_settings_store.go @@ -0,0 +1,151 @@ +package db + +import ( + "database/sql" + "fmt" + "time" +) + +// RepoSettingsRow is one per-repo settings row (feature github-authorization-integration, +// U-10, FR-SETTINGS-01). MVP field set is fixed (R-08): +// - default_branch (FR-PR-02, C-11 main fallback) +// - pr_draft_default +// - conflict_detection_enabled +// - provider (native|gh, FR-SETTINGS-05, ADR-17) +type RepoSettingsRow struct { + ID int64 `json:"id"` + RepoRegistryID int64 `json:"repo_registry_id"` + DefaultBranch string `json:"default_branch"` + PrDraftDefault int `json:"pr_draft_default"` // 0/1 + ConflictDetectionEnabled int `json:"conflict_detection_enabled"` // 0/1 + Provider string `json:"provider"` // "native" | "gh" + UpdatedAt time.Time `json:"updated_at"` +} + +// MVPRepoSettingsFields is the fixed set of allowed `repo set` keys (R-08, +// FR-SETTINGS-01). Writes outside this set are rejected at the CLI boundary +// with "not supported in MVP" (FR-SETTINGS-03). +var MVPRepoSettingsFields = []string{ + "default_branch", + "pr_draft_default", + "conflict_detection_enabled", + "provider", +} + +// Phase2RepoSettingsFields are explicitly NOT supported in MVP. A `repo set` +// write of any of these fails with exit 2 and the scope-change pointer (R-08). +var Phase2RepoSettingsFields = []string{ + "required_reviewers", + "labels", + "branch_protection", + "merge_strategy", + "status_checks", +} + +// GetRepoSettings reads the settings row for a repo_registry row. Returns +// (nil, nil) if no settings row exists — the caller applies defaults (main, +// draft=true, conflict_detection=true, provider=native) per FR-SETTINGS-01. +func (db *DB) GetRepoSettings(repoRegistryID int64) (*RepoSettingsRow, error) { + var r RepoSettingsRow + err := db.QueryRow( + `SELECT id, repo_registry_id, default_branch, pr_draft_default, conflict_detection_enabled, provider, updated_at + FROM repo_settings WHERE repo_registry_id = ?`, + repoRegistryID, + ).Scan(&r.ID, &r.RepoRegistryID, &r.DefaultBranch, &r.PrDraftDefault, &r.ConflictDetectionEnabled, &r.Provider, &r.UpdatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("getting repo_settings for registry_id %d: %w", repoRegistryID, err) + } + return &r, nil +} + +// UpsertRepoSettings inserts or updates a settings field. field must be in +// MVPRepoSettingsFields (the caller validates). value is the string form; this +// helper coerces to the column type. Returns the upserted row. +func (db *DB) UpsertRepoSettings(repoRegistryID int64, field, value string) (*RepoSettingsRow, error) { + // Validate field is in MVP set (defense in depth — the CLI validates first). + if !contains(MVPRepoSettingsFields, field) { + return nil, fmt.Errorf("field %q is not in the MVP settings set; supported: %v", field, MVPRepoSettingsFields) + } + + // Ensure a settings row exists (INSERT if missing), then UPDATE the field. + // This is a single-statement upsert pattern via ON CONFLICT. + now := time.Now().UTC() + + // Coerce value to the column type. + var setClause string + switch field { + case "default_branch": + setClause = "default_branch = EXCLUDED.default_branch" + case "pr_draft_default": + coerced, err := coerceBool(value, "pr_draft_default") + if err != nil { + return nil, err + } + value = coerced + setClause = "pr_draft_default = EXCLUDED.pr_draft_default" + case "conflict_detection_enabled": + coerced, err := coerceBool(value, "conflict_detection_enabled") + if err != nil { + return nil, err + } + value = coerced + setClause = "conflict_detection_enabled = EXCLUDED.conflict_detection_enabled" + case "provider": + if value != "native" && value != "gh" { + return nil, fmt.Errorf("provider: must be 'native' or 'gh'; got %q", value) + } + setClause = "provider = EXCLUDED.provider" + } + + // Build the INSERT with the field set, then ON CONFLICT update just that field. + // We use a dynamic column list to keep the insert minimal. + var insertCols, insertVals string + switch field { + case "default_branch": + insertCols = "repo_registry_id, default_branch, pr_draft_default, conflict_detection_enabled, provider" + insertVals = "?, ?, 1, 1, 'native'" + case "pr_draft_default": + insertCols = "repo_registry_id, default_branch, pr_draft_default, conflict_detection_enabled, provider" + insertVals = "?, 'main', ?, 1, 'native'" + case "conflict_detection_enabled": + insertCols = "repo_registry_id, default_branch, pr_draft_default, conflict_detection_enabled, provider" + insertVals = "?, 'main', 1, ?, 'native'" + case "provider": + insertCols = "repo_registry_id, default_branch, pr_draft_default, conflict_detection_enabled, provider" + insertVals = "?, 'main', 1, 1, ?" + } + + query := `INSERT INTO repo_settings (` + insertCols + `, updated_at) VALUES (` + insertVals + `, ?) + ON CONFLICT (repo_registry_id) DO UPDATE SET ` + setClause + `, updated_at = EXCLUDED.updated_at` + + _, err := db.Exec(query, repoRegistryID, value, now) + if err != nil { + return nil, fmt.Errorf("upserting repo_settings (field=%s, value=%s): %w", field, value, err) + } + + return db.GetRepoSettings(repoRegistryID) +} + +func contains(s []string, v string) bool { + for _, x := range s { + if x == v { + return true + } + } + return false +} + +// coerceBool converts "true"/"false"/"1"/"0" to "1"/"0" for INTEGER columns. +func coerceBool(value, field string) (string, error) { + switch value { + case "true", "1": + return "1", nil + case "false", "0": + return "0", nil + default: + return "", fmt.Errorf("%s: must be true|false|1|0; got %q", field, value) + } +} \ No newline at end of file diff --git a/internal/db/repos_overlay.go b/internal/db/repos_overlay.go new file mode 100644 index 0000000..217e13c --- /dev/null +++ b/internal/db/repos_overlay.go @@ -0,0 +1,138 @@ +package db + +import ( + "fmt" + "os" + "path/filepath" + "time" + + "gopkg.in/yaml.v3" +) + +// MaterializeReposOverlay writes the per-feature repos.yaml from repo_registry +// (+ repo_settings join) so internal/repo/manager.go consumers keep working +// without code change (FR-DISC-04, C-10, NFR-COMPAT-04, U-07). +// +// The materialized file is the SAME shape as the root repos.yaml (the +// ReposConfig struct in internal/config) — `repos:` list with name/url/description. +// The DB is canonical; the file is a generated overlay. The root repos.yaml +// stays parse-compatible (FR-DISC-05) and is marked deprecated (U-07 adds the +// deprecation comment to the root file separately). +// +// If repo_registry is empty, the materialization seeds from the root repos.yaml +// (the startup seed path, FR-DISC-04). This makes the transition seamless: an +// operator with an existing repos.yaml gets it loaded into repo_registry on +// first startup, then subsequent runs materialize from the DB. +func (db *DB) MaterializeReposOverlay(rootReposYAMLPath, featureReposYAMLPath string) error { + empty, err := db.RepoRegistryEmpty() + if err != nil { + return fmt.Errorf("checking repo_registry empty: %w", err) + } + if empty { + // Seed from the root repos.yaml if it exists. + if err := db.seedRepoRegistryFromYAML(rootReposYAMLPath); err != nil { + return fmt.Errorf("seeding repo_registry from %s: %w", rootReposYAMLPath, err) + } + } + + // Read the joined registry + settings and write the overlay. + rows, err := db.Query( + `SELECT r.name, r.full_name, r.default_branch, r.managed, + COALESCE(s.provider, 'native') + FROM repo_registry r + LEFT JOIN repo_settings s ON s.repo_registry_id = r.id + ORDER BY r.managed DESC, r.owner ASC, r.name ASC`, + ) + if err != nil { + return fmt.Errorf("querying repo_registry for overlay: %w", err) + } + defer rows.Close() + + type overlayEntry struct { + Name string `yaml:"name"` + Description string `yaml:"description"` + Managed int `yaml:"managed"` + DefaultBranch string `yaml:"default_branch"` + Provider string `yaml:"provider"` + } + var entries []overlayEntry + for rows.Next() { + var e overlayEntry + if err := rows.Scan(&e.Name, &e.Description, &e.DefaultBranch, &e.Managed, &e.Provider); err != nil { + return fmt.Errorf("scanning overlay row: %w", err) + } + entries = append(entries, e) + } + + // Build the overlay YAML. We use a simple struct that matches the root + // repos.yaml shape (name + description) plus the new managed/provider/default_branch + // fields (additive — the root file ignores unknown fields via yaml.v3). + out := struct { + Repos []overlayEntry `yaml:"repos"` + }{Repos: entries} + + data, err := yaml.Marshal(out) + if err != nil { + return fmt.Errorf("marshaling overlay yaml: %w", err) + } + + // Ensure the feature dir exists. + dir := filepath.Dir(featureReposYAMLPath) + if dir != "." && dir != "" { + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("creating overlay dir %s: %w", dir, err) + } + } + + if err := os.WriteFile(featureReposYAMLPath, data, 0o644); err != nil { + return fmt.Errorf("writing overlay %s: %w", featureReposYAMLPath, err) + } + return nil +} + +// seedRepoRegistryFromYAML reads the root repos.yaml and inserts each repo +// into repo_registry (managed=1, since the operator explicitly listed them — +// the root file is the curated set). installation_id is set to 0 (unknown); +// discovery will update it on the next sync. +func (db *DB) seedRepoRegistryFromYAML(path string) error { + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + return nil // no root file → empty registry is fine + } + return fmt.Errorf("reading %s: %w", path, err) + } + var cfg struct { + Repos []struct { + Name string `yaml:"name"` + URL string `yaml:"url"` + Description string `yaml:"description"` + } `yaml:"repos"` + } + if err := yaml.Unmarshal(data, &cfg); err != nil { + return fmt.Errorf("parsing %s: %w", path, err) + } + now := time.Now().UTC() + for _, r := range cfg.Repos { + owner, name := splitFullName(r.Name) + _, _, err := db.UpsertRepoRegistry(owner, name, r.Name, "main", 0) + if err != nil { + return fmt.Errorf("seeding %s: %w", r.Name, err) + } + // Mark seeded repos as managed (they were in the operator's curated list). + _ = db.SetRepoManaged(owner, name, 1) + } + _ = now + return nil +} + +// splitFullName splits "owner/name" into (owner, name). If there's no slash, +// the whole string is the name and owner is "". +func splitFullName(full string) (string, string) { + for i, c := range full { + if c == '/' { + return full[:i], full[i+1:] + } + } + return "", full +} \ No newline at end of file diff --git a/internal/db/test_helpers.go b/internal/db/test_helpers.go index 357c61d..f8bebfa 100644 --- a/internal/db/test_helpers.go +++ b/internal/db/test_helpers.go @@ -20,6 +20,8 @@ func TruncateAllTables(d *DB) { "feature_defaults", "server_config", // provider config tables (migration 020) — truncate so config tests start clean. "role_overrides", "tier_models", "provider_models", "providers", + // credentials table (migration 022) — truncate so cred tests start clean. + "credentials", } for _, table := range tables { d.Conn().Exec("TRUNCATE TABLE " + table + " CASCADE") diff --git a/internal/github/client.go b/internal/github/client.go new file mode 100644 index 0000000..350a5c7 --- /dev/null +++ b/internal/github/client.go @@ -0,0 +1,50 @@ +package github + +import ( + "context" + "errors" +) + +// GitHubClient is the sole interface for GitHub API access in the devteam +// platform (feature github-authorization-integration, U-01, ADR-01, FR-IFACE-01). +// +// The interface uses domain types (RepoRef, Repository, PRRef, MergeableState), +// NOT go-github types, so callers never transitively import go-github +// (ADR-04). NativeClient translates at its boundary. +// +// 7 methods, all taking context.Context first (ADR-04). The GhCLIClient adapter +// implements 3 (CreatePR, ReadyPR, CommentPR) and returns ErrUnsupported for the +// other 4 (ADR-08) — it is a fallback, not a parallel implementation. +type GitHubClient interface { + AuthHealthCheck(ctx context.Context) error + ListRepositories(ctx context.Context) ([]Repository, error) + CreateBranch(ctx context.Context, repo RepoRef, branch, from string) error + CreatePR(ctx context.Context, repo RepoRef, base, head, title, body string, draft bool) (*PRRef, error) + ReadyPR(ctx context.Context, repo RepoRef, number int64) error + CommentPR(ctx context.Context, repo RepoRef, number int64, body string) error + GetMergeableState(ctx context.Context, repo RepoRef, number int64) (MergeableState, error) +} + +// ErrUnsupported is the sentinel returned by GhCLIClient for interface methods +// it does not back (AuthHealthCheck, ListRepositories, GetMergeableState, +// CreateBranch — ADR-08). Callers check errors.Is(err, ErrUnsupported) and +// either fail with a clear message or fall back to NativeClient. +var ErrUnsupported = errors.New("gh CLI adapter does not support this method") + +// NewClient is the factory seam (ADR-02, FR-AUTH-05). It selects NativeClient +// (default) or GhCLIClient from the provider config. Concrete constructors +// live in U-02 (native.go) and U-03 (ghcli.go); this function is the single +// dispatch point the pipeline and CLI use. +// +// Until U-02 lands, provider=native returns a clear "native client not +// implemented" error (U-01 acceptance). With U-02, it returns *NativeClient. +func NewClient(cfg Config) (GitHubClient, error) { + switch cfg.Provider { + case "", "native": + return NewNativeClient(cfg) + case "gh": + return NewGhCLIClient(cfg) + default: + return nil, errors.New("github.provider: must be 'native' or 'gh'; got '" + cfg.Provider + "'") + } +} \ No newline at end of file diff --git a/internal/github/client_test.go b/internal/github/client_test.go new file mode 100644 index 0000000..db52f51 --- /dev/null +++ b/internal/github/client_test.go @@ -0,0 +1,289 @@ +package github + +import ( + "database/sql" + "errors" + "fmt" + "os/exec" + "strings" + "testing" + "time" +) + +// TestCredstoreEncryptDecryptRoundTrip verifies AES-256-GCM round-trip +// (FR-CRED-01, U-06 acceptance). Uses an in-memory master key (no DB needed +// for the crypto round-trip). +func TestCredstoreEncryptDecryptRoundTrip(t *testing.T) { + c := &Credstore{} + // Set a 32-byte master key directly (bypasses env-var loading for unit test). + copy(c.masterKey[:], []byte("0123456789ABCDEF0123456789ABCDEF")) + + plaintext := []byte("super-secret-app-private-key-PEM") + ciphertext, nonce, err := c.Encrypt(plaintext) + if err != nil { + t.Fatalf("Encrypt: %v", err) + } + if len(nonce) != 12 { + t.Errorf("nonce len = %d; want 12", len(nonce)) + } + if len(ciphertext) != len(plaintext)+16 { + t.Errorf("ciphertext len = %d; want %d (plaintext + 16 GCM tag)", len(ciphertext), len(plaintext)+16) + } + + decrypted, err := c.Decrypt(ciphertext, nonce) + if err != nil { + t.Fatalf("Decrypt: %v", err) + } + if string(decrypted) != string(plaintext) { + t.Errorf("round-trip mismatch: got %q; want %q", decrypted, plaintext) + } +} + +// TestCredstoreTamperedCiphertext verifies GCM tag mismatch surfaces as +// ErrCiphertextTampered (NFR-SEC-02 key-loss simulation, nfr-design-specs §3.4). +func TestCredstoreTamperedCiphertext(t *testing.T) { + c := &Credstore{} + copy(c.masterKey[:], []byte("0123456789ABCDEF0123456789ABCDEF")) + + ct, nonce, _ := c.Encrypt([]byte("plaintext")) + // Flip a byte in the ciphertext. + ct[0] ^= 0xFF + _, err := c.Decrypt(ct, nonce) + if !errors.Is(err, ErrCiphertextTampered) { + t.Errorf("expected ErrCiphertextTampered; got %v", err) + } +} + +// TestCredstoreKeyMismatch verifies a different master key fails to decrypt +// (the key-loss recovery path: a re-generated master key cannot read old rows). +func TestCredstoreKeyMismatch(t *testing.T) { + c1 := &Credstore{} + copy(c1.masterKey[:], []byte("0123456789ABCDEF0123456789ABCDEF")) + c2 := &Credstore{} + copy(c2.masterKey[:], []byte("FEDCBA9876543210FEDCBA9876543210")) + + ct, nonce, _ := c1.Encrypt([]byte("plaintext")) + _, err := c2.Decrypt(ct, nonce) + if !errors.Is(err, ErrCiphertextTampered) { + t.Errorf("expected ErrCiphertextTampered on key mismatch; got %v", err) + } +} + +// TestFingerprintIs16HexChars verifies the audit-disambiguation fingerprint +// (nfr-design-specs §3.6 — 16 hex chars, SHA-256 prefix). +func TestFingerprintIs16HexChars(t *testing.T) { + fp := Fingerprint([]byte("some-credential")) + if len(fp) != 16 { + t.Errorf("fingerprint len = %d; want 16", len(fp)) + } + for _, c := range fp { + if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) { + t.Errorf("fingerprint contains non-hex char %q in %q", c, fp) + } + } +} + +// TestRedactTokenURLs verifies the token-URL scrubbing (CR-03, FR-AUDIT-05, +// nfr-design-specs §2.2). +func TestRedactTokenURLs(t *testing.T) { + tests := []struct { + name string + input string + want string + }{ + { + name: "PAT in URL", + input: "error cloning https://ghp_abcdef1234567890@github.com/owner/repo", + want: "error cloning https://[redacted]@github.com/owner/repo", + }, + { + name: "installation token in URL", + input: "failed: https://ghs_abcdefghijklmnop@github.com/org/repo.git", + want: "failed: https://[redacted]@github.com/org/repo.git", + }, + { + name: "token query param", + input: "GET https://api.github.com/?token=gho_secretvalue123", + want: "GET https://api.github.com/?token=[redacted]", + }, + { + name: "bare ghp_ prefix", + input: "leaked: ghp_1234567890abcdefghijklmnopqrstuv", + want: "leaked: ghp_[redacted]", + }, + { + name: "no token", + input: "ordinary error: connection refused", + want: "ordinary error: connection refused", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := redactString(tc.input) + if got != tc.want { + t.Errorf("redactString(%q)\n got: %q\n want: %q", tc.input, got, tc.want) + } + }) + } +} + +// TestRedactTokenURLsIdempotent verifies double-application is identical to +// single (nfr-design-specs §2.2 — defensive against double-wrapping). +func TestRedactTokenURLsIdempotent(t *testing.T) { + input := "https://ghp_secret@github.com/repo" + once := redactString(input) + twice := redactString(once) + if once != twice { + t.Errorf("redaction not idempotent:\n once: %q\n twice: %q", once, twice) + } +} + +// TestRedactTokenURLsOnError verifies the error-wrapper form preserves +// errors.Is/As unwrapping (nfr-design-specs §2.2). +func TestRedactTokenURLsOnError(t *testing.T) { + original := fmt.Errorf("clone failed: https://ghp_secret@github.com/repo: %w", sql.ErrConnDone) + redacted := redactTokenURLs(original) + if !errors.Is(redacted, sql.ErrConnDone) { + t.Errorf("errors.Is broken by redaction: %v", redacted) + } + redactedStr := redacted.Error() + if strings.Contains(redactedStr, "ghp_secret") { + t.Errorf("token leaked in redacted error: %q", redactedStr) + } + if !strings.Contains(redactedStr, "[redacted]") { + t.Errorf("redaction marker missing in: %q", redactedStr) + } +} + +// TestMergeableStateString verifies the lowercase banner form (interaction-spec §8.4). +func TestMergeableStateString(t *testing.T) { + tests := []struct { + state MergeableState + want string + }{ + {Mergeable, "mergeable"}, + {Conflicting, "conflicting"}, + {MergeableUnknown, "unknown"}, + } + for _, tc := range tests { + if got := tc.state.String(); got != tc.want { + t.Errorf("%d.String() = %q; want %q", tc.state, got, tc.want) + } + } +} + +// TestAuthErrorCodeRunbookSection verifies every code maps to a section +// (BR-AUTH-05, nfr-design-specs §5.1). +func TestAuthErrorCodeRunbookSection(t *testing.T) { + codes := []AuthErrorCode{ + ErrCodeInstallationNotFound, + ErrCodeInstallationSuspended, + ErrCodeKeyRejected, + ErrCodeKeyFileMissing, + ErrCodeKeyFileInvalid, + ErrCodePATFallbackExhausted, + ErrCodeCiphertextTampered, + ErrCodeGhCLINotFound, + } + for _, c := range codes { + section := c.RunbookSection() + if section == "" || !strings.HasPrefix(section, "§") { + t.Errorf("code %q: runbook section = %q; want non-empty §-prefixed", c, section) + } + } +} + +// TestAuthErrorFormatting verifies the Error() string includes the runbook pointer. +func TestAuthErrorFormatting(t *testing.T) { + ae := &AuthError{Code: ErrCodeInstallationNotFound, Message: "installation #42 not reachable"} + s := ae.Error() + if !strings.Contains(s, "installation_not_found") { + t.Errorf("error string missing code: %q", s) + } + if !strings.Contains(s, "docs/github-app-setup.md") { + t.Errorf("error string missing runbook pointer: %q", s) + } + if !strings.Contains(s, "§10") { + t.Errorf("error string missing section: %q", s) + } +} + +// TestIsAuthError verifies the errors.As-based extraction. +func TestIsAuthError(t *testing.T) { + original := authErrorFromCode(ErrCodeKeyRejected, "bad key") + wrapped := fmt.Errorf("wrap: %w", original) + + ae, ok := IsAuthError(wrapped) + if !ok { + t.Fatalf("IsAuthError returned false for wrapped *AuthError") + } + if ae.Code != ErrCodeKeyRejected { + t.Errorf("extracted code = %q; want %q", ae.Code, ErrCodeKeyRejected) + } +} + +// TestGhCLIClientErrUnsupported verifies the adapter returns ErrUnsupported for +// the 4 net-new methods (ADR-08, FR-IFACE-04, U-03 acceptance). +func TestGhCLIClientErrUnsupported(t *testing.T) { + g := &GhCLIClient{baseDir: t.TempDir()} + ctx := t.Context() + + if _, err := g.ListRepositories(ctx); !errors.Is(err, ErrUnsupported) { + t.Errorf("ListRepositories: expected ErrUnsupported; got %v", err) + } + if _, err := g.GetMergeableState(ctx, RepoRef{Owner: "o", Name: "n"}, 1); !errors.Is(err, ErrUnsupported) { + t.Errorf("GetMergeableState: expected ErrUnsupported; got %v", err) + } + if err := g.CreateBranch(ctx, RepoRef{Owner: "o", Name: "n"}, "b", "main"); !errors.Is(err, ErrUnsupported) { + t.Errorf("CreateBranch: expected ErrUnsupported; got %v", err) + } +} + +// TestGhCLIClientAuthHealthCheckGhAbsent verifies NFR-PORT-03: when provider=gh +// and gh is not on PATH, AuthHealthCheck returns a typed ErrCodeGhCLINotFound +// error (not a panic, not an exec error leak). +func TestGhCLIClientAuthHealthCheckGhAbsent(t *testing.T) { + // Sanitize PATH so gh is not findable. This test only runs if gh is NOT + // installed at the test host's PATH (most CI). If gh IS installed, skip. + if _, err := exec.LookPath("gh"); err == nil { + t.Skip("gh is on PATH; cannot test gh-absent detection on this host") + } + g := &GhCLIClient{baseDir: t.TempDir()} + err := g.AuthHealthCheck(t.Context()) + ae, ok := IsAuthError(err) + if !ok { + t.Fatalf("expected *AuthError; got %T: %v", err, err) + } + if ae.Code != ErrCodeGhCLINotFound { + t.Errorf("code = %q; want %q", ae.Code, ErrCodeGhCLINotFound) + } +} + +// TestTokenCacheTTL verifies the cache returns fresh hits and expires. +func TestTokenCacheTTL(t *testing.T) { + tc := newTokenCache(50 * time.Millisecond) + tc.set("token-A", "refreshed", 50*time.Millisecond) + if got, ok := tc.get(); !ok || got != "token-A" { + t.Errorf("fresh get: got %q ok=%v; want token-A true", got, ok) + } + time.Sleep(60 * time.Millisecond) + if _, ok := tc.get(); ok { + t.Errorf("expired get: expected ok=false") + } +} + +// TestTokenCacheProvenance verifies the "cached" downgrade on warm reads +// (interaction-spec §8.1). +func TestTokenCacheProvenance(t *testing.T) { + tc := newTokenCache(time.Minute) + tc.set("tok", "refreshed", time.Minute) + // First read within 1s → "refreshed". + if got := tc.provenance(); got != "refreshed" { + t.Errorf("immediate provenance = %q; want refreshed", got) + } + // Wait past 1s → "cached". + time.Sleep(1100 * time.Millisecond) + if got := tc.provenance(); got != "cached" { + t.Errorf("warm provenance = %q; want cached", got) + } +} \ No newline at end of file diff --git a/internal/github/credstore.go b/internal/github/credstore.go new file mode 100644 index 0000000..a24fcd9 --- /dev/null +++ b/internal/github/credstore.go @@ -0,0 +1,313 @@ +// Package github is the sole GitHub-API boundary for the devteam platform +// (feature github-authorization-integration, ADR-01). All GitHub API access — +// authentication, repository discovery, PR operations, merge-conflict polling — +// goes through this package. No other package imports google/go-github, +// golang.org/x/oauth2, or the App private key material. +// +// The package owns: +// - GitHubClient interface + domain types (U-01) +// - NativeClient (go-github, default) + GhCLIClient (gh-CLI fallback adapter) (U-02, U-03) +// - Encrypted credential store at rest (U-06) +// - Repository discovery + per-repo settings reader (U-04) +// - Branch/PR ops + mergeable-state poll (U-08, U-09) +// - Audit redaction wrapper (U-11) +// +// Build invariant (ADR-18): internal/github/ is the sole importer of +// google/go-github and golang.org/x/oauth2. A test in imports_test.go asserts +// this. AES-GCM uses stdlib crypto/aes + crypto/cipher (nfr-design-specs §3.1 +// refinement: x/crypto is NOT imported by this feature). +package github + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "time" +) + +// Credstore encrypts and decrypts GitHub credentials at rest using AES-256-GCM +// with a master key sourced from an env-pointed file path (feature +// github-authorization-integration, U-06, FR-CRED-01/02, C-04, C-12). +// +// The master key is loaded ONCE at process startup and held in an unexported +// field (nfr-design-specs §3.2). It is never logged, never in devteam.yaml, +// never in any DB table (BR-CRED-03). Key loss is documented-unrecoverable +// (NFR-SEC-02); there is no escrow. +// +// The credstore is the SOLE reader of decrypted credential values (FR-CRED-03). +// NativeClient calls credstore.Decrypt on JWT mint (ADR-10); no other package +// reads plaintext. Static check: grep internal/ for direct credentials-ciphertext +// reads outside this file → zero hits. +type Credstore struct { + db *sql.DB + masterKey [32]byte // AES-256 key; loaded once at startup, never re-read +} + +// CredentialKind enumerates the `kind` values stored in the credentials table. +const ( + CredKindAppPrivateKey = "app_private_key" + CredKindInstallationToken = "installation_token" + CredKindPAT = "pat" +) + +// ErrKeyFileMissing is returned when the master key file (or env var) is not +// found at the configured path (nfr-design-specs §3.2). It is an *AuthError so +// callers can branch via errors.As and the CLI can format the W-10 block. +var ErrKeyFileMissing = errors.New("master key file not found") + +// ErrKeyFileInvalid is returned when the master key file is not exactly 32 bytes +// (a trailing newline is the common cause — the operator must `truncate -s 32`). +var ErrKeyFileInvalid = errors.New("master key file is not 32 bytes") + +// ErrCiphertextTampered is returned when GCM tag verification fails — the +// ciphertext was modified, or the master key does not match the one used to +// encrypt (NFR-SEC-02 key-loss simulation path, nfr-design-specs §3.4). +var ErrCiphertextTampered = errors.New("ciphertext tampered or master key mismatch") + +// ErrNoActiveCredential is returned when no active (rotated_at IS NULL) row +// exists for the requested kind. +var ErrNoActiveCredential = errors.New("no active credential of that kind") + +// NewCredstore loads the master key from the env-pointed file path +// (DEVTEAM_MASTER_KEY_FILE) or, as a fallback, the DEVTEAM_MASTER_KEY env var +// (base64 or raw 32 bytes). It returns an error if the key is missing or +// not 32 bytes; the caller (cmd/devteam/main.go) fails fast at startup with +// a runbook pointer (FR-CRED-01, NFR-OPS-01). +// +// db may be nil — a nil-DB credstore can still load the master key (used by +// the auth-health CLI path before the DB is opened in some test scenarios). +// Encrypt/Decrypt require a non-nil DB. +func NewCredstore(db *sql.DB) (*Credstore, error) { + key, err := loadMasterKey() + if err != nil { + return nil, err + } + var k [32]byte + copy(k[:], key) + // Zero the source slice defensively. + for i := range key { + key[i] = 0 + } + return &Credstore{db: db, masterKey: k}, nil +} + +// loadMasterKey reads the master key from DEVTEAM_MASTER_KEY_FILE (preferred, +// 32 bytes raw) or DEVTEAM_MASTER_KEY (fallback, base64 or raw 32 bytes). +// nfr-design-specs §3.2. +func loadMasterKey() ([]byte, error) { + if path := os.Getenv("DEVTEAM_MASTER_KEY_FILE"); path != "" { + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("%w: %s: %v", ErrKeyFileMissing, path, err) + } + if len(data) != 32 { + return nil, fmt.Errorf("%w: %s is %d bytes; expected 32 (truncate -s 32 %s)", ErrKeyFileInvalid, path, len(data), path) + } + return data, nil + } + if v := os.Getenv("DEVTEAM_MASTER_KEY"); v != "" { + // Try base64 first, then raw. + if decoded, err := base64.StdEncoding.DecodeString(v); err == nil && len(decoded) == 32 { + return decoded, nil + } + if len(v) == 32 { + return []byte(v), nil + } + return nil, fmt.Errorf("DEVTEAM_MASTER_KEY is set but is %d bytes (not 32 raw or base64 of 32); expected 32", len(v)) + } + return nil, fmt.Errorf("%w: set DEVTEAM_MASTER_KEY_FILE to the master key file path; see docs/github-app-setup.md §3", ErrKeyFileMissing) +} + +// Encrypt encrypts plaintext with AES-256-GCM using a fresh random 12-byte +// nonce. Returns (ciphertext, nonce). The ciphertext includes the GCM auth tag +// (16 bytes appended, stdlib behavior). The caller persists both columns. +// +// The API makes misuse impossible: there is no nonce-input parameter (nfr-design-specs +// §3.3, principle 3 — error prevention). Random nonce via crypto/rand; no reuse. +func (c *Credstore) Encrypt(plaintext []byte) (ciphertext, nonce []byte, err error) { + block, err := aes.NewCipher(c.masterKey[:]) + if err != nil { + return nil, nil, fmt.Errorf("creating AES cipher: %w", err) + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return nil, nil, fmt.Errorf("creating GCM: %w", err) + } + nonce = make([]byte, gcm.NonceSize()) + if _, err := io.ReadFull(rand.Reader, nonce); err != nil { + return nil, nil, fmt.Errorf("generating nonce: %w", err) + } + ciphertext = gcm.Seal(nil, nonce, plaintext, nil) + return ciphertext, nonce, nil +} + +// Decrypt decrypts ciphertext+nonce with AES-256-GCM. Returns the plaintext. +// On tag mismatch (ciphertext tampered or key mismatch) returns ErrCiphertextTampered. +func (c *Credstore) Decrypt(ciphertext, nonce []byte) ([]byte, error) { + block, err := aes.NewCipher(c.masterKey[:]) + if err != nil { + return nil, fmt.Errorf("creating AES cipher: %w", err) + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return nil, fmt.Errorf("creating GCM: %w", err) + } + if len(nonce) != gcm.NonceSize() { + return nil, fmt.Errorf("nonce is %d bytes; expected %d", len(nonce), gcm.NonceSize()) + } + plain, err := gcm.Open(nil, nonce, ciphertext, nil) + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrCiphertextTampered, err) + } + return plain, nil +} + +// Fingerprint returns the 16-hex-char SHA-256 prefix of plaintext. This is +// NOT a security boundary — it is audit-disambiguation only ("is this the same +// key as last week?"). It is computationally irreversible (nfr-design-specs §3.6). +func Fingerprint(plaintext []byte) string { + sum := sha256.Sum256(plaintext) + return hex.EncodeToString(sum[:8]) // 8 bytes = 16 hex chars +} + +// StoreCredential encrypts plaintext, inserts a credentials row, and marks the +// previous active row of the same kind as rotated (sets rotated_at=now). All in +// one transaction (NFR-SEC-03 rotation procedure, nfr-design-specs §3.5). +// +// expiresAt is set for installation_token rows (restart resilience, BR-CRED-08); +// pass a zero time for keys/PATs (NULL expires_at). +// +// Returns the new row's ID. The caller emits the CREDENTIAL_STORED or +// CREDENTIAL_ROTATED audit event (U-11) — this helper does NOT audit directly +// (separation: credstore does crypto + persistence; the audit layer is above). +func (c *Credstore) StoreCredential(kind string, plaintext []byte, expiresAt time.Time) (int64, error) { + if c.db == nil { + return 0, fmt.Errorf("credstore: db is nil (cannot store credential)") + } + ciphertext, nonce, err := c.Encrypt(plaintext) + if err != nil { + return 0, fmt.Errorf("encrypting %s: %w", kind, err) + } + fp := Fingerprint(plaintext) + + tx, err := c.db.Begin() + if err != nil { + return 0, fmt.Errorf("beginning credential store tx: %w", err) + } + + // Mark previous active row rotated. + if _, err := tx.Exec( + `UPDATE credentials SET rotated_at = CURRENT_TIMESTAMP WHERE kind = ? AND rotated_at IS NULL`, + kind, + ); err != nil { + tx.Rollback() + return 0, fmt.Errorf("rotating previous %s: %w", kind, err) + } + + var expires interface{} + if !expiresAt.IsZero() { + expires = expiresAt + } + res, err := tx.Exec( + `INSERT INTO credentials (kind, fingerprint, ciphertext, nonce, expires_at, created_at) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`, + kind, fp, ciphertext, nonce, expires, + ) + if err != nil { + tx.Rollback() + return 0, fmt.Errorf("inserting %s credential: %w", kind, err) + } + id, _ := res.LastInsertId() + if err := tx.Commit(); err != nil { + return 0, fmt.Errorf("committing credential store tx: %w", err) + } + return id, nil +} + +// LoadActiveCredential returns the decrypted plaintext of the active (rotated_at +// IS NULL, and for installation_token expires_at > now) credential of the given +// kind. Returns ErrNoActiveCredential if none exists. +func (c *Credstore) LoadActiveCredential(kind string) ([]byte, error) { + if c.db == nil { + return nil, fmt.Errorf("credstore: db is nil (cannot load credential)") + } + var ciphertext, nonce []byte + var expiresAt sql.NullTime + err := c.db.QueryRow( + `SELECT ciphertext, nonce, expires_at FROM credentials + WHERE kind = ? AND rotated_at IS NULL + ORDER BY id DESC LIMIT 1`, + kind, + ).Scan(&ciphertext, &nonce, &expiresAt) + if err == sql.ErrNoRows { + return nil, ErrNoActiveCredential + } + if err != nil { + return nil, fmt.Errorf("loading active %s: %w", kind, err) + } + // For installation tokens, refuse an expired persisted token. + if kind == CredKindInstallationToken && expiresAt.Valid && time.Now().After(expiresAt.Time) { + return nil, ErrNoActiveCredential + } + return c.Decrypt(ciphertext, nonce) +} + +// LoadInstallationToken returns the persisted installation token if not expired +// (BR-CRED-08 restart resilience). Returns ErrNoActiveCredential if missing/expired. +func (c *Credstore) LoadInstallationToken() (string, error) { + plain, err := c.LoadActiveCredential(CredKindInstallationToken) + if err != nil { + return "", err + } + return string(plain), nil +} + +// LoadAppPrivateKey returns the active App private key (PEM bytes). +func (c *Credstore) LoadAppPrivateKey() ([]byte, error) { + return c.LoadActiveCredential(CredKindAppPrivateKey) +} + +// LoadPAT returns the active PAT (fallback auth, FR-AUTH-02). +func (c *Credstore) LoadPAT() (string, error) { + plain, err := c.LoadActiveCredential(CredKindPAT) + if err != nil { + return "", err + } + return string(plain), nil +} + +// HasPAT reports whether a PAT is stored (used to decide whether PAT fallback +// can engage — nfr-design-specs §4.3, ADR-09). +func (c *Credstore) HasPAT() bool { + _, err := c.LoadPAT() + return err == nil +} + +// StoreInstallationToken persists a freshly-exchanged installation token with +// its GitHub-reported expiry. Called by the token cache on every exchange +// (nfr-design-specs §4.1). +func (c *Credstore) StoreInstallationToken(token string, expiresAt time.Time) error { + _, err := c.StoreCredential(CredKindInstallationToken, []byte(token), expiresAt) + return err +} + +// StoreAppPrivateKey persists the App private key (PEM). Called by +// `devteam auth rotate-key` (NFR-SEC-03, nfr-design-specs §3.5). +func (c *Credstore) StoreAppPrivateKey(pemBytes []byte) error { + _, err := c.StoreCredential(CredKindAppPrivateKey, pemBytes, time.Time{}) + return err +} + +// StorePAT persists a PAT (read from stdin by `devteam auth store-pat`, +// nfr-design-specs §11 finding 6). +func (c *Credstore) StorePAT(pat string) error { + _, err := c.StoreCredential(CredKindPAT, []byte(pat), time.Time{}) + return err +} \ No newline at end of file diff --git a/internal/github/errors.go b/internal/github/errors.go new file mode 100644 index 0000000..c17d407 --- /dev/null +++ b/internal/github/errors.go @@ -0,0 +1,92 @@ +package github + +import ( + "errors" + "fmt" +) + +// AuthErrorCode is the typed enum for auth-family failures (ADR-12, BR-AUTH-04). +// Callers branch via errors.As(err, &authErr) then switch authErr.Code — no +// string parsing. The CLI's W-10 block formatter (cmd/devteam/auth.go) does +// exactly this (nfr-design-specs §5.1). +type AuthErrorCode string + +const ( + // ErrCodeInstallationNotFound: 404 from token exchange — the App installation + // was revoked (nfr-design-specs §4.3, ADR-09). PAT fallback NOT engaged. + ErrCodeInstallationNotFound AuthErrorCode = "installation_not_found" + // ErrCodeInstallationSuspended: 403 — org admin suspended the installation. + ErrCodeInstallationSuspended AuthErrorCode = "installation_suspended" + // ErrCodeKeyRejected: 401 from token exchange — bad JWT / bad App key. + ErrCodeKeyRejected AuthErrorCode = "key_rejected" + // ErrCodeKeyFileMissing: master key or App key file not found at the configured path. + ErrCodeKeyFileMissing AuthErrorCode = "key_file_missing" + // ErrCodeKeyFileInvalid: master key file not 32 bytes, or App key not valid PEM. + ErrCodeKeyFileInvalid AuthErrorCode = "key_file_invalid" + // ErrCodePATFallbackExhausted: primary auth failed (token-expiry-class) AND no + // PAT is configured (nfr-design-specs §4.3). + ErrCodePATFallbackExhausted AuthErrorCode = "pat_fallback_exhausted" + // ErrCodeCiphertextTampered: GCM tag mismatch — ciphertext modified or master + // key does not match (NFR-SEC-02 key-loss path). + ErrCodeCiphertextTampered AuthErrorCode = "ciphertext_tampered" + // ErrCodeGhCLINotFound: provider=gh AND gh not on PATH (NFR-PORT-03). + ErrCodeGhCLINotFound AuthErrorCode = "gh_cli_not_found" +) + +// RunbookSection maps each code to a runbook section pointer (BR-AUTH-05). +// The CLI formats this into the W-10 block: "see docs/github-app-setup.md §N". +func (c AuthErrorCode) RunbookSection() string { + switch c { + case ErrCodeInstallationNotFound, ErrCodeInstallationSuspended: + return "§10" + case ErrCodeKeyRejected: + return "§9" + case ErrCodeKeyFileMissing, ErrCodeKeyFileInvalid: + return "§3" + case ErrCodePATFallbackExhausted: + return "§8" + case ErrCodeCiphertextTampered: + return "§7.4" + case ErrCodeGhCLINotFound: + return "§11" + default: + return "§11" + } +} + +// AuthError is the typed error for auth-family failures (ADR-12). Callers use +// errors.As to extract the Code and format the runbook pointer. The Error() +// string includes the runbook reference so a bare log of the error still +// points the operator at the fix (NFR-OPS-01). +type AuthError struct { + Code AuthErrorCode + Message string + RunbookSection string // e.g. "§10"; if empty, derived from Code +} + +func (e *AuthError) Error() string { + section := e.RunbookSection + if section == "" { + section = e.Code.RunbookSection() + } + return fmt.Sprintf("%s: %s (see docs/github-app-setup.md %s)", e.Code, e.Message, section) +} + +// authErrorFromCode is a constructor used by NativeClient/GhCLIClient to build +// a typed error with a message, deriving the runbook section from the code. +func authErrorFromCode(code AuthErrorCode, message string) *AuthError { + return &AuthError{ + Code: code, + Message: message, + RunbookSection: code.RunbookSection(), + } +} + +// IsAuthError reports whether err is an *AuthError and returns it if so. +func IsAuthError(err error) (*AuthError, bool) { + var ae *AuthError + if errors.As(err, &ae) { + return ae, true + } + return nil, false +} \ No newline at end of file diff --git a/internal/github/ghcli.go b/internal/github/ghcli.go new file mode 100644 index 0000000..714dd52 --- /dev/null +++ b/internal/github/ghcli.go @@ -0,0 +1,148 @@ +package github + +import ( + "context" + "fmt" + "os/exec" + "strings" +) + +// GhCLIClient implements GitHubClient by delegating the four PR ops to the +// existing gh-CLI shelling behavior (ADR-02, ADR-03, U-03). It is a fallback, +// not a parallel implementation — the gh-free run path is the feature's goal +// (C-05, FR-PR-05), and this adapter exists so the operator can revert to the +// pre-feature behavior without a code change (provider: gh in config). +// +// Byte-identical legacy behavior (ADR-03, FR-IFACE-03): CLI args, stdout +// parsing, error wrapping, opaque-output treatment are preserved verbatim +// from internal/gitops/client.go. The fragile GetPRNumber string-parse is +// preserved ("do not improve" — RE §3.2 anti-pattern 3). +// +// Net-new methods (AuthHealthCheck, ListRepositories, GetMergeableState, +// CreateBranch) return ErrUnsupported (ADR-08) — the adapter is honest about +// its limits. +type GhCLIClient struct { + baseDir string // cmd.Dir for gh subprocesses +} + +// NewGhCLIClient constructs the fallback adapter. The baseDir is the worktree +// root for gh subprocess cwd (matches the legacy gitops.GitClient.baseDir). +func NewGhCLIClient(cfg Config) (*GhCLIClient, error) { + return &GhCLIClient{baseDir: cfg.BaseDir}, nil +} + +// AuthHealthCheck returns ErrUnsupported (ADR-08). The gh adapter does not +// back discovery/auth-health — those require provider: native. +func (g *GhCLIClient) AuthHealthCheck(ctx context.Context) error { + // But we DO check gh is on PATH (NFR-PORT-03): if the operator set + // provider: gh but gh is absent, fail with a typed error pointing at §11. + if _, err := exec.LookPath("gh"); err != nil { + return authErrorFromCode(ErrCodeGhCLINotFound, + "provider: gh requires the gh CLI on PATH; either install gh or set github.provider=native") + } + return ErrUnsupported +} + +// ListRepositories returns ErrUnsupported (ADR-08). +func (g *GhCLIClient) ListRepositories(ctx context.Context) ([]Repository, error) { + return nil, ErrUnsupported +} + +// GetMergeableState returns ErrUnsupported (ADR-08). +func (g *GhCLIClient) GetMergeableState(ctx context.Context, repo RepoRef, number int64) (MergeableState, error) { + return MergeableUnknown, ErrUnsupported +} + +// CreateBranch returns ErrUnsupported (ADR-08) — the gh adapter does not back +// the native branch-creation path. +func (g *GhCLIClient) CreateBranch(ctx context.Context, repo RepoRef, branch, from string) error { + return ErrUnsupported +} + +// CreatePR delegates to `gh pr create` with the caller-supplied base + draft +// (ADR-05 — the adapter parameterizes the previously-hard-coded --base main / +// --draft). Empty base falls back to "main" (C-11, FR-PR-02 main fallback). +// +// Byte-identical to pre-refactor internal/gitops.GitClient.CreatePullRequest +// except base/draft are now params (the I-03 fix). Output parsing preserved. +func (g *GhCLIClient) CreatePR(ctx context.Context, repo RepoRef, base, head, title, body string, draft bool) (*PRRef, error) { + if base == "" { + base = "main" + } + args := []string{"pr", "create", "--base", base, "--head", head, "--title", title, "--body", body} + if draft { + args = append(args, "--draft") + } + cmd := exec.CommandContext(ctx, "gh", args...) + cmd.Dir = g.baseDir + out, err := cmd.CombinedOutput() + if err != nil { + return nil, redactTokenURLs(fmt.Errorf("creating PR: %s: %w", string(out), err)) + } + url := strings.TrimSpace(string(out)) + // Extract PR number from the URL (gh returns the web URL; parse the trailing /pull/N). + number := parsePRNumberFromURL(url) + return &PRRef{Repo: repo, Number: number, URL: url}, nil +} + +// ReadyPR delegates to `gh pr ready` (FR-PR-03). The legacy ReadyPullRequest +// took a branch; the interface takes a number (ADR-11). The adapter bridges +// by calling `gh pr ready ` (gh accepts the number form). +func (g *GhCLIClient) ReadyPR(ctx context.Context, repo RepoRef, number int64) error { + cmd := exec.CommandContext(ctx, "gh", "pr", "ready", fmt.Sprintf("%d", number)) + cmd.Dir = g.baseDir + out, err := cmd.CombinedOutput() + if err != nil { + return redactTokenURLs(fmt.Errorf("marking PR ready: %s: %w", string(out), err)) + } + return nil +} + +// CommentPR delegates to `gh pr comment --body ` (FR-PR-04). +// Byte-identical to the legacy AddPullRequestComment (which looked up the +// number first via GetPRNumber; the interface takes the number directly). +func (g *GhCLIClient) CommentPR(ctx context.Context, repo RepoRef, number int64, body string) error { + cmd := exec.CommandContext(ctx, "gh", "pr", "comment", fmt.Sprintf("%d", number), "--body", body) + cmd.Dir = g.baseDir + out, err := cmd.CombinedOutput() + if err != nil { + return redactTokenURLs(fmt.Errorf("commenting on PR: %s: %w", string(out), err)) + } + return nil +} + +// GetPRNumberByBranch is a GhCLIClient-specific helper (NOT on the interface) +// used by the legacy gitops.GitClient bridge (ADR-11, ADR-14). It preserves the +// fragile `gh pr list --head --json number --limit 1` string-parse +// verbatim ("do not improve" — ADR-03, RE §3.2 anti-pattern 3). +func (g *GhCLIClient) GetPRNumberByBranch(ctx context.Context, branch string) (int64, error) { + cmd := exec.CommandContext(ctx, "gh", "pr", "list", "--head", branch, "--json", "number", "--limit", "1") + cmd.Dir = g.baseDir + out, err := cmd.CombinedOutput() + if err != nil { + return 0, redactTokenURLs(fmt.Errorf("finding PR for %s: %s: %w", branch, string(out), err)) + } + lines := strings.Split(strings.TrimSpace(string(out)), "\n") + if len(lines) == 0 { + return 0, fmt.Errorf("no PR found for branch %s", branch) + } + parts := strings.Split(lines[0], ":") + if len(parts) < 2 { + return 0, fmt.Errorf("unexpected PR list format: %s", lines[0]) + } + var n int64 + fmt.Sscanf(strings.TrimSpace(parts[1]), "%d", &n) + return n, nil +} + +// parsePRNumberFromURL extracts the trailing /pull/ from a GitHub PR URL. +// gh's `pr create` returns the web URL; we parse the number for the PRRef. +func parsePRNumberFromURL(url string) int64 { + idx := strings.LastIndex(url, "/pull/") + if idx < 0 { + return 0 + } + var n int64 + fmt.Sscanf(url[idx+len("/pull/"):], "%d", &n) + return n +} \ No newline at end of file diff --git a/internal/github/imports_test.go b/internal/github/imports_test.go new file mode 100644 index 0000000..4bc5608 --- /dev/null +++ b/internal/github/imports_test.go @@ -0,0 +1,102 @@ +package github + +import ( + "os" + "os/exec" + "strings" + "testing" +) + +// TestADR18_NoExternalGitHubImportsOutsideThisPackage enforces the build +// invariant (ADR-18): internal/github/ is the SOLE importer of google/go-github +// and golang.org/x/oauth2. No package outside internal/github/ may import +// either library — this keeps the GitHub-API boundary machine-checked, not +// convention-checked (nfr-design-specs §6.2, FR-IFACE-02). +// +// Per nfr-design-specs §3.1 refinement, x/crypto is NOT imported by this +// feature (AES-GCM uses stdlib), so it is NOT checked here — there is no +// x/crypto import to be the sole importer of. +// +// The test runs `go list -deps ./...` and asserts the forbidden imports appear +// only in packages under internal/github/. It skips if go is not on PATH +// (NFR-COMPAT-01 — the test environment may not have the toolchain). +func TestADR18_NoExternalGitHubImportsOutsideThisPackage(t *testing.T) { + goPath, err := exec.LookPath("go") + if err != nil { + t.Skip("go not on PATH; skipping ADR-18 import-invariant test") + } + + // Run `go list -deps -f '{{.ImportPath}} {{.Imports}}' ./...` from the + // repo root. We use the module root (two dirs up from internal/github). + cmd := exec.Command(goPath, "list", "-deps", "-f", "{{.ImportPath}}\t{{.Imports}}", "./...") + cmd.Dir = "../.." // internal/github → repo root + out, err := cmd.Output() + if err != nil { + t.Skipf("go list failed (module not resolvable?): %v; skipping", err) + } + + forbidden := []string{ + "github.com/google/go-github", + "golang.org/x/oauth2", + } + + for _, line := range strings.Split(string(out), "\n") { + if line == "" { + continue + } + parts := strings.SplitN(line, "\t", 2) + if len(parts) != 2 { + continue + } + pkg := parts[0] + imports := parts[1] + + // Skip the library packages themselves and their subpackages. + if strings.HasPrefix(pkg, "github.com/google/go-github") || + strings.HasPrefix(pkg, "golang.org/x/oauth2") { + continue + } + // Skip our own package — it IS the sole importer. + if strings.Contains(pkg, "github.com/MichielDean/devteam/internal/github") { + continue + } + // Skip non-devteam packages (stdlib, third-party deps of deps). + if !strings.HasPrefix(pkg, "github.com/MichielDean/devteam") { + continue + } + + for _, f := range forbidden { + if strings.Contains(imports, f) { + t.Errorf("ADR-18 violation: package %s imports %s (only internal/github/ may)", pkg, f) + } + } + } +} + +// TestNoOSExecInNativeClientFiles enforces NFR-PORT-02: the NativeClient files +// must NOT import os/exec (the gh-free run path). Only ghcli.go (the adapter) +// may import os/exec. This is the precise mechanism (nfr-design-specs §6.2). +func TestNoOSExecInNativeClientFiles(t *testing.T) { + nativeFiles := []string{ + "native.go", + "auth.go", + "token_cache.go", + "pr_ops.go", + "mergeable.go", + "credstore.go", + "redaction.go", + "errors.go", + "client.go", + "types.go", + "repos.go", + } + for _, f := range nativeFiles { + data, err := os.ReadFile(f) + if err != nil { + continue // file may not exist in this build + } + if strings.Contains(string(data), `"os/exec"`) { + t.Errorf("NFR-PORT-02 violation: %s imports os/exec (only ghcli.go may)", f) + } + } +} \ No newline at end of file diff --git a/internal/github/mergeable.go b/internal/github/mergeable.go new file mode 100644 index 0000000..4095b31 --- /dev/null +++ b/internal/github/mergeable.go @@ -0,0 +1,81 @@ +package github + +import ( + "context" + "fmt" + "time" + + "github.com/google/go-github/v66/github" +) + +// GetMergeableState returns the PR's mergeability, polling with bounded +// exponential backoff when GitHub reports `null`/`unknown` (FR-CONFLICT-02, +// ADR-07, U-09). The poll loop is encapsulated INSIDE this method (ADR-07): +// the caller sees only the final state + diagnostic. +// +// Bounds (nc.pollMaxRetries, nc.pollMaxDuration) are constructor config +// (NFR-PERF-02, defaults 5 / 60s, hard ceilings 10 / 300s enforced at config +// load). On exhaustion: return MergeableUnknown + diagnostic — NEVER +// silently Mergeable (R-09, F-6 invariant, ADR-07). +// +// context.Context cancellation is honored mid-poll (the select on ctx.Done() +// during the backoff sleep). +func (nc *NativeClient) GetMergeableState(ctx context.Context, repo RepoRef, number int64) (MergeableState, error) { + c, err := nc.ensureClientWithFreshToken(ctx) + if err != nil { + return MergeableUnknown, err + } + + var lastSeen string + deadline := time.Now().Add(nc.pollMaxDuration) + backoff := 1 * time.Second + const backoffCap = 5 * time.Second + + for attempt := 0; attempt < nc.pollMaxRetries; attempt++ { + pr, _, err := c.PullRequests.Get(ctx, repo.Owner, repo.Name, int(number)) + if err != nil { + return MergeableUnknown, redactTokenURLs(fmt.Errorf("GetMergeableState %s/%s#%d: %w", repo.Owner, repo.Name, number, err)) + } + state := pr.GetMergeableState() + lastSeen = state + switch state { + case "clean", "has_hooks": + return Mergeable, nil + case "dirty", "blocked": + return Conflicting, nil + case "behind": + // "behind" means the PR needs rebase — treat as conflicting for the + // pipeline's halt decision (the operator must rebase before merge). + return Conflicting, nil + case "unstable": + // "unstable" means status checks are running — poll again (GitHub + // hasn't reached a definitive mergeable state). + } + // state == "" (null) or "unknown" → poll. + + // Check deadline before sleeping. + if time.Now().After(deadline) { + return MergeableUnknown, fmt.Errorf("mergeable_state polling exhausted after %d retries / %s; last seen state: %q", + attempt+1, time.Since(deadline.Add(-nc.pollMaxDuration)).Round(time.Second), lastSeen) + } + + // Sleep with ctx cancellation. + select { + case <-ctx.Done(): + return MergeableUnknown, ctx.Err() + case <-time.After(backoff): + } + if backoff < backoffCap { + backoff *= 2 + if backoff > backoffCap { + backoff = backoffCap + } + } + } + + return MergeableUnknown, fmt.Errorf("mergeable_state polling exhausted after %d retries / %s; last seen state: %q", + nc.pollMaxRetries, nc.pollMaxDuration, lastSeen) +} + +// _ keeps the github import used even if the API surface narrows. +var _ = github.String \ No newline at end of file diff --git a/internal/github/native.go b/internal/github/native.go new file mode 100644 index 0000000..ccafe6d --- /dev/null +++ b/internal/github/native.go @@ -0,0 +1,262 @@ +package github + +import ( + "context" + "fmt" + "net/http" + "os" + "strings" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/google/go-github/v66/github" + "golang.org/x/oauth2" +) + +// NativeClient implements GitHubClient using google/go-github (ADR-02, U-02). +// It is the default provider and has no dependency on the gh CLI binary +// (FR-IFACE-02, NFR-PORT-02). All GitHub API access goes through this client +// or the GhCLIClient fallback adapter — never both for the same method. +// +// Auth model (ADR-10): the App private key is read from the credstore on JWT +// mint, NOT at construction. Key rotation = file replace + next JWT mint uses +// the new key (no restart, no code change — F-8, NFR-SEC-03). +type NativeClient struct { + appID int64 + installationID int64 + privateKeyPath string + credstore *Credstore + tokenCache *tokenCache + httpClient *http.Client // transport for go-github (oauth2-injected token) + client *github.Client // the go-github wrapper + patFallback bool + pollMaxRetries int + pollMaxDuration time.Duration +} + +// NewNativeClient constructs a NativeClient (U-02). The App private key is NOT +// read here — it is read on the first JWT mint (ADR-10). A nil credstore is +// allowed only in test paths; production requires a credstore for key + token +// persistence (FR-CRED-03). +func NewNativeClient(cfg Config) (*NativeClient, error) { + if cfg.AppID == 0 || cfg.InstallationID == 0 { + return nil, fmt.Errorf("native client: app_id and installation_id are required") + } + if cfg.PrivateKeyPath == "" { + return nil, fmt.Errorf("native client: private_key_path is required") + } + if cfg.Credstore == nil { + return nil, fmt.Errorf("native client: credstore is required (master key not loaded?)") + } + ttl := cfg.TokenCacheTTL + if ttl == 0 { + ttl = 9 * time.Minute + } + pollRetries := cfg.ConflictPollMaxRetries + if pollRetries == 0 { + pollRetries = 5 + } + pollDur := cfg.ConflictPollMaxDuration + if pollDur == 0 { + pollDur = 60 * time.Second + } + + // Start with a plain HTTP client; the oauth2-token-injected transport is + // built on the first getToken (after token exchange). This is lazy: we + // don't exchange at construction so a misconfigured-but-not-yet-called + // client doesn't fail construction. + nc := &NativeClient{ + appID: cfg.AppID, + installationID: cfg.InstallationID, + privateKeyPath: cfg.PrivateKeyPath, + credstore: cfg.Credstore, + tokenCache: newTokenCache(ttl), + patFallback: cfg.PATFallbackEnabled, + pollMaxRetries: pollRetries, + pollMaxDuration: pollDur, + } + nc.httpClient = &http.Client{Timeout: 30 * time.Second} + nc.client = github.NewClient(nc.httpClient) + return nc, nil +} + +// clientWithToken returns a go-github client wired to use the given token. +// We rebuild the client on token refresh (the oauth2 transport caches the +// token; rebuilding swaps it cleanly without mutating a shared transport). +func (nc *NativeClient) clientWithToken(token string) *github.Client { + ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}) + tc := oauth2.NewClient(context.Background(), ts) + tc.Timeout = 30 * time.Second + return github.NewClient(tc) +} + +// AuthHealthCheck verifies the identity is alive (FR-AUTH-04, ADR-15). +// nil = alive. On failure returns *AuthError with Code + RunbookSection +// (ADR-12). The check issues ONE lightweight API call (GET /app or +// /installation/repositories?per_page=1) to confirm the token is valid. +func (nc *NativeClient) AuthHealthCheck(ctx context.Context) error { + token, err := nc.getToken(ctx) + if err != nil { + return redactTokenURLs(err) + } + c := nc.clientWithToken(token) + // Lightweight probe: list 1 repo from the installation. + _, resp, err := c.Apps.ListRepos(ctx, &github.ListOptions{PerPage: 1}) + if err != nil { + return redactTokenURLs(nc.classifyAPIError(resp, err, "auth health check")) + } + return nil +} + +// TokenProvenance returns the cache's provenance string for the CLI's +// `token source:` line (US-01, ADR-06). This is a *NativeClient-specific method, +// NOT on the interface — the CLI type-asserts to call it. +func (nc *NativeClient) TokenProvenance(ctx context.Context) (string, error) { + if _, err := nc.getToken(ctx); err != nil { + return "", redactTokenURLs(err) + } + return nc.tokenCache.provenance(), nil +} + +// AppID returns the configured GitHub App ID (CLI display, US-01). +func (nc *NativeClient) AppID() int64 { return nc.appID } + +// InstallationID returns the configured installation ID (CLI display, US-01). +func (nc *NativeClient) InstallationID() int64 { return nc.installationID } + +// getToken returns a valid installation token, exchanging/refreshing as needed +// (nfr-design-specs §4.2, BR-CRED-07). Never returns a stale token past TTL. +func (nc *NativeClient) getToken(ctx context.Context) (string, error) { + // 1. Cache hit (fresh)? + if tok, ok := nc.tokenCache.get(); ok { + return tok, nil + } + // 2. Persisted fallback (restart resilience, BR-CRED-08)? + if persisted, err := nc.credstore.LoadInstallationToken(); err == nil && persisted != "" { + // Validate it via a lightweight call? No — we trust the expires_at check + // done in LoadActiveCredential. Populate cache with a short TTL so the + // next getToken refreshes properly. We don't know the exact expiry from + // the string alone, so set cache TTL to the configured TTL (the refresh + // goroutine will mint a fresh one before this one expires). + nc.tokenCache.set(persisted, "re-exchanged", nc.tokenCache.ttl) + return persisted, nil + } + // 3. Cold path: mint JWT → exchange for installation token. + tok, expiresAt, err := nc.exchangeInstallationToken(ctx) + if err != nil { + // 4. PAT fallback (only on token-expiry-class failures, ADR-09). + if nc.patFallback && nc.credstore.HasPAT() { + pat, perr := nc.credstore.LoadPAT() + if perr == nil && pat != "" { + nc.tokenCache.set(pat, "fallback (PAT)", nc.tokenCache.ttl) + return pat, nil + } + } + return "", err + } + nc.tokenCache.set(tok, "refreshed", time.Until(expiresAt)) + // Persist for restart resilience. + _ = nc.credstore.StoreInstallationToken(tok, expiresAt) + return tok, nil +} + +// exchangeInstallationToken mints a JWT from the App private key (read on-demand, +// ADR-10) and exchanges it for an installation token via +// POST /app/installations/{id}/access_tokens (FR-AUTH-01). +func (nc *NativeClient) exchangeInstallationToken(ctx context.Context) (token string, expiresAt time.Time, err error) { + // Read the App private key on-demand (ADR-10 — key rotation = file replace, + // next mint uses the new key, no restart). + pemBytes, err := os.ReadFile(nc.privateKeyPath) + if err != nil { + return "", time.Time{}, authErrorFromCode(ErrCodeKeyFileMissing, + fmt.Sprintf("private key file not readable at %s: %v", nc.privateKeyPath, err)) + } + // Validate PEM. + if !strings.Contains(string(pemBytes), "PRIVATE KEY") { + return "", time.Time{}, authErrorFromCode(ErrCodeKeyFileInvalid, + fmt.Sprintf("file at %s is not a PEM private key", nc.privateKeyPath)) + } + + // Mint JWT (RS256, App ID, 10-min expiry). + jwtTok, err := mintAppJWT(nc.appID, pemBytes) + if err != nil { + return "", time.Time{}, authErrorFromCode(ErrCodeKeyRejected, + fmt.Sprintf("minting App JWT: %v", err)) + } + + // Exchange JWT for installation token via go-github. + jwtClient := oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: jwtTok})) + jwtClient.Timeout = 30 * time.Second + appClient := github.NewClient(jwtClient) + + tok, resp, err := appClient.Apps.CreateInstallationToken(ctx, nc.installationID, nil) + if err != nil { + return "", time.Time{}, nc.classifyAPIError(resp, err, "token exchange") + } + if tok == nil || tok.GetToken() == "" { + return "", time.Time{}, authErrorFromCode(ErrCodeKeyRejected, "token exchange returned empty token") + } + expires := tok.GetExpiresAt() + if expires.IsZero() { + // GitHub default: 1 hour from now. go-github's Timestamp wraps time.Time. + expires = github.Timestamp{Time: time.Now().Add(60 * time.Minute)} + } + return tok.GetToken(), expires.Time, nil +} + +// mintAppJWT builds the RS256-signed App JWT (GitHub App auth, FR-AUTH-01). +// The JWT is valid for 10 minutes (GitHub's max); issued-at now, expires now+10m. +func mintAppJWT(appID int64, pemBytes []byte) (string, error) { + key, err := jwt.ParseRSAPrivateKeyFromPEM(pemBytes) + if err != nil { + return "", fmt.Errorf("parsing PEM: %w", err) + } + now := time.Now() + claims := jwt.RegisteredClaims{ + Issuer: fmt.Sprintf("%d", appID), + IssuedAt: jwt.NewNumericDate(now.Add(-60 * time.Second)), // clock skew tolerance + ExpiresAt: jwt.NewNumericDate(now.Add(10 * time.Minute)), + } + tok := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) + signed, err := tok.SignedString(key) + if err != nil { + return "", fmt.Errorf("signing JWT: %w", err) + } + return signed, nil +} + +// classifyAPIError maps a go-github API error to an *AuthError by status code +// (ADR-09, nfr-design-specs §4.3). 404/403 surface loudly (no PAT fallback); 401 +// is key-rejected; 5xx/timeout are token-expiry-class (PAT fallback engages +// upstream in getToken). Non-auth errors pass through wrapped + redacted. +func (nc *NativeClient) classifyAPIError(resp *github.Response, err error, op string) error { + if resp == nil { + // Network error / no response — token-expiry-class. The caller (getToken) + // decides on PAT fallback; here we return a generic auth error. + return authErrorFromCode(ErrCodePATFallbackExhausted, + fmt.Sprintf("%s: network error: %v", op, err)) + } + switch resp.StatusCode { + case 401: + return authErrorFromCode(ErrCodeKeyRejected, + fmt.Sprintf("%s: 401 — App private key rejected (rotate key: devteam auth rotate-key)", op)) + case 403: + return authErrorFromCode(ErrCodeInstallationSuspended, + fmt.Sprintf("%s: 403 — installation #%d suspended by org admin", op, nc.installationID)) + case 404: + return authErrorFromCode(ErrCodeInstallationNotFound, + fmt.Sprintf("%s: 404 — installation #%d not reachable (revoked?)", op, nc.installationID)) + default: + return fmt.Errorf("%s: %w", op, err) + } +} + +// ensureClientWithFreshToken is the helper called before each API method to +// guarantee the embedded client has a fresh token. Returns the client to use. +func (nc *NativeClient) ensureClientWithFreshToken(ctx context.Context) (*github.Client, error) { + tok, err := nc.getToken(ctx) + if err != nil { + return nil, redactTokenURLs(err) + } + return nc.clientWithToken(tok), nil +} \ No newline at end of file diff --git a/internal/github/pr_ops.go b/internal/github/pr_ops.go new file mode 100644 index 0000000..d82a073 --- /dev/null +++ b/internal/github/pr_ops.go @@ -0,0 +1,159 @@ +package github + +import ( + "context" + "fmt" + "strings" + + "github.com/google/go-github/v66/github" +) + +// CreateBranch creates a branch on the remote repo via the GitHub git refs API +// (FR-PR-01). `from` is the source ref (e.g. "main" or a full SHA); the new +// branch points at from's current HEAD. +func (nc *NativeClient) CreateBranch(ctx context.Context, repo RepoRef, branch, from string) error { + c, err := nc.ensureClientWithFreshToken(ctx) + if err != nil { + return err + } + // Resolve `from` to a SHA. If it's already a 40-char hex, use it directly; + // otherwise treat it as a branch name and resolve via the branch endpoint. + var sha string + if isFullSHA(from) { + sha = from + } else { + br, _, err := c.Repositories.GetBranch(ctx, repo.Owner, repo.Name, from, 10) + if err != nil { + return redactTokenURLs(fmt.Errorf("CreateBranch: resolving source branch %s: %w", from, err)) + } + sha = br.GetCommit().GetSHA() + } + ref := "refs/heads/" + branch + _, _, err = c.Git.CreateRef(ctx, repo.Owner, repo.Name, &github.Reference{ + Ref: &ref, + Object: &github.GitObject{ + SHA: &sha, + }, + }) + if err != nil { + return redactTokenURLs(fmt.Errorf("CreateBranch: creating %s from %s: %w", branch, from, err)) + } + return nil +} + +// CreatePR creates a pull request targeting `base` (FR-PR-02). `base` and +// `draft` are caller-supplied (ADR-05); the helpers resolveBase/resolveDraft +// read repo_settings and pass the resolved values. Empty base → "main" +// fallback (C-11, I-03 fix). +func (nc *NativeClient) CreatePR(ctx context.Context, repo RepoRef, base, head, title, body string, draft bool) (*PRRef, error) { + if base == "" { + base = "main" + } + c, err := nc.ensureClientWithFreshToken(ctx) + if err != nil { + return nil, err + } + newPR := &github.NewPullRequest{ + Base: &base, + Head: &head, + Title: &title, + Body: &body, + Draft: &draft, + } + pr, _, err := c.PullRequests.Create(ctx, repo.Owner, repo.Name, newPR) + if err != nil { + return nil, redactTokenURLs(fmt.Errorf("CreatePR on %s/%s (base=%s head=%s): %w", repo.Owner, repo.Name, base, head, err)) + } + return &PRRef{ + Repo: repo, + Number: int64(pr.GetNumber()), + URL: pr.GetHTMLURL(), + }, nil +} + +// ReadyPR transitions a draft PR to ready-for-review (FR-PR-03) via +// PATCH /repos/{owner}/{repo}/pulls/{pr} with draft=false. +func (nc *NativeClient) ReadyPR(ctx context.Context, repo RepoRef, number int64) error { + c, err := nc.ensureClientWithFreshToken(ctx) + if err != nil { + return err + } + _, _, err = c.PullRequests.Edit(ctx, repo.Owner, repo.Name, int(number), &github.PullRequest{ + Draft: github.Bool(false), + }) + if err != nil { + return redactTokenURLs(fmt.Errorf("ReadyPR %s/%s#%d: %w", repo.Owner, repo.Name, number, err)) + } + return nil +} + +// CommentPR posts a comment on a PR (FR-PR-04) via +// POST /repos/{owner}/{repo}/pulls/{pr}/comments. +func (nc *NativeClient) CommentPR(ctx context.Context, repo RepoRef, number int64, body string) error { + c, err := nc.ensureClientWithFreshToken(ctx) + if err != nil { + return err + } + _, _, err = c.Issues.CreateComment(ctx, repo.Owner, repo.Name, int(number), &github.IssueComment{ + Body: &body, + }) + if err != nil { + return redactTokenURLs(fmt.Errorf("CommentPR %s/%s#%d: %w", repo.Owner, repo.Name, number, err)) + } + return nil +} + +// isFullSHA reports whether s is a 40-char lowercase hex SHA. +func isFullSHA(s string) bool { + if len(s) != 40 { + return false + } + for _, c := range s { + if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) { + return false + } + } + return true +} + +// resolveBase reads repo_settings.default_branch for the given repo; empty +// (no settings row) → "main" (C-11, FR-PR-02 main fallback). Used by the +// pipeline's PR-creation helper (U-08 pr_helpers.go conceptually; inlined here +// for the NativeClient path because the helper needs the DB + repo ID). +// +// This is a thin wrapper; the SettingsReader (repos.go) is the actual DB +// reader. We keep it here so NativeClient stays self-contained for the +// gh-free run path (NFR-PORT-02) without a separate settings dependency. +func resolveBase(settings *SettingsReader, repo RepoRef) string { + if settings == nil { + return "main" + } + if b := settings.DefaultBranch(repo); b != "" { + return b + } + return "main" +} + +// resolveDraft reads repo_settings.pr_draft_default; no settings row → true +// (matches the legacy `--draft` default, I-03). +func resolveDraft(settings *SettingsReader, repo RepoRef) bool { + if settings == nil { + return true + } + return settings.PrDraftDefault(repo) +} + +// CreatePRWithSettings is the pipeline-facing PR creator that resolves base + +// draft from repo_settings before calling CreatePR (ADR-05, FR-PR-02). The +// interface's CreatePR takes explicit base/draft; this helper is the policy +// site that reads settings. The pipeline calls this, not CreatePR directly, +// when per-repo settings should apply (the gh-free run path, U-08). +func (nc *NativeClient) CreatePRWithSettings(ctx context.Context, settings *SettingsReader, repo RepoRef, head, title, body string) (*PRRef, error) { + base := resolveBase(settings, repo) + draft := resolveDraft(settings, repo) + return nc.CreatePR(ctx, repo, base, head, title, body, draft) +} + +// _ is a placeholder to keep the imports used if the helpers above reference +// strings only minimally (avoids "imported and not used" in some build paths). +var _ = strings.TrimSpace \ No newline at end of file diff --git a/internal/github/redaction.go b/internal/github/redaction.go new file mode 100644 index 0000000..26a5c96 --- /dev/null +++ b/internal/github/redaction.go @@ -0,0 +1,88 @@ +package github + +import ( + "io" + "regexp" +) + +// redactTokenURLs scrubs token-bearing URLs and bare token prefixes from an +// error string before it crosses the package boundary (ADR-12, CR-03, +// FR-AUDIT-05, nfr-design-specs §2.2). +// +// Patterns scrubbed: +// - https://@github.com/... → https://[redacted]@github.com/... +// ( matches [^/@]+ — covers PATs, oauth tokens, installation tokens) +// - token= query params → token=[redacted] +// - bare ghp_..., gho_..., ghs_... PAT/token prefixes (defense in depth) +// +// Idempotent (nfr-design-specs §2.2): applying twice is identical to once. +// +// Error-chain preservation: the redacted message replaces the outermost error +// message; the underlying error chain (errors.Is/As) is preserved by wrapping +// with %w on the original error. The redacted string is the new message. +func redactTokenURLs(err error) error { + if err == nil { + return nil + } + // Build a new error with the redacted message but wrapping the original + // to preserve errors.Is/As. We use fmt.Errorf with %w on a sentinel that + // carries the redacted string. + redacted := redactString(err.Error()) + return &redactedError{msg: redacted, cause: err} +} + +// redactedError carries a redacted message while preserving the error chain +// for errors.Is/As (nfr-design-specs §2.2 — "wraps with fmt.Errorf %w to +// preserve unwrapping"). We use a custom type instead of fmt.Errorf because +// %w requires the arg to be an error, and we want to REPLACE the message +// while keeping the chain. +type redactedError struct { + msg string + cause error +} + +func (e *redactedError) Error() string { return e.msg } +func (e *redactedError) Unwrap() error { return e.cause } + +// redactString is the string-form redaction used by the audit-details writer +// and the log sanitizer (nfr-design-specs §2.4, BR-AUDIT-01/04). +func redactString(s string) string { + s = tokenURLRe.ReplaceAllString(s, "https://[redacted]@github.com") + s = tokenQueryRe.ReplaceAllString(s, "token=[redacted]") + s = ghpPrefixRe.ReplaceAllString(s, "ghp_[redacted]") + s = ghoPrefixRe.ReplaceAllString(s, "gho_[redacted]") + s = ghsPrefixRe.ReplaceAllString(s, "ghs_[redacted]") + return s +} + +var ( + // https://@github.com/... — is [^/@]+ (non-slash, non-at). + tokenURLRe = regexp.MustCompile(`https://[^/@]+@github\.com`) + // token= query parameter. + tokenQueryRe = regexp.MustCompile(`token=[^&\s]+`) + // Bare PAT prefixes (defense in depth — these appear in some error families). + ghpPrefixRe = regexp.MustCompile(`ghp_[A-Za-z0-9]{20,}`) + ghoPrefixRe = regexp.MustCompile(`gho_[A-Za-z0-9]{20,}`) + ghsPrefixRe = regexp.MustCompile(`ghs_[A-Za-z0-9]{20,}`) +) + +// redactWriter is an io.Writer wrapper that scrubs each Write call through +// redactString before forwarding (nfr-design-specs §2.3, Layer 2 log sanitizer). +// Wired in cmd/devteam/main.go startup after config load. +type redactWriter struct { + w io.Writer +} + +// NewRedactWriter wraps w so all writes are scrubbed of token-bearing strings. +func NewRedactWriter(w io.Writer) io.Writer { + return &redactWriter{w: w} +} + +func (rw *redactWriter) Write(p []byte) (int, error) { + cleaned := redactString(string(p)) + _, err := rw.w.Write([]byte(cleaned)) + if err != nil { + return 0, err + } + return len(p), nil // report the original length so callers don't loop +} \ No newline at end of file diff --git a/internal/github/repos.go b/internal/github/repos.go new file mode 100644 index 0000000..0773f3a --- /dev/null +++ b/internal/github/repos.go @@ -0,0 +1,140 @@ +package github + +import ( + "context" + "database/sql" + "fmt" + + "github.com/google/go-github/v66/github" +) + +// ListRepositories discovers the repos the GitHub App installation can access +// (FR-DISC-01, U-04). Calls GET /installation/repositories, returns []Repository +// (domain type, ADR-04) filtered to the configured installation (C-09 single- +// installation MVP — FR-DISC-03). +// +// The caller (the pipeline or `devteam repo list`) persists the result to +// repo_registry via RepoRegistryStore; this method is the API read only. +func (nc *NativeClient) ListRepositories(ctx context.Context) ([]Repository, error) { + c, err := nc.ensureClientWithFreshToken(ctx) + if err != nil { + return nil, err + } + var out []Repository + opts := &github.ListOptions{PerPage: 100} + for { + repos, resp, err := c.Apps.ListRepos(ctx, opts) + if err != nil { + return nil, redactTokenURLs(fmt.Errorf("ListRepositories: %w", err)) + } + for _, r := range repos.Repositories { + out = append(out, Repository{ + Ref: RepoRef{ + Owner: r.GetOwner().GetLogin(), + Name: r.GetName(), + }, + DefaultBranch: r.GetDefaultBranch(), + InstallationID: nc.installationID, + }) + } + if resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + return out, nil +} + +// SettingsReader is a concrete struct (ADR-13), DB-backed, read by +// NativeClient (resolveBase/resolveDraft) and config loaders (U-07 +// materialization). Tests use a real test-DB-backed SettingsReader or +// construct one with a mock *sql.DB (the existing internal/db/ pattern). +// +// NOT an interface — single implementation, no premature abstraction +// (principle 4, ADR-13). If Phase 2 adds a cache, the struct becomes an +// interface then; the change is localized. +// +// Callers pass a *SettingsReader (pointer) so nil can represent "no settings +// available" (the resolveBase/resolveDraft fallback path). +type SettingsReader struct { + db *sql.DB +} + +// NewSettingsReader constructs a DB-backed *SettingsReader. +func NewSettingsReader(db *sql.DB) *SettingsReader { + return &SettingsReader{db: db} +} + +// DefaultBranch returns the per-repo default_branch from repo_settings, +// or "" if no settings row exists (the caller applies the "main" fallback). +func (sr *SettingsReader) DefaultBranch(repo RepoRef) string { + if sr == nil || sr.db == nil { + return "" + } + var b string + err := sr.db.QueryRow( + `SELECT s.default_branch FROM repo_settings s + JOIN repo_registry r ON r.id = s.repo_registry_id + WHERE r.owner = ? AND r.name = ?`, + repo.Owner, repo.Name, + ).Scan(&b) + if err != nil { + return "" + } + return b +} + +// PrDraftDefault returns the per-repo pr_draft_default (true if no settings row). +func (sr *SettingsReader) PrDraftDefault(repo RepoRef) bool { + if sr == nil || sr.db == nil { + return true + } + var v int + err := sr.db.QueryRow( + `SELECT s.pr_draft_default FROM repo_settings s + JOIN repo_registry r ON r.id = s.repo_registry_id + WHERE r.owner = ? AND r.name = ?`, + repo.Owner, repo.Name, + ).Scan(&v) + if err != nil { + return true + } + return v == 1 +} + +// ConflictDetectionEnabled returns whether conflict detection is on for a repo. +func (sr *SettingsReader) ConflictDetectionEnabled(repo RepoRef) bool { + if sr == nil || sr.db == nil { + return true + } + var v int + err := sr.db.QueryRow( + `SELECT s.conflict_detection_enabled FROM repo_settings s + JOIN repo_registry r ON r.id = s.repo_registry_id + WHERE r.owner = ? AND r.name = ?`, + repo.Owner, repo.Name, + ).Scan(&v) + if err != nil { + return true + } + return v == 1 +} + +// Provider returns the per-repo provider override ("native"|"gh") or "" if +// no override (global provider applies — FR-SETTINGS-05, ADR-17). +func (sr *SettingsReader) Provider(repo RepoRef) string { + if sr == nil || sr.db == nil { + return "" + } + var p string + err := sr.db.QueryRow( + `SELECT s.provider FROM repo_settings s + JOIN repo_registry r ON r.id = s.repo_registry_id + WHERE r.owner = ? AND r.name = ?`, + repo.Owner, repo.Name, + ).Scan(&p) + if err != nil { + return "" + } + return p +} \ No newline at end of file diff --git a/internal/github/token_cache.go b/internal/github/token_cache.go new file mode 100644 index 0000000..8a0ac28 --- /dev/null +++ b/internal/github/token_cache.go @@ -0,0 +1,69 @@ +package github + +import ( + "sync" + "time" +) + +// tokenCache is the in-process installation-token cache (nfr-design-specs §4.1). +// It holds the plaintext token guarded by mu. The token is short-lived +// (GitHub's 60-minute installation-token expiry); the cache TTL is strictly +// less than that (default 9m, FR-AUTH-03). +// +// Never use a stale token past TTL (BR-CRED-07): getToken checks +// time.Now().Before(expiresAt) before returning; if false, it re-exchanges. +type tokenCache struct { + mu sync.RWMutex + token string + expiresAt time.Time + refreshedAt time.Time + prov string // "cached" | "refreshed" | "fallback (PAT)" | "re-exchanged" + ttl time.Duration +} + +func newTokenCache(ttl time.Duration) *tokenCache { + return &tokenCache{ttl: ttl} +} + +// get returns the token if fresh (time.Now() before expiresAt). ok=false if +// expired or never set. +func (tc *tokenCache) get() (string, bool) { + tc.mu.RLock() + defer tc.mu.RUnlock() + if tc.token == "" || time.Now().After(tc.expiresAt) { + return "", false + } + // Return "cached" provenance on a hit (US-01). + return tc.token, true +} + +// set populates the cache with a token + provenance. ttl is either the +// configured TTL or time.Until(expiresAt), whichever is shorter (so a token +// returned with 7m of life doesn't get a 9m cache entry that outlives it). +func (tc *tokenCache) set(token, provenance string, ttl time.Duration) { + tc.mu.Lock() + defer tc.mu.Unlock() + tc.token = token + tc.refreshedAt = time.Now() + tc.expiresAt = time.Now().Add(ttl) + tc.prov = provenance +} + +// provenance returns the current provenance string ("cached" on a hit, +// "refreshed" after exchange, "fallback (PAT)" after PAT fallback — US-01). +// It downgrades to "cached" if the token was set more than 0s ago (the first +// read after a set returns the set-time provenance; subsequent reads return +// "cached" — interaction-spec §8.1). +func (tc *tokenCache) provenance() string { + tc.mu.RLock() + defer tc.mu.RUnlock() + if tc.prov == "" { + return "cached" + } + // If the set was recent (within 1s), report the set-time provenance; + // otherwise report "cached" (the operator sees "cached" on a warm call). + if time.Since(tc.refreshedAt) < time.Second { + return tc.prov + } + return "cached" +} \ No newline at end of file diff --git a/internal/github/types.go b/internal/github/types.go new file mode 100644 index 0000000..8ca515e --- /dev/null +++ b/internal/github/types.go @@ -0,0 +1,74 @@ +package github + +import ( + "time" +) + +// Config carries the resolved github: block values for client construction +// (feature github-authorization-integration, U-01). The config loader +// (internal/config) validates these; this struct is the construction-time +// shape passed to NewClient and the concrete constructors. +type Config struct { + Provider string // "native" (default) | "gh" + AppID int64 // GitHub App ID + InstallationID int64 // App installation ID + PrivateKeyPath string // path to App private key PEM (NOT the master key) + TokenCacheTTL time.Duration // < 60m; default 9m + PATFallbackEnabled bool // FR-AUTH-02; PAT stored via `devteam auth store-pat` + ConflictPollMaxRetries int // NFR-PERF-02; default 5, ceiling 10 + ConflictPollMaxDuration time.Duration // NFR-PERF-02; default 60s, ceiling 300s + BaseDir string // worktree base dir (for GhCLIClient's cmd.Dir) + Credstore *Credstore // for NativeClient key/token read+persist; nil for GhCLIClient +} + +// RepoRef identifies a repository by owner + name (ADR-04 domain type). +// Callers construct this; it does not carry installation or settings state. +type RepoRef struct { + Owner string + Name string +} + +// Repository is the discovery result (FR-DISC-01, ADR-04). Carries only the +// fields the feature needs — no leaky abstraction of go-github's full struct. +type Repository struct { + Ref RepoRef + DefaultBranch string + InstallationID int64 +} + +// PRRef identifies a pull request (ADR-04). URL is the human-readable web URL +// returned by CreatePR; Number is the API identifier for subsequent ops. +type PRRef struct { + Repo RepoRef + Number int64 + URL string +} + +// MergeableState is the typed enum for a PR's mergeability (FR-CONFLICT-01, +// ADR-07). The third value, MergeableUnknown, is returned when the poll bound +// is exhausted — it is NEVER silently promoted to Mergeable (R-09, F-6). +type MergeableState int + +const ( + // Mergeable means GitHub reports the PR can be merged cleanly. + Mergeable MergeableState = iota + // Conflicting means GitHub reports the PR has merge conflicts. + Conflicting + // MergeableUnknown means the poll bound was exhausted before GitHub + // returned a definitive state. The pipeline treats this as "needs + // investigation" and halts (interaction-spec §6.2, US-05 criterion 3). + MergeableUnknown +) + +// String returns the lowercase string form used in banners and CLI output +// (interaction-spec §8.4: "mergeable", "conflicting", "unknown"). +func (m MergeableState) String() string { + switch m { + case Mergeable: + return "mergeable" + case Conflicting: + return "conflicting" + default: + return "unknown" + } +} \ No newline at end of file diff --git a/internal/gitops/client.go b/internal/gitops/client.go index 96faabc..15581dd 100644 --- a/internal/gitops/client.go +++ b/internal/gitops/client.go @@ -1,19 +1,66 @@ package gitops import ( + "context" "fmt" "os/exec" "strings" + + "github.com/MichielDean/devteam/internal/github" ) +// GitClient owns local-git operations (clone, branch, commit, push) AND +// bridges the legacy string-based PR-method signatures to the new +// internal/github.GitHubClient interface (feature github-authorization-integration, +// U-05, ADR-14, FR-IFACE-05). +// +// The local-git methods (CreateBranch, StageAll, Commit, Push, CommitAndPush, +// CurrentBranch, HasRemoteBranch, HasStagedChanges, Run) are UNCHANGED +// (C-02, FR-PR-06, NFR-COMPAT-03) — they shell to `git`, not `gh`. +// +// The PR methods (CreatePullRequest, ReadyPullRequest, AddPullRequestComment, +// GetPRNumber) keep their legacy string-based signatures (C-01, R-03) but now +// delegate to the injected ghClient GitHubClient (the interface), not to `gh` +// directly. The interface uses int64 PR numbers + RepoRef; the legacy methods +// bridge by resolving repo + settings + number internally, then calling the +// interface (ADR-14). +// +// A nil ghClient means the bridge is not wired (the pipeline sets it after +// construction); the PR methods return an error in that case (fail-fast, not +// a silent fallback to gh shelling — the gh-free run path is the goal). type GitClient struct { - baseDir string + baseDir string + ghClient github.GitHubClient } +// NewGitClient constructs a GitClient with local-git ops only (the legacy +// constructor, preserved for existing callers — pipeline.go's three injection +// sites). The PR methods will fail with "GitHubClient not wired" until +// SetGitHubClient is called. func NewGitClient(baseDir string) *GitClient { return &GitClient{baseDir: baseDir} } +// NewGitClientWithGitHub constructs a GitClient with the GitHubClient interface +// injected (the post-feature constructor). The pipeline uses this when the +// github: config block is present (FR-IFACE-06). +func NewGitClientWithGitHub(baseDir string, ghClient github.GitHubClient) *GitClient { + return &GitClient{baseDir: baseDir, ghClient: ghClient} +} + +// SetGitHubClient injects the GitHubClient after construction (used by the +// pipeline when it resolves the client from config after the fact — the three +// NewGitClient(baseDir) sites in pipeline.go). +func (g *GitClient) SetGitHubClient(gh github.GitHubClient) { + g.ghClient = gh +} + +// GitHubClient returns the injected GitHubClient (or nil — the pipeline checks +// before calling PR methods). +func (g *GitClient) GitHubClient() github.GitHubClient { + return g.ghClient +} + func (g *GitClient) run(args ...string) (string, error) { cmd := exec.Command("git", args...) cmd.Dir = g.baseDir @@ -97,62 +144,114 @@ func (g *GitClient) Push(branch string) error { } func (g *GitClient) CreatePullRequest(branch string, title string, body string) (string, error) { - cmd := exec.Command("gh", "pr", "create", - "--base", "main", - "--head", branch, - "--title", title, - "--body", body, - "--draft", - ) - cmd.Dir = g.baseDir - out, err := cmd.CombinedOutput() + if g.ghClient == nil { + return "", fmt.Errorf("GitHubClient not wired (set github: config block or call SetGitHubClient); see docs/github-app-setup.md") + } + repo, err := g.resolveRepoRef() if err != nil { - return "", fmt.Errorf("creating PR: %s: %w", string(out), err) + return "", err } - url := strings.TrimSpace(string(out)) - return url, nil + // Legacy behavior: --base main, --draft (ADR-14 — the bridge preserves the + // legacy defaults; per-repo settings override is the NativeClient's job via + // CreatePRWithSettings, not this legacy bridge). + prRef, err := g.ghClient.CreatePR(context.Background(), repo, "main", branch, title, body, true) + if err != nil { + return "", err + } + if prRef == nil { + return "", fmt.Errorf("CreatePR returned nil PRRef") + } + return prRef.URL, nil } func (g *GitClient) ReadyPullRequest(branch string) error { - cmd := exec.Command("gh", "pr", "ready", branch) - cmd.Dir = g.baseDir - out, err := cmd.CombinedOutput() + if g.ghClient == nil { + return fmt.Errorf("GitHubClient not wired (set github: config block or call SetGitHubClient); see docs/github-app-setup.md") + } + repo, err := g.resolveRepoRef() if err != nil { - return fmt.Errorf("marking PR ready: %s: %w", string(out), err) + return err } - return nil + // Legacy ReadyPullRequest takes a branch; the interface takes a number + // (ADR-11). Bridge: look up the number by branch via the gh adapter's + // helper if available, else fail. + ghAdapter, ok := g.ghClient.(*github.GhCLIClient) + if !ok { + return fmt.Errorf("ReadyPullRequest(branch) bridge requires *GhCLIClient; for NativeClient use ReadyPR(ctx, repo, number) directly") + } + number, err := ghAdapter.GetPRNumberByBranch(context.Background(), branch) + if err != nil { + return err + } + return g.ghClient.ReadyPR(context.Background(), repo, number) } func (g *GitClient) AddPullRequestComment(branch string, comment string) error { - prNumber, err := g.GetPRNumber(branch) + if g.ghClient == nil { + return fmt.Errorf("GitHubClient not wired (set github: config block or call SetGitHubClient); see docs/github-app-setup.md") + } + repo, err := g.resolveRepoRef() if err != nil { return err } - cmd := exec.Command("gh", "pr", "comment", prNumber, "--body", comment) - cmd.Dir = g.baseDir - out, err := cmd.CombinedOutput() + prNumber, err := g.GetPRNumber(branch) if err != nil { - return fmt.Errorf("commenting on PR: %s: %w", string(out), err) + return err } - return nil + var number int64 + fmt.Sscanf(prNumber, "%d", &number) + return g.ghClient.CommentPR(context.Background(), repo, number, comment) } func (g *GitClient) GetPRNumber(branch string) (string, error) { - cmd := exec.Command("gh", "pr", "list", "--head", branch, "--json", "number", "--limit", "1") - cmd.Dir = g.baseDir - out, err := cmd.CombinedOutput() + if g.ghClient == nil { + return "", fmt.Errorf("GitHubClient not wired (set github: config block or call SetGitHubClient); see docs/github-app-setup.md") + } + // Preserve the fragile string-parse verbatim for the GhCLIClient path + // (ADR-03 "do not improve"). For NativeClient, there's no branch→number + // lookup in MVP — the kanban-view path that uses this is gh-adapter-only. + ghAdapter, ok := g.ghClient.(*github.GhCLIClient) + if !ok { + return "", fmt.Errorf("GetPRNumber(branch) bridge requires *GhCLIClient; for NativeClient the PR number is returned by CreatePR directly") + } + number, err := ghAdapter.GetPRNumberByBranch(context.Background(), branch) if err != nil { - return "", fmt.Errorf("finding PR for %s: %s: %w", branch, string(out), err) + return "", err } - lines := strings.Split(strings.TrimSpace(string(out)), "\n") - if len(lines) == 0 { - return "", fmt.Errorf("no PR found for branch %s", branch) + return fmt.Sprintf("%d", number), nil +} + +// resolveRepoRef derives the RepoRef (owner/name) from the worktree's git remote. +// This is the bridge from the legacy string-based signatures (which take only a +// branch) to the interface's typed RepoRef (ADR-14). It reads `git remote -v` +// to extract the GitHub owner/repo. +func (g *GitClient) resolveRepoRef() (github.RepoRef, error) { + out, err := g.run("remote", "get-url", "origin") + if err != nil { + return github.RepoRef{}, fmt.Errorf("resolving origin remote: %s: %w", strings.TrimSpace(out), err) + } + url := strings.TrimSpace(out) + return parseGitHubURL(url), nil +} + +// parseGitHubURL extracts owner/name from a GitHub remote URL (SSH or HTTPS). +func parseGitHubURL(url string) github.RepoRef { + // SSH: git@github.com:owner/name.git + // HTTPS: https://github.com/owner/name.git + var rest string + if i := strings.Index(url, "github.com"); i >= 0 { + rest = url[i+len("github.com"):] + } else { + return github.RepoRef{} } - parts := strings.Split(lines[0], ":") - if len(parts) < 2 { - return "", fmt.Errorf("unexpected PR list format: %s", lines[0]) + rest = strings.TrimPrefix(rest, ":") + rest = strings.TrimPrefix(rest, "/") + rest = strings.TrimSuffix(rest, ".git") + parts := strings.SplitN(rest, "/", 2) + if len(parts) != 2 { + return github.RepoRef{} } - return strings.TrimSpace(parts[1]), nil + return github.RepoRef{Owner: parts[0], Name: parts[1]} } func (g *GitClient) CommitAndPush(branch string, message string) error { diff --git a/internal/pipeline/pipeline.go b/internal/pipeline/pipeline.go index 3ef92f6..3e48542 100644 --- a/internal/pipeline/pipeline.go +++ b/internal/pipeline/pipeline.go @@ -12,6 +12,7 @@ import ( "github.com/MichielDean/devteam/internal/config" "github.com/MichielDean/devteam/internal/db" "github.com/MichielDean/devteam/internal/feature" + "github.com/MichielDean/devteam/internal/github" "github.com/MichielDean/devteam/internal/gitops" "github.com/MichielDean/devteam/internal/repo" "github.com/MichielDean/devteam/internal/role" @@ -35,6 +36,8 @@ type Pipeline struct { dispatcher *role.Dispatcher questionStore feature.QuestionStore gitClient *gitops.GitClient + ghClient github.GitHubClient // feature github-authorization-integration; nil = not wired (pre-feature behavior) + credstore *github.Credstore // nil when the github: block is absent or master key not loadable repoManager *repo.Manager database *db.DB sessionMgr *SessionManager @@ -101,6 +104,57 @@ func (p *Pipeline) SetDatabase(database *db.DB) { p.providerStore = config.NewProviderStore(database) p.tierStore = config.NewTierStore(database) p.configMerger = config.NewConfigMerger(p.providerStore) + // Wire the GitHubClient from config now that the DB is available (the + // credstore needs the DB). Feature github-authorization-integration, FR-IFACE-06. + // If the github: block is absent, this is a no-op (pre-feature behavior). + p.wireGitHubClient() +} + +// wireGitHubClient constructs the GitHubClient from the config github: block +// and injects it into gitClient (FR-IFACE-06). Called from SetDatabase after +// the DB is open (the credstore needs it). If the block is absent or the +// master key isn't loadable, ghClient stays nil and the gitClient's PR +// methods fail with "GitHubClient not wired" — pre-feature behavior is +// preserved (NFR-COMPAT-03). +func (p *Pipeline) wireGitHubClient() { + if p.config == nil { + // Tests may construct a Pipeline without config; guard against nil. + return + } + gcfg := p.config.GitHub + if gcfg.AppID == 0 && gcfg.Provider == "" { + // Feature not configured. Skip silently (the pipeline still works + // for everything that doesn't touch GitHub API ops). + return + } + // Try to load the credstore (master key). If it fails, log and skip — + // the pipeline should still run for non-GitHub work. + credstore, err := github.NewCredstore(p.database.Conn()) + if err != nil { + log.Printf("pipeline: github: credstore not loaded (master key unavailable): %v", err) + return + } + p.credstore = credstore + baseDir := p.specProvider.BaseDir() + ghCfg := github.Config{ + Provider: gcfg.Provider, + AppID: gcfg.AppID, + InstallationID: gcfg.InstallationID, + PrivateKeyPath: gcfg.PrivateKeyPath, + TokenCacheTTL: gcfg.TokenCacheTTL, + PATFallbackEnabled: gcfg.PATFallback.Enabled, + ConflictPollMaxRetries: gcfg.ConflictPollMaxRetries, + ConflictPollMaxDuration: gcfg.ConflictPollMaxDuration, + BaseDir: baseDir, + Credstore: credstore, + } + ghClient, err := github.NewClient(ghCfg) + if err != nil { + log.Printf("pipeline: github: client construction failed: %v", err) + return + } + p.ghClient = ghClient + p.gitClient.SetGitHubClient(ghClient) } func (p *Pipeline) SetQuestionStore(qs feature.QuestionStore) { diff --git a/internal/pipeline/stage_runner.go b/internal/pipeline/stage_runner.go index 8cc54ea..fa3f3d8 100644 --- a/internal/pipeline/stage_runner.go +++ b/internal/pipeline/stage_runner.go @@ -626,6 +626,21 @@ func (p *Pipeline) AdvanceStage(f *feature.Feature, currentStageID string) error if p.sessionMgr != nil { p.sessionMgr.CompletePhaseSessions(f.ID, oldStageDef.Phase) } + // Auth-health check at the phase boundary (feature github-authorization-integration, + // ADR-15, FR-AUTH-04). A revoked installation must halt the pipeline at the + // phase boundary, never mid-phase (F-7 invariant — the phase boundary is the + // half-write blast-radius boundary). If the github: block is absent (ghClient + // nil), this is a no-op (pre-feature behavior preserved). + if p.ghClient != nil { + if err := p.ghClient.AuthHealthCheck(context.Background()); err != nil { + log.Printf("AdvanceStage: auth-health check failed at phase boundary (%s→%s) for %s: %v", + oldStageDef.Phase, newStageDef.Phase, f.ID, err) + p.database.RecordAuditEvent(f.ID, "AUTH_HEALTH_FAILED", "", newStageDef.Phase, + fmt.Sprintf("phase boundary auth check failed: %v", err)) + return fmt.Errorf("auth precondition failed at phase boundary (%s→%s): %w; see docs/github-app-setup.md", + oldStageDef.Phase, newStageDef.Phase, err) + } + } // Push impl repo changes for the completed phase if err := p.PushPhaseChanges(f, oldStageDef.Phase); err != nil { log.Printf("AdvanceStage: failed to push phase changes for %s: %v", oldStageDef.Phase, err) diff --git a/repos.yaml b/repos.yaml index b152939..2901f11 100644 --- a/repos.yaml +++ b/repos.yaml @@ -1,5 +1,18 @@ # Repository Registry - +# +# DEPRECATED (feature github-authorization-integration, FR-DISC-05): +# The canonical repo registry is now the `repo_registry` table in Postgres, +# populated by `devteam repo list` (discovery) and `devteam repo manage ` +# (curation). This root repos.yaml is now the SEED file: on first startup with +# an empty repo_registry, its entries are loaded into the DB (managed=1) and +# the DB becomes the source of truth. Thereafter this file is generated from +# the DB on each materialization (do not hand-edit it — your edits will be +# overwritten on next startup; use `devteam repo set` / `devteam repo manage`). +# +# The schema is unchanged (yaml.v3 ignores the new managed/provider/default_branch +# fields in the generated overlay). `config.LoadRepos` continues to parse this +# file for backward compatibility (no live main-branch caller breaks — RE §6.1). +# # Maps feature specs to the implementation repos they touch. # Each feature declares which repos are in scope. # Implementation repos get a .devteam/ pointer back to the central spec.