-
Notifications
You must be signed in to change notification settings - Fork 383
feat: add secret helper #6223
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat: add secret helper #6223
Changes from 3 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
47d2dc8
feat: add internal secret helper
mnkiefer 5d1235a
Merge branch 'main' into token-getter
mnkiefer 10c2185
make fmt
mnkiefer 29e40a7
recompile
mnkiefer fd46058
Update internal/tools/ghsecret/main.go
mnkiefer e91c967
Update docs/src/content/docs/reference/tokens.md
mnkiefer e83c891
fix: add missing cobra import to tokens_bootstrap.go (#6233)
Copilot 3268caa
Merge branch 'main' into token-getter
mnkiefer 6ad5d49
Merge branch 'main' into token-getter
mnkiefer cc60e30
use go-gh package
mnkiefer 64f0bf0
refactor: migrate ghsecret to 'gh aw secret set' subcommand
mnkiefer 907bd59
enhance token management with engine-specific recommendations and opt…
mnkiefer 7fe09a3
feat: enhance tokens bootstrap command with repository owner and name…
mnkiefer 3d7a039
integrated secret mgt into the gh aw init flow and updated install.md
mnkiefer 4eb436e
Merge branch 'main' into token-getter
mnkiefer 1c7c165
make fmt
mnkiefer 68606c0
fix tests to include new parameters
mnkiefer b3954a6
Merge branch 'main' into token-getter
mnkiefer 883c384
Merge branch 'main' into token-getter
mnkiefer 2b3c52f
give owner/repo defaults
mnkiefer b9d6bdb
Merge branch 'main' into token-getter
mnkiefer ca13f6f
Merge branch 'main' into token-getter
mnkiefer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,236 @@ | ||
| package main | ||
|
mnkiefer marked this conversation as resolved.
Outdated
|
||
|
|
||
| import ( | ||
| "bufio" | ||
| "crypto/rand" | ||
| "encoding/base64" | ||
| "encoding/json" | ||
| "errors" | ||
| "flag" | ||
| "fmt" | ||
| "io" | ||
| "log" | ||
| "net/http" | ||
| "net/url" | ||
| "os" | ||
| "strings" | ||
|
|
||
| "golang.org/x/crypto/nacl/box" | ||
| ) | ||
|
|
||
| type repoPublicKey struct { | ||
| ID string `json:"key_id"` | ||
| Key string `json:"key"` | ||
| } | ||
|
|
||
| type secretPayload struct { | ||
| EncryptedValue string `json:"encrypted_value"` | ||
| KeyID string `json:"key_id"` | ||
| } | ||
|
|
||
| func main() { | ||
| var ( | ||
| flagOwner = flag.String("owner", "", "GitHub repository owner or organization") | ||
| flagRepo = flag.String("repo", "", "GitHub repository name") | ||
| flagSecretName = flag.String("secret", "", "Secret name to create or update") | ||
| flagValue = flag.String("value", "", "Secret value (if empty, read from stdin)") | ||
| flagValueEnv = flag.String("value-from-env", "", "Environment variable to read secret value from") | ||
| flagAPIBase = flag.String("api-url", "", "GitHub API base URL (default: https://api.github.com or $GITHUB_API_URL)") | ||
| ) | ||
|
|
||
| flag.Parse() | ||
|
|
||
| if *flagOwner == "" || *flagRepo == "" || *flagSecretName == "" { | ||
| flag.Usage() | ||
| os.Exit(1) | ||
| } | ||
|
|
||
| apiBase := resolveAPIBase(*flagAPIBase) | ||
| token, err := resolveToken() | ||
| if err != nil { | ||
| log.Fatalf("cannot resolve GitHub token: %v", err) | ||
| } | ||
|
|
||
| secretValue, err := resolveSecretValue(*flagValueEnv, *flagValue) | ||
| if err != nil { | ||
| log.Fatalf("cannot resolve secret value: %v", err) | ||
| } | ||
|
|
||
| if err := setRepoSecret(apiBase, token, *flagOwner, *flagRepo, *flagSecretName, secretValue); err != nil { | ||
| log.Fatalf("failed to set secret: %v", err) | ||
| } | ||
|
|
||
| fmt.Printf("Secret %s updated for %s/%s\n", *flagSecretName, *flagOwner, *flagRepo) | ||
| } | ||
|
|
||
| func resolveAPIBase(flagValue string) string { | ||
|
mnkiefer marked this conversation as resolved.
Outdated
|
||
| candidates := []string{ | ||
| strings.TrimSpace(flagValue), | ||
| strings.TrimSpace(os.Getenv("GITHUB_API_URL")), | ||
| } | ||
|
|
||
| for _, c := range candidates { | ||
| if c != "" { | ||
| return strings.TrimRight(c, "/") | ||
| } | ||
| } | ||
|
|
||
| return "https://api.github.com" | ||
| } | ||
|
|
||
| func resolveToken() (string, error) { | ||
| for _, name := range []string{"GITHUB_TOKEN", "GH_TOKEN"} { | ||
| if v := strings.TrimSpace(os.Getenv(name)); v != "" { | ||
| return v, nil | ||
| } | ||
| } | ||
| return "", errors.New("no token found; set GITHUB_TOKEN or GH_TOKEN") | ||
|
mnkiefer marked this conversation as resolved.
Outdated
|
||
| } | ||
|
|
||
| func resolveSecretValue(fromEnv, fromFlag string) (string, error) { | ||
| if fromEnv != "" { | ||
| v := os.Getenv(fromEnv) | ||
| if v == "" { | ||
| return "", fmt.Errorf("environment variable %s is not set or empty", fromEnv) | ||
| } | ||
| return v, nil | ||
| } | ||
|
|
||
| if fromFlag != "" { | ||
| return fromFlag, nil | ||
| } | ||
|
|
||
| info, err := os.Stdin.Stat() | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| if info.Mode()&os.ModeCharDevice != 0 { | ||
| fmt.Fprintln(os.Stderr, "Enter secret value, then press Ctrl+D:") | ||
| } | ||
|
|
||
| reader := bufio.NewReader(os.Stdin) | ||
| var b strings.Builder | ||
|
|
||
| for { | ||
| line, err := reader.ReadString('\n') | ||
| b.WriteString(line) | ||
| if err != nil { | ||
| if errors.Is(err, io.EOF) { | ||
| break | ||
| } | ||
| return "", err | ||
| } | ||
| } | ||
|
|
||
| value := strings.TrimRight(b.String(), "\r\n") | ||
| if value == "" { | ||
| return "", errors.New("secret value is empty") | ||
| } | ||
| return value, nil | ||
| } | ||
|
|
||
| func setRepoSecret(apiBase, token, owner, repo, name, value string) error { | ||
| pubKey, err := getRepoPublicKey(apiBase, token, owner, repo) | ||
| if err != nil { | ||
| return fmt.Errorf("get repo public key: %w", err) | ||
| } | ||
|
|
||
| encrypted, err := encryptWithPublicKey(pubKey.Key, value) | ||
| if err != nil { | ||
| return fmt.Errorf("encrypt secret: %w", err) | ||
| } | ||
|
|
||
| return putRepoSecret(apiBase, token, owner, repo, name, pubKey.ID, encrypted) | ||
| } | ||
|
|
||
| func getRepoPublicKey(apiBase, token, owner, repo string) (*repoPublicKey, error) { | ||
|
mnkiefer marked this conversation as resolved.
Outdated
|
||
| endpoint := fmt.Sprintf("%s/repos/%s/%s/actions/secrets/public-key", apiBase, owner, repo) | ||
|
|
||
| req, err := http.NewRequest(http.MethodGet, endpoint, nil) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| addGitHubHeaders(req, token) | ||
|
|
||
| resp, err := http.DefaultClient.Do(req) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| body, _ := io.ReadAll(resp.Body) | ||
| return nil, fmt.Errorf("GitHub API %s: %s", resp.Status, string(body)) | ||
| } | ||
|
|
||
| var key repoPublicKey | ||
| if err := json.NewDecoder(resp.Body).Decode(&key); err != nil { | ||
| return nil, err | ||
| } | ||
| if key.ID == "" || key.Key == "" { | ||
| return nil, errors.New("public key response missing key_id or key") | ||
| } | ||
| return &key, nil | ||
| } | ||
|
|
||
| func encryptWithPublicKey(publicKeyB64, plaintext string) (string, error) { | ||
| raw, err := base64.StdEncoding.DecodeString(publicKeyB64) | ||
| if err != nil { | ||
| return "", fmt.Errorf("decode public key: %w", err) | ||
| } | ||
| if len(raw) != 32 { | ||
| return "", fmt.Errorf("unexpected public key length: %d", len(raw)) | ||
| } | ||
|
|
||
| var pk [32]byte | ||
| copy(pk[:], raw) | ||
|
|
||
| ciphertext, err := box.SealAnonymous(nil, []byte(plaintext), &pk, rand.Reader) | ||
| if err != nil { | ||
| return "", fmt.Errorf("nacl encryption failed: %w", err) | ||
| } | ||
|
|
||
| return base64.StdEncoding.EncodeToString(ciphertext), nil | ||
| } | ||
|
|
||
| func putRepoSecret(apiBase, token, owner, repo, name, keyID, encryptedValue string) error { | ||
| endpoint := fmt.Sprintf("%s/repos/%s/%s/actions/secrets/%s", | ||
| apiBase, owner, repo, url.PathEscape(name)) | ||
|
|
||
| body, err := json.Marshal(secretPayload{ | ||
| EncryptedValue: encryptedValue, | ||
| KeyID: keyID, | ||
| }) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| req, err := http.NewRequest(http.MethodPut, endpoint, strings.NewReader(string(body))) | ||
|
mnkiefer marked this conversation as resolved.
Outdated
|
||
| if err != nil { | ||
| return err | ||
| } | ||
| addGitHubHeaders(req, token) | ||
| req.Header.Set("Content-Type", "application/json") | ||
|
|
||
| resp, err := http.DefaultClient.Do(req) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusCreated { | ||
| b, _ := io.ReadAll(resp.Body) | ||
| return fmt.Errorf("GitHub API %s: %s", resp.Status, string(b)) | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func addGitHubHeaders(req *http.Request, token string) { | ||
| req.Header.Set("Accept", "application/vnd.github+json") | ||
| req.Header.Set("Authorization", "Bearer "+token) | ||
| if req.Header.Get("X-GitHub-Api-Version") == "" { | ||
| req.Header.Set("X-GitHub-Api-Version", "2022-11-28") | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| package cli | ||
|
|
||
| import ( | ||
| "github.com/githubnext/gh-aw/pkg/logger" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| var tokensCommandLog = logger.New("cli:tokens") | ||
|
|
||
| // NewTokensCommand creates the main tokens command with subcommands | ||
| func NewTokensCommand() *cobra.Command { | ||
| tokensCommandLog.Print("Creating tokens command with subcommands") | ||
| cmd := &cobra.Command{ | ||
| Use: "tokens", | ||
| Short: "Inspect and bootstrap GitHub tokens for gh-aw", | ||
| Long: `Token utilities for GitHub Agentic Workflows. | ||
|
|
||
| Use this command to check which recommended secrets are configured | ||
| for the current repository and to see how to create them with | ||
| minimum required permissions.`, | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| return cmd.Help() | ||
| }, | ||
| } | ||
|
|
||
| // Add subcommands | ||
| cmd.AddCommand(NewTokensBootstrapSubcommand()) | ||
|
|
||
| return cmd | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.