Files
skillshare/internal/install/auth.go
T
Willie 1094668408 fix(install): keep git tokens out of process arguments (#566)
Token auth rewrote the clone URL with url.<user>:<token>@host.insteadOf.
git hands the rewritten URL to git-remote-https as an argument, so any
user on the machine could read the token with ps for as long as a clone
or fetch ran. Every platform token (GitHub, GitLab, Bitbucket, Azure
DevOps, Gitea, CNB) went through the same rewrite.

git now gets the token from a credential helper scoped to the host,
which reads it from SKILLSHARE_GIT_AUTH_PASSWORD; printf is a shell
builtin, so the token never reaches an argv. An empty helper entry
first clears the user's own helpers for that host, so git neither asks
their keychain nor erases from it on a 401, and no longer stores the
skillshare token there as the URL rewrite did.

An http.extraHeader was tried first and dropped: the header goes out
before any 401, so a stale token broke installs from public repos, and
after a rejection git fell back to the user's helper and erased their
stored credentials.

Refs #565
2026-10-14 13:36:09 +08:00

290 lines
8.8 KiB
Go

package install
import (
"fmt"
"net/url"
"os"
"strconv"
"strings"
)
// Platform represents a git hosting platform.
type Platform int
const (
PlatformUnknown Platform = iota
PlatformGitHub // github.com and GitHub Enterprise
PlatformGitLab // gitlab.com and self-hosted GitLab
PlatformBitbucket // bitbucket.org
PlatformAzureDevOps // dev.azure.com and visualstudio.com
PlatformCNB // cnb.cool and self-hosted CNB instances
PlatformGitea // gitea.com and self-hosted Gitea instances
)
// extractHost returns the hostname from a clone URL.
// Supports HTTPS (https://host/...) and SSH (git@host:...) formats.
func extractHost(cloneURL string) string {
s := strings.TrimSpace(cloneURL)
if s == "" {
return ""
}
// SSH: git@host:owner/repo.git
if strings.Contains(s, "@") && strings.Contains(s, ":") && !strings.Contains(s, "://") {
at := strings.Index(s, "@")
colon := strings.Index(s[at:], ":")
if colon > 0 {
return s[at+1 : at+colon]
}
}
// HTTPS or file://
u, err := url.Parse(s)
if err != nil || u.Host == "" {
return ""
}
return u.Hostname()
}
// detectPlatform identifies the git hosting platform from a clone URL.
func detectPlatform(cloneURL string) Platform {
host := strings.ToLower(extractHost(cloneURL))
if host == "" {
return PlatformUnknown
}
if isGitHubLikeHost(host) {
return PlatformGitHub
}
if strings.Contains(host, "gitlab") {
return PlatformGitLab
}
if strings.Contains(host, "bitbucket") {
return PlatformBitbucket
}
if host == "dev.azure.com" || host == "ssh.dev.azure.com" || strings.HasSuffix(host, ".visualstudio.com") {
return PlatformAzureDevOps
}
if strings.Contains(host, "cnb.cool") {
return PlatformCNB
}
if strings.Contains(host, "gitea") {
return PlatformGitea
}
return PlatformUnknown
}
// resolveToken looks up a token from environment variables based on the
// detected platform. Platform-specific vars take priority over the generic
// SKILLSHARE_GIT_TOKEN. Returns empty strings if no token is available or
// the URL is not HTTPS.
func resolveToken(cloneURL string) (token, username string) {
return resolveTokenWithOptions(cloneURL, nil, nil)
}
func resolveTokenWithOptions(cloneURL string, cnbHosts, giteaHosts []string) (token, username string) {
if !isHTTPS(cloneURL) {
return "", ""
}
platform := detectPlatformWithOptions(cloneURL, cnbHosts, giteaHosts)
switch platform {
case PlatformGitHub:
if t := os.Getenv("GITHUB_TOKEN"); t != "" {
return t, "x-access-token"
}
if t := os.Getenv("GH_TOKEN"); t != "" {
return t, "x-access-token"
}
case PlatformGitLab:
if t := os.Getenv("GITLAB_TOKEN"); t != "" {
return t, "oauth2"
}
case PlatformBitbucket:
if t := os.Getenv("BITBUCKET_TOKEN"); t != "" {
if u := os.Getenv("BITBUCKET_USERNAME"); u != "" {
return t, u
}
return t, "x-token-auth"
}
case PlatformAzureDevOps:
if t := os.Getenv("AZURE_DEVOPS_TOKEN"); t != "" {
return t, "x-access-token"
}
case PlatformCNB:
if t := os.Getenv("CNB_TOKEN"); t != "" {
return t, "cnb"
}
case PlatformGitea:
if t := os.Getenv("GITEA_TOKEN"); t != "" {
return t, "x-access-token"
}
}
// Generic fallback — use platform-appropriate username, or preserve
// existing URL username (e.g. https://myuser@host/... authenticates as myuser).
if t := os.Getenv("SKILLSHARE_GIT_TOKEN"); t != "" {
if u := urlUsername(cloneURL); u != "" {
return t, u
}
switch platform {
case PlatformGitLab:
return t, "oauth2"
case PlatformBitbucket:
return t, "x-token-auth"
default:
return t, "x-access-token"
}
}
return "", ""
}
// authEnv returns environment variables that give git the token through a
// credential helper set via GIT_CONFIG_COUNT/KEY/VALUE (Git 2.31+). The token
// itself travels only in SKILLSHARE_GIT_AUTH_PASSWORD, never in config or argv.
// If GIT_CONFIG_COUNT is already set in the environment, the new entries
// are appended at the next available index to avoid overriding existing
// git config entries (e.g. from CI pipelines).
// Returns nil for SSH/file URLs or when no token is available.
func authEnv(cloneURL string) []string {
return authEnvWithOptions(cloneURL, nil, nil)
}
func authEnvWithOptions(cloneURL string, cnbHosts, giteaHosts []string) []string {
token, username := resolveTokenWithOptions(cloneURL, cnbHosts, giteaHosts)
if token == "" {
return nil
}
host := extractHost(cloneURL)
if host == "" {
return nil
}
// Not an insteadOf URL rewrite: git passes the rewritten URL to
// git-remote-https as an argument, visible in ps (#565). Not an extraHeader:
// it is sent before any 401, so a stale token breaks public repos.
// The empty entry clears the user's helpers for this host, so git never
// asks their keychain or erases from it.
base := existingConfigCount()
key := fmt.Sprintf("credential.https://%s.helper", host)
return []string{
fmt.Sprintf("GIT_CONFIG_COUNT=%d", base+2),
fmt.Sprintf("GIT_CONFIG_KEY_%d=%s", base, key),
fmt.Sprintf("GIT_CONFIG_VALUE_%d=", base),
fmt.Sprintf("GIT_CONFIG_KEY_%d=%s", base+1, key),
fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", base+1, gitCredentialHelper),
gitAuthUsernameEnv + "=" + username,
gitAuthPasswordEnv + "=" + token,
}
}
const (
gitAuthUsernameEnv = "SKILLSHARE_GIT_AUTH_USERNAME"
gitAuthPasswordEnv = "SKILLSHARE_GIT_AUTH_PASSWORD"
// printf is a shell builtin, so the token never reaches a process argv.
gitCredentialHelper = `!f() { if [ "$1" = get ]; then printf 'username=%s\npassword=%s\n' "$` + gitAuthUsernameEnv + `" "$` + gitAuthPasswordEnv + `"; fi; }; f`
)
// AuthEnvForURL returns git auth injection env for HTTPS clone/pull URLs.
// Returns nil when no token is available or URL is not HTTPS.
func AuthEnvForURL(cloneURL string) []string {
return authEnv(cloneURL)
}
// ResolveTokenForURL returns token credentials resolved from env vars for the
// provided HTTPS URL. Returns empty strings when no token is available.
func ResolveTokenForURL(cloneURL string) (token, username string) {
return resolveToken(cloneURL)
}
// DetectPlatformForURL identifies the git hosting platform for a URL.
func DetectPlatformForURL(cloneURL string) Platform {
return detectPlatform(cloneURL)
}
func detectPlatformWithOptions(cloneURL string, cnbHosts, giteaHosts []string) Platform {
host := strings.ToLower(extractHost(cloneURL))
if host == "" {
return PlatformUnknown
}
return detectPlatformFromHost(host, cnbHosts, giteaHosts)
}
func (s *Source) authEnv() []string {
if s == nil {
return nil
}
return authEnvWithOptions(s.CloneURL, s.CNBHosts, s.GiteaHosts)
}
func (s *Source) platform() Platform {
if s == nil {
return PlatformUnknown
}
return detectPlatformWithOptions(s.CloneURL, s.CNBHosts, s.GiteaHosts)
}
// existingConfigCount returns the current GIT_CONFIG_COUNT from the
// environment, or 0 if unset/invalid.
func existingConfigCount() int {
s := os.Getenv("GIT_CONFIG_COUNT")
if s == "" {
return 0
}
n, err := strconv.Atoi(s)
if err != nil || n < 0 {
return 0
}
return n
}
// sanitizeTokens replaces any known credential values found in text with
// [REDACTED]. This prevents tokens and associated usernames from leaking
// in error messages.
func sanitizeTokens(text string) string {
vars := []string{
"GITHUB_TOKEN", "GH_TOKEN", "GITLAB_TOKEN", "BITBUCKET_TOKEN",
"AZURE_DEVOPS_TOKEN", "SKILLSHARE_GIT_TOKEN", "BITBUCKET_USERNAME",
"CNB_TOKEN", "GITEA_TOKEN",
}
for _, v := range vars {
if t := os.Getenv(v); t != "" {
text = strings.ReplaceAll(text, t, "[REDACTED]")
}
}
return text
}
// urlUsername extracts the username from an HTTPS URL, if present.
// Returns "" for URLs without userinfo (e.g. https://github.com/...).
func urlUsername(cloneURL string) string {
u, err := url.Parse(strings.TrimSpace(cloneURL))
if err != nil || u.User == nil {
return ""
}
return u.User.Username()
}
// isHTTPS returns true if the URL uses the HTTPS scheme.
func isHTTPS(cloneURL string) bool {
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(cloneURL)), "https://")
}
// IsAuthError returns true when git stderr indicates an authentication failure.
func IsAuthError(output string) bool {
return strings.Contains(output, "Authentication failed") ||
strings.Contains(output, "Access denied") ||
strings.Contains(output, "could not read Username") ||
strings.Contains(output, "terminal prompts disabled")
}
// IsSSLError returns true when git stderr indicates a TLS/SSL certificate failure.
func IsSSLError(output string) bool {
lower := strings.ToLower(output)
return strings.Contains(lower, "ssl certificate problem") ||
strings.Contains(lower, "unable to get local issuer certificate") ||
strings.Contains(lower, "self signed certificate") ||
strings.Contains(lower, "certificate verify failed") ||
strings.Contains(lower, "certificate verification failed")
}