mirror of
https://gitea.com/gitea/tea.git
synced 2026-10-26 11:01:25 +01:00
feat!: rebuild tea on Cobra with explicit noun/verb commands (#1126)
- **switch tea to the Cobra command tree:** `internal/app` wires the packages from parts 1–4 into explicit noun/verb commands with `--repo`, `--json` / `--jq`, `--sudo` and `--debug`; `main.go` points at it. Build, release and docs tooling (`tools/cli-docs`, Makefile, goreleaser, snap, CI) and README / CONTRIBUTING are updated. - **remove the urfave/cli command tree:** deletes `cmd/`, `modules/`, the old integration tests, contrib completion scripts and the generated `docs/CLI.md`, and drops their dependencies. This commit only deletes. ## Breaking changes This is a breaking release. It requires Gitea 28 or newer; configuration moves to separate `config.yml` and `hosts.yml` files and requires fresh authentication, and command names, aliases, flags and output formats change. `docs/migration-1.0.md` maps every old command, flag and environment variable to its replacement. ## Issues fixes #1118 fixes #1116 fixes #1115 fixes #1094 fixes #1091 fixes #1073 fixes #1052 fixes #1032 fixes #1023 fixes #966 fixes #908 fixes #833 fixes #831 fixes #817 fixes #804 fixes #779 fixes #770 fixes #737 fixes #697 fixes #726 fixes #677 fixes #672 fixes #633 fixes #632 fixes #560 fixes #556 fixes #523 fixes #516 fixes #510 fixes #504 fixes #500 fixes #482 fixes #406 fixes #403 fixes #373 fixes #351 fixes #344 fixes #326 fixes #325 fixes #323 fixes #246 fixes #240 fixes #232 fixes #197 fixes #172 fixes #141 fixes #69 fixes #1110 fixes #569 fixes #480 fixes #666 fixes #670 fixes #457 fixes #643 fixes #498 fixes #490 fixes #1069 fixes #834 fixes #602 fixes #328 fixes #417 fixes #571 fixes #1029 fixes #489 fixes #1050 fixes #162 fixes #430 fixes #1087 fixes #683 Reviewed-on: https://gitea.com/gitea/tea/pulls/1126 Reviewed-by: TheFox0x7 <95654+thefox0x7@noreply.gitea.com>
This commit is contained in:
1 parent
12e415a7a7
commit
f02245449b
456 files changed
+18892
-34015
No files matched your search
@@ -1,157 +0,0 @@
|
||||
// Copyright 2020 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"gitea.dev/tea/modules/utils"
|
||||
|
||||
"github.com/adrg/xdg"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// FlagDefaults defines all flags that can be overridden with a default value
|
||||
// via the config file
|
||||
type FlagDefaults struct {
|
||||
// Prefer a specific git remote to use for selecting a repository on gitea,
|
||||
// instead of relying on the remote associated with main/master/trunk branch.
|
||||
// The --remote flag still has precedence over this value.
|
||||
Remote string `yaml:"remote"`
|
||||
}
|
||||
|
||||
// Preferences that are stored in and read from the config file
|
||||
type Preferences struct {
|
||||
// Prefer using an external text editor over inline multiline prompts
|
||||
Editor bool `yaml:"editor"`
|
||||
FlagDefaults FlagDefaults `yaml:"flag_defaults"`
|
||||
}
|
||||
|
||||
// LocalConfig represents local configurations
|
||||
type LocalConfig struct {
|
||||
Logins []Login `yaml:"logins"`
|
||||
Prefs Preferences `yaml:"preferences"`
|
||||
}
|
||||
|
||||
var (
|
||||
// config contain if loaded local tea config
|
||||
config LocalConfig
|
||||
loadConfigOnce sync.Once
|
||||
configPathMu sync.Mutex
|
||||
configPathTestOverride string
|
||||
)
|
||||
|
||||
// GetConfigPath return path to tea config file
|
||||
func GetConfigPath() string {
|
||||
configPathMu.Lock()
|
||||
override := configPathTestOverride
|
||||
configPathMu.Unlock()
|
||||
if override != "" {
|
||||
return override
|
||||
}
|
||||
|
||||
configFilePath, err := xdg.ConfigFile("tea/config.yml")
|
||||
|
||||
var exists bool
|
||||
if err != nil {
|
||||
exists = false
|
||||
} else {
|
||||
exists, _ = utils.PathExists(configFilePath)
|
||||
}
|
||||
|
||||
// fallback to old config if no new one exists
|
||||
if !exists {
|
||||
file := filepath.Join(xdg.Home, ".tea", "tea.yml")
|
||||
exists, _ = utils.PathExists(file)
|
||||
if exists {
|
||||
return file
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "unable to get or create config file")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
return configFilePath
|
||||
}
|
||||
|
||||
// SetConfigPathForTesting overrides the config path used by helpers in tests.
|
||||
func SetConfigPathForTesting(path string) {
|
||||
configPathMu.Lock()
|
||||
configPathTestOverride = path
|
||||
configPathMu.Unlock()
|
||||
}
|
||||
|
||||
// GetPreferences returns preferences based on the config file
|
||||
func GetPreferences() Preferences {
|
||||
_ = loadConfig()
|
||||
return config.Prefs
|
||||
}
|
||||
|
||||
// loadConfig load config from file
|
||||
func loadConfig() (err error) {
|
||||
loadConfigOnce.Do(func() {
|
||||
ymlPath := GetConfigPath()
|
||||
exist, _ := utils.FileExist(ymlPath)
|
||||
if exist {
|
||||
bs, readErr := os.ReadFile(ymlPath)
|
||||
if readErr != nil {
|
||||
err = fmt.Errorf("failed to read config file %s: %w", ymlPath, readErr)
|
||||
return
|
||||
}
|
||||
|
||||
if unmarshalErr := yaml.Unmarshal(bs, &config); unmarshalErr != nil {
|
||||
err = fmt.Errorf("failed to parse config file %s: %w", ymlPath, unmarshalErr)
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// reloadConfigFromDisk re-reads the config file from disk, bypassing the sync.Once.
|
||||
// This is used after acquiring a lock to ensure we have the latest config state.
|
||||
// The caller must hold the config lock.
|
||||
func reloadConfigFromDisk() error {
|
||||
ymlPath := GetConfigPath()
|
||||
exist, _ := utils.FileExist(ymlPath)
|
||||
if !exist {
|
||||
// No config file yet, start with empty config
|
||||
config = LocalConfig{}
|
||||
return nil
|
||||
}
|
||||
|
||||
bs, err := os.ReadFile(ymlPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read config file %s: %w", ymlPath, err)
|
||||
}
|
||||
|
||||
if err := yaml.Unmarshal(bs, &config); err != nil {
|
||||
return fmt.Errorf("failed to parse config file %s: %w", ymlPath, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetConfigForTesting replaces the in-memory config and marks it as loaded.
|
||||
// This allows tests to inject config without relying on file-based loading.
|
||||
func SetConfigForTesting(cfg LocalConfig) {
|
||||
loadConfigOnce.Do(func() {}) // ensure sync.Once is spent
|
||||
config = cfg
|
||||
}
|
||||
|
||||
// saveConfigUnsafe saves config to file without acquiring a lock.
|
||||
// Caller must hold the config lock.
|
||||
func saveConfigUnsafe() error {
|
||||
ymlPath := GetConfigPath()
|
||||
bs, err := yaml.Marshal(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(ymlPath, bs, 0o600)
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/adrg/xdg"
|
||||
"github.com/go-signet/sdk-go/credstore"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
var (
|
||||
tokenStore *credstore.SecureStore[credstore.Token]
|
||||
tokenStoreOnce sync.Once
|
||||
|
||||
saveOAuthTokenToStore = func(loginName, accessToken, refreshToken string, expiresAt time.Time) error {
|
||||
return getTokenStore().Save(loginName, credstore.Token{
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
ExpiresAt: expiresAt,
|
||||
ClientID: loginName,
|
||||
})
|
||||
}
|
||||
deleteOAuthTokenFromStore = func(loginName string) error {
|
||||
return getTokenStore().Delete(loginName)
|
||||
}
|
||||
)
|
||||
|
||||
func getTokenStore() *credstore.SecureStore[credstore.Token] {
|
||||
tokenStoreOnce.Do(func() {
|
||||
filePath := filepath.Join(xdg.ConfigHome, "tea", "credentials.json")
|
||||
tokenStore = credstore.DefaultTokenSecureStore("tea-cli", filePath)
|
||||
})
|
||||
return tokenStore
|
||||
}
|
||||
|
||||
// LoadOAuthToken loads OAuth tokens from the secure store.
|
||||
func LoadOAuthToken(loginName string) (*credstore.Token, error) {
|
||||
tok, err := getTokenStore().Load(loginName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tok, nil
|
||||
}
|
||||
|
||||
// SaveOAuthToken saves OAuth tokens to the secure store.
|
||||
func SaveOAuthToken(loginName, accessToken, refreshToken string, expiresAt time.Time) error {
|
||||
return saveOAuthTokenToStore(loginName, accessToken, refreshToken, expiresAt)
|
||||
}
|
||||
|
||||
// DeleteOAuthToken removes tokens from the secure store.
|
||||
func DeleteOAuthToken(loginName string) error {
|
||||
return deleteOAuthTokenFromStore(loginName)
|
||||
}
|
||||
|
||||
// SaveOAuthTokenFromOAuth2 saves an oauth2.Token to credstore, falling back to
|
||||
// the existing login's values for empty refresh token or zero expiry.
|
||||
func SaveOAuthTokenFromOAuth2(loginName string, token *oauth2.Token, login *Login) error {
|
||||
refreshToken := token.RefreshToken
|
||||
if refreshToken == "" {
|
||||
refreshToken = login.GetRefreshToken()
|
||||
}
|
||||
expiry := token.Expiry
|
||||
if expiry.IsZero() {
|
||||
expiry = login.GetTokenExpiry()
|
||||
}
|
||||
return SaveOAuthToken(loginName, token.AccessToken, refreshToken, expiry)
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.dev/tea/modules/filelock"
|
||||
)
|
||||
|
||||
const (
|
||||
// LockTimeout is the default timeout for acquiring the config file lock.
|
||||
LockTimeout = 5 * time.Second
|
||||
|
||||
// mutexPollInterval is how often to retry acquiring the in-process mutex.
|
||||
mutexPollInterval = 10 * time.Millisecond
|
||||
)
|
||||
|
||||
// configMutex protects in-process concurrent access to the config.
|
||||
var configMutex sync.Mutex
|
||||
|
||||
// acquireConfigLock acquires both the in-process mutex and a file lock.
|
||||
// Returns an unlock function that must be called to release both locks.
|
||||
// The timeout applies to acquiring the file lock; the mutex acquisition
|
||||
// uses the same timeout via a TryLock loop.
|
||||
func acquireConfigLock(lockPath string, timeout time.Duration) (unlock func() error, err error) {
|
||||
// Try to acquire mutex with timeout
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
if configMutex.TryLock() {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return nil, fmt.Errorf("timeout waiting for config mutex")
|
||||
}
|
||||
time.Sleep(mutexPollInterval)
|
||||
}
|
||||
|
||||
// Mutex acquired, now try file lock
|
||||
remaining := max(time.Until(deadline), 0)
|
||||
locker := filelock.New(lockPath, remaining)
|
||||
|
||||
fileUnlock, err := locker.Acquire()
|
||||
if err != nil {
|
||||
configMutex.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Return unlock function
|
||||
return func() error {
|
||||
unlockErr := fileUnlock()
|
||||
configMutex.Unlock()
|
||||
return unlockErr
|
||||
}, nil
|
||||
}
|
||||
|
||||
// getConfigLockPath returns the path to the lock file for the config.
|
||||
func getConfigLockPath() string {
|
||||
return GetConfigPath() + ".lock"
|
||||
}
|
||||
|
||||
// withConfigLock executes the given function while holding the config lock.
|
||||
// It acquires the lock, reloads the config from disk, executes fn, and releases the lock.
|
||||
func withConfigLock(fn func() error) (retErr error) {
|
||||
lockPath := getConfigLockPath()
|
||||
unlock, err := acquireConfigLock(lockPath, LockTimeout)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to acquire config lock: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if unlockErr := unlock(); unlockErr != nil && retErr == nil {
|
||||
retErr = fmt.Errorf("failed to release config lock: %w", unlockErr)
|
||||
}
|
||||
}()
|
||||
|
||||
// Reload config from disk to get latest state
|
||||
if err := reloadConfigFromDisk(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return fn()
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestConfigLock_BasicLockUnlock(t *testing.T) {
|
||||
// Create a temp directory for test
|
||||
tmpDir, err := os.MkdirTemp("", "tea-lock-test")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
lockPath := filepath.Join(tmpDir, "config.yml.lock")
|
||||
|
||||
// Should be able to acquire lock
|
||||
unlock, err := acquireConfigLock(lockPath, 5*time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to acquire lock: %v", err)
|
||||
}
|
||||
|
||||
// Should be able to release lock
|
||||
err = unlock()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to release lock: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigLock_MutexProtection(t *testing.T) {
|
||||
// Create a temp directory for test
|
||||
tmpDir, err := os.MkdirTemp("", "tea-lock-test")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
lockPath := filepath.Join(tmpDir, "config.yml.lock")
|
||||
|
||||
// Acquire lock
|
||||
unlock, err := acquireConfigLock(lockPath, 5*time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to acquire lock: %v", err)
|
||||
}
|
||||
|
||||
// Try to acquire again from same process - should block/timeout due to mutex
|
||||
done := make(chan bool)
|
||||
go func() {
|
||||
_, err := acquireConfigLock(lockPath, 100*time.Millisecond)
|
||||
done <- (err != nil) // Should timeout/fail
|
||||
}()
|
||||
|
||||
select {
|
||||
case failed := <-done:
|
||||
if !failed {
|
||||
t.Error("second lock acquisition should have failed due to mutex")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Error("test timed out")
|
||||
}
|
||||
|
||||
if err := unlock(); err != nil {
|
||||
t.Errorf("failed to unlock: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func useTempConfigPath(t *testing.T) string {
|
||||
t.Helper()
|
||||
|
||||
configPath := filepath.Join(t.TempDir(), "config.yml")
|
||||
SetConfigPathForTesting(configPath)
|
||||
t.Cleanup(func() {
|
||||
SetConfigPathForTesting("")
|
||||
})
|
||||
|
||||
return configPath
|
||||
}
|
||||
|
||||
func TestReloadConfigFromDisk(t *testing.T) {
|
||||
configPath := useTempConfigPath(t)
|
||||
|
||||
// Save original config state
|
||||
originalConfig := config
|
||||
|
||||
config = LocalConfig{Logins: []Login{{Name: "stale"}}}
|
||||
if err := os.WriteFile(configPath, []byte("logins:\n - name: test\n"), 0o600); err != nil {
|
||||
t.Fatalf("failed to write temp config: %v", err)
|
||||
}
|
||||
|
||||
err := reloadConfigFromDisk()
|
||||
if err != nil {
|
||||
t.Fatalf("reloadConfigFromDisk returned error: %v", err)
|
||||
}
|
||||
|
||||
if len(config.Logins) != 1 || config.Logins[0].Name != "test" {
|
||||
t.Fatalf("expected config to reload test login, got %+v", config.Logins)
|
||||
}
|
||||
|
||||
// Restore original config
|
||||
config = originalConfig
|
||||
}
|
||||
|
||||
func TestWithConfigLock(t *testing.T) {
|
||||
useTempConfigPath(t)
|
||||
|
||||
executed := false
|
||||
err := withConfigLock(func() error {
|
||||
executed = true
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("withConfigLock returned error: %v", err)
|
||||
}
|
||||
if !executed {
|
||||
t.Error("function was not executed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithConfigLock_PropagatesError(t *testing.T) {
|
||||
useTempConfigPath(t)
|
||||
|
||||
expectedErr := fmt.Errorf("test error")
|
||||
err := withConfigLock(func() error {
|
||||
return expectedErr
|
||||
})
|
||||
|
||||
if err != expectedErr {
|
||||
t.Errorf("expected error %v, got %v", expectedErr, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoubleCheckedLocking_SimulatedRefresh(t *testing.T) {
|
||||
useTempConfigPath(t)
|
||||
|
||||
// This test simulates the double-checked locking pattern
|
||||
// by having multiple goroutines try to "refresh" simultaneously
|
||||
|
||||
var (
|
||||
refreshCount int
|
||||
mu sync.Mutex
|
||||
)
|
||||
|
||||
// Simulate what RefreshOAuthToken does with double-check
|
||||
simulatedRefresh := func(tokenExpiry *int64) error {
|
||||
// First check (without lock)
|
||||
if *tokenExpiry > time.Now().Unix() {
|
||||
return nil // Token still valid
|
||||
}
|
||||
|
||||
return withConfigLock(func() error {
|
||||
// Double-check after acquiring lock
|
||||
if *tokenExpiry > time.Now().Unix() {
|
||||
return nil // Another goroutine refreshed it
|
||||
}
|
||||
|
||||
// Simulate refresh
|
||||
mu.Lock()
|
||||
refreshCount++
|
||||
mu.Unlock()
|
||||
|
||||
time.Sleep(50 * time.Millisecond) // Simulate API call
|
||||
*tokenExpiry = time.Now().Add(1 * time.Hour).Unix()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Start with expired token
|
||||
tokenExpiry := time.Now().Add(-1 * time.Hour).Unix()
|
||||
|
||||
// Launch multiple goroutines trying to refresh
|
||||
var wg sync.WaitGroup
|
||||
for range 5 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := simulatedRefresh(&tokenExpiry); err != nil {
|
||||
t.Errorf("refresh failed: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// Should only have refreshed once due to double-checked locking
|
||||
if refreshCount != 1 {
|
||||
t.Errorf("expected 1 refresh, got %d", refreshCount)
|
||||
}
|
||||
}
|
||||
@@ -1,549 +0,0 @@
|
||||
// Copyright 2020 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
gitea "gitea.dev/sdk"
|
||||
|
||||
"gitea.dev/tea/modules/debug"
|
||||
"gitea.dev/tea/modules/httputil"
|
||||
"gitea.dev/tea/modules/theme"
|
||||
"gitea.dev/tea/modules/utils"
|
||||
|
||||
"charm.land/huh/v2"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// TokenRefreshThreshold is how far before expiry we should refresh OAuth tokens.
|
||||
// This is used by config.Login.Client() for automatic token refresh.
|
||||
const TokenRefreshThreshold = 5 * time.Minute
|
||||
|
||||
// DefaultClientID is the default OAuth2 client ID included in most Gitea instances
|
||||
const DefaultClientID = "d57cb8c4-630c-4168-8324-ec79935e18d4"
|
||||
|
||||
// AuthMethodOAuth marks a login as using OAuth with secure credential storage.
|
||||
const AuthMethodOAuth = "oauth"
|
||||
|
||||
// Login represents a login to a gitea server, you even could add multiple logins for one gitea server
|
||||
type Login struct {
|
||||
Name string `yaml:"name"`
|
||||
URL string `yaml:"url"`
|
||||
Token string `yaml:"token,omitempty"`
|
||||
Default bool `yaml:"default"`
|
||||
SSHHost string `yaml:"ssh_host"`
|
||||
// optional path to the private key
|
||||
SSHKey string `yaml:"ssh_key"`
|
||||
Insecure bool `yaml:"insecure"`
|
||||
SSHCertPrincipal string `yaml:"ssh_certificate_principal"`
|
||||
SSHAgent bool `yaml:"ssh_agent"`
|
||||
SSHKeyFingerprint string `yaml:"ssh_key_agent_pub"`
|
||||
SSHPassphrase string `yaml:"-"`
|
||||
VersionCheck bool `yaml:"version_check"`
|
||||
// User is username from gitea
|
||||
User string `yaml:"user"`
|
||||
// Created is auto created unix timestamp
|
||||
Created int64 `yaml:"created"`
|
||||
// AuthMethod indicates the authentication method ("oauth" for OAuth with credstore)
|
||||
AuthMethod string `yaml:"auth_method,omitempty"`
|
||||
// RefreshToken is used to renew the access token when it expires
|
||||
RefreshToken string `yaml:"refresh_token,omitempty"`
|
||||
// TokenExpiry is when the token expires (unix timestamp)
|
||||
TokenExpiry int64 `yaml:"token_expiry,omitempty"`
|
||||
}
|
||||
|
||||
// IsOAuth returns true if this login uses OAuth with secure credential storage.
|
||||
func (l *Login) IsOAuth() bool {
|
||||
return l.AuthMethod == AuthMethodOAuth
|
||||
}
|
||||
|
||||
// loadOAuthToken loads the OAuth token from credstore, returning nil if
|
||||
// this is not an OAuth login or if the load fails (caller should fallback).
|
||||
func (l *Login) loadOAuthToken() *OAuthToken {
|
||||
if !l.IsOAuth() {
|
||||
return nil
|
||||
}
|
||||
tok, err := LoadOAuthToken(l.Name)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return &OAuthToken{
|
||||
AccessToken: tok.AccessToken,
|
||||
RefreshToken: tok.RefreshToken,
|
||||
ExpiresAt: tok.ExpiresAt,
|
||||
}
|
||||
}
|
||||
|
||||
// OAuthToken holds the token fields loaded from credstore.
|
||||
type OAuthToken struct {
|
||||
AccessToken string
|
||||
RefreshToken string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
// GetAccessToken returns the effective access token.
|
||||
// For OAuth logins, reads from credstore. For others, returns l.Token directly.
|
||||
func (l *Login) GetAccessToken() string {
|
||||
if tok := l.loadOAuthToken(); tok != nil {
|
||||
return tok.AccessToken
|
||||
}
|
||||
return l.Token
|
||||
}
|
||||
|
||||
// GetRefreshToken returns the refresh token.
|
||||
func (l *Login) GetRefreshToken() string {
|
||||
if tok := l.loadOAuthToken(); tok != nil {
|
||||
return tok.RefreshToken
|
||||
}
|
||||
return l.RefreshToken
|
||||
}
|
||||
|
||||
// GetTokenExpiry returns the token expiry time.
|
||||
func (l *Login) GetTokenExpiry() time.Time {
|
||||
if tok := l.loadOAuthToken(); tok != nil {
|
||||
return tok.ExpiresAt
|
||||
}
|
||||
return time.Unix(l.TokenExpiry, 0)
|
||||
}
|
||||
|
||||
// GetLogins return all login available by config
|
||||
func GetLogins() ([]Login, error) {
|
||||
if err := loadConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return config.Logins, nil
|
||||
}
|
||||
|
||||
// GetDefaultLogin return the default login
|
||||
func GetDefaultLogin() (*Login, error) {
|
||||
if err := loadConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(config.Logins) == 0 {
|
||||
return nil, errors.New("no available login")
|
||||
}
|
||||
for _, l := range config.Logins {
|
||||
if l.Default {
|
||||
return &l, nil
|
||||
}
|
||||
}
|
||||
|
||||
return &config.Logins[0], nil
|
||||
}
|
||||
|
||||
// SetDefaultLogin set the default login by name (case insensitive)
|
||||
func SetDefaultLogin(name string) error {
|
||||
return withConfigLock(func() error {
|
||||
loginExist := false
|
||||
for i := range config.Logins {
|
||||
config.Logins[i].Default = false
|
||||
if strings.EqualFold(config.Logins[i].Name, name) {
|
||||
config.Logins[i].Default = true
|
||||
loginExist = true
|
||||
}
|
||||
}
|
||||
|
||||
if !loginExist {
|
||||
return fmt.Errorf("login '%s' not found", name)
|
||||
}
|
||||
|
||||
return saveConfigUnsafe()
|
||||
})
|
||||
}
|
||||
|
||||
// GetLoginByName get login by name (case insensitive)
|
||||
func GetLoginByName(name string) (*Login, error) {
|
||||
if err := loadConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for i := range config.Logins {
|
||||
if strings.EqualFold(config.Logins[i].Name, name) {
|
||||
return &config.Logins[i], nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// GetLoginByToken get login by token
|
||||
func GetLoginByToken(token string) (*Login, error) {
|
||||
if token == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if err := loadConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, l := range config.Logins {
|
||||
if l.Token == token {
|
||||
return &l, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// GetLoginByHost finds a login by its server URL
|
||||
func GetLoginByHost(host string) (*Login, error) {
|
||||
logins, err := GetLoginsByHost(host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(logins) > 0 {
|
||||
return logins[0], nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// GetLoginsByHost returns all logins matching a host
|
||||
func GetLoginsByHost(host string) ([]*Login, error) {
|
||||
if err := loadConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var matches []*Login
|
||||
for i := range config.Logins {
|
||||
loginURL, err := url.Parse(config.Logins[i].URL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if loginURL.Host == host {
|
||||
matches = append(matches, &config.Logins[i])
|
||||
}
|
||||
}
|
||||
return matches, nil
|
||||
}
|
||||
|
||||
// DeleteLogin delete a login by name from config
|
||||
func DeleteLogin(name string) error {
|
||||
return withConfigLock(func() error {
|
||||
idx := -1
|
||||
for i, l := range config.Logins {
|
||||
if strings.EqualFold(l.Name, name) {
|
||||
idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if idx == -1 {
|
||||
return fmt.Errorf("can not delete login '%s', does not exist", name)
|
||||
}
|
||||
|
||||
isOAuth := config.Logins[idx].IsOAuth()
|
||||
config.Logins = append(config.Logins[:idx], config.Logins[idx+1:]...)
|
||||
|
||||
// Clean up credstore tokens for OAuth logins
|
||||
if isOAuth {
|
||||
_ = DeleteOAuthToken(name)
|
||||
}
|
||||
|
||||
return saveConfigUnsafe()
|
||||
})
|
||||
}
|
||||
|
||||
// AddLogin save a login to config
|
||||
func AddLogin(login *Login) error {
|
||||
return withConfigLock(func() error {
|
||||
// Check for duplicate login names
|
||||
for _, existing := range config.Logins {
|
||||
if strings.EqualFold(existing.Name, login.Name) {
|
||||
return fmt.Errorf("login name '%s' already exists", login.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// save login to global var
|
||||
config.Logins = append(config.Logins, *login)
|
||||
|
||||
// save login to config file
|
||||
return saveConfigUnsafe()
|
||||
})
|
||||
}
|
||||
|
||||
// AddOAuthLogin saves the OAuth token and login profile as one operation.
|
||||
// The profile is only written after secure token storage succeeds.
|
||||
func AddOAuthLogin(login *Login, accessToken, refreshToken string, expiresAt time.Time) error {
|
||||
return withConfigLock(func() error {
|
||||
// Check for duplicate login names before touching credential storage.
|
||||
for _, existing := range config.Logins {
|
||||
if strings.EqualFold(existing.Name, login.Name) {
|
||||
return fmt.Errorf("login name '%s' already exists", login.Name)
|
||||
}
|
||||
}
|
||||
|
||||
if err := SaveOAuthToken(login.Name, accessToken, refreshToken, expiresAt); err != nil {
|
||||
return fmt.Errorf("failed to save token to secure store: %w", err)
|
||||
}
|
||||
|
||||
config.Logins = append(config.Logins, *login)
|
||||
if err := saveConfigUnsafe(); err != nil {
|
||||
config.Logins = config.Logins[:len(config.Logins)-1]
|
||||
if deleteErr := DeleteOAuthToken(login.Name); deleteErr != nil {
|
||||
return errors.Join(err, fmt.Errorf("failed to clean up OAuth token after config save failure: %w", deleteErr))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// SaveLoginTokens updates the token fields for an existing login.
|
||||
// This is used after browser-based re-authentication to save new tokens.
|
||||
func SaveLoginTokens(login *Login) error {
|
||||
if login.IsOAuth() {
|
||||
return SaveOAuthToken(login.Name, login.GetAccessToken(), login.GetRefreshToken(), login.GetTokenExpiry())
|
||||
}
|
||||
return withConfigLock(func() error {
|
||||
for i, l := range config.Logins {
|
||||
if strings.EqualFold(l.Name, login.Name) {
|
||||
config.Logins[i].Token = login.Token
|
||||
config.Logins[i].RefreshToken = login.RefreshToken
|
||||
config.Logins[i].TokenExpiry = login.TokenExpiry
|
||||
return saveConfigUnsafe()
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("login %s not found", login.Name)
|
||||
})
|
||||
}
|
||||
|
||||
// RefreshOAuthTokenIfNeeded refreshes the OAuth token if it's expired or near expiry.
|
||||
// Returns nil without doing anything if no refresh is needed.
|
||||
func (l *Login) RefreshOAuthTokenIfNeeded() error {
|
||||
// Load once to avoid multiple credstore reads
|
||||
if tok := l.loadOAuthToken(); tok != nil {
|
||||
if tok.RefreshToken == "" || tok.ExpiresAt.IsZero() {
|
||||
return nil
|
||||
}
|
||||
if time.Now().Add(TokenRefreshThreshold).After(tok.ExpiresAt) {
|
||||
return l.RefreshOAuthToken()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Non-OAuth path: use YAML fields
|
||||
if l.RefreshToken == "" || l.TokenExpiry == 0 {
|
||||
return nil
|
||||
}
|
||||
if time.Now().Add(TokenRefreshThreshold).After(time.Unix(l.TokenExpiry, 0)) {
|
||||
return l.RefreshOAuthToken()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RefreshOAuthToken refreshes the OAuth access token using the refresh token.
|
||||
// It updates the login with new token information and saves it to config.
|
||||
// Uses double-checked locking to avoid unnecessary refresh calls when multiple
|
||||
// processes race to refresh the same token.
|
||||
func (l *Login) RefreshOAuthToken() error {
|
||||
if l.GetRefreshToken() == "" {
|
||||
return fmt.Errorf("no refresh token available")
|
||||
}
|
||||
|
||||
return withConfigLock(func() error {
|
||||
// Double-check: after acquiring lock, re-read config and check if
|
||||
// another process already refreshed the token
|
||||
for i, login := range config.Logins {
|
||||
if login.Name == l.Name {
|
||||
// Check if token was refreshed by another process
|
||||
currentExpiry := login.GetTokenExpiry()
|
||||
ourExpiry := l.GetTokenExpiry()
|
||||
if currentExpiry != ourExpiry && !currentExpiry.IsZero() {
|
||||
if time.Now().Add(TokenRefreshThreshold).Before(currentExpiry) {
|
||||
// Token was refreshed by another process, update our copy
|
||||
if !login.IsOAuth() {
|
||||
l.Token = login.Token
|
||||
l.RefreshToken = login.RefreshToken
|
||||
l.TokenExpiry = login.TokenExpiry
|
||||
}
|
||||
// For OAuth logins, credstore already has the latest tokens
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Still need to refresh - proceed with OAuth call
|
||||
newToken, err := doOAuthRefresh(context.Background(), l)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if l.IsOAuth() {
|
||||
// Save tokens to credstore; no YAML changes needed
|
||||
return SaveOAuthTokenFromOAuth2(l.Name, newToken, l)
|
||||
}
|
||||
|
||||
// Update login with new token information (legacy path)
|
||||
l.Token = newToken.AccessToken
|
||||
if newToken.RefreshToken != "" {
|
||||
l.RefreshToken = newToken.RefreshToken
|
||||
}
|
||||
if !newToken.Expiry.IsZero() {
|
||||
l.TokenExpiry = newToken.Expiry.Unix()
|
||||
}
|
||||
config.Logins[i] = *l
|
||||
return saveConfigUnsafe()
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("login %s not found", l.Name)
|
||||
})
|
||||
}
|
||||
|
||||
// doOAuthRefresh performs the actual OAuth token refresh API call.
|
||||
func doOAuthRefresh(ctx context.Context, l *Login) (*oauth2.Token, error) {
|
||||
// Build current token from credstore (single load) or YAML fields
|
||||
var accessToken, refreshToken string
|
||||
var expiry time.Time
|
||||
if tok := l.loadOAuthToken(); tok != nil {
|
||||
accessToken = tok.AccessToken
|
||||
refreshToken = tok.RefreshToken
|
||||
expiry = tok.ExpiresAt
|
||||
} else {
|
||||
accessToken = l.Token
|
||||
refreshToken = l.RefreshToken
|
||||
expiry = time.Unix(l.TokenExpiry, 0)
|
||||
}
|
||||
currentToken := &oauth2.Token{
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
Expiry: expiry,
|
||||
}
|
||||
|
||||
httpClient := &http.Client{
|
||||
Transport: httputil.WrapTransport(&tls.Config{InsecureSkipVerify: l.Insecure}),
|
||||
}
|
||||
ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
|
||||
|
||||
oauth2Config := &oauth2.Config{
|
||||
ClientID: DefaultClientID,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
TokenURL: fmt.Sprintf("%s/login/oauth/access_token", l.URL),
|
||||
},
|
||||
}
|
||||
|
||||
newToken, err := oauth2Config.TokenSource(ctx, currentToken).Token()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to refresh token: %w", err)
|
||||
}
|
||||
|
||||
return newToken, nil
|
||||
}
|
||||
|
||||
// Client returns a client to operate Gitea API. You may provide additional modifiers
|
||||
// for the client like gitea.SetBasicAuth() for customization
|
||||
func (l *Login) Client(options ...gitea.ClientOption) *gitea.Client {
|
||||
// Refresh OAuth token if expired or near expiry
|
||||
if err := l.RefreshOAuthTokenIfNeeded(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Failed to refresh token: %s\nPlease use 'tea login oauth-refresh %s' to manually refresh the token.\n", err, l.Name)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
return l.ClientWithoutRefresh(options...)
|
||||
}
|
||||
|
||||
// ClientWithoutRefresh returns a client to operate the Gitea API without
|
||||
// attempting an automatic OAuth token refresh. Commands that need to handle
|
||||
// token refresh errors themselves (such as 'tea login status') should use this
|
||||
// instead of Client, which prints to stderr and exits on refresh failure.
|
||||
func (l *Login) ClientWithoutRefresh(options ...gitea.ClientOption) *gitea.Client {
|
||||
// Configure transport-level timeouts so a stalled or unresponsive server
|
||||
// fails fast instead of hanging forever. These bound connection setup and
|
||||
// time-to-first-response-byte only, so slow-but-progressing transfers (e.g.
|
||||
// large attachment uploads) are unaffected.
|
||||
httpClient := &http.Client{
|
||||
Transport: httputil.WrapTransport(nil),
|
||||
}
|
||||
if l.Insecure {
|
||||
cookieJar, _ := cookiejar.New(nil) // New with nil options never returns an error
|
||||
|
||||
httpClient = &http.Client{
|
||||
Jar: cookieJar,
|
||||
Transport: httputil.WrapTransport(&tls.Config{InsecureSkipVerify: true}),
|
||||
}
|
||||
}
|
||||
|
||||
// versioncheck must be prepended in options to make sure we don't hit any version checks in the sdk
|
||||
if !l.VersionCheck {
|
||||
options = append([]gitea.ClientOption{gitea.SetGiteaVersion("")}, options...)
|
||||
}
|
||||
|
||||
// SetUserAgent is intentionally redundant with the User-Agent the WrapTransport
|
||||
// transport already sets: this is the SDK's own guarantee, so the UA survives
|
||||
// even if the client is ever given a transport that didn't come from WrapTransport.
|
||||
// Both resolve to httputil.UserAgent(), so the duplicate Header.Set is a no-op.
|
||||
options = append(options, gitea.SetToken(l.GetAccessToken()), gitea.SetHTTPClient(httpClient), gitea.SetUserAgent(httputil.UserAgent()))
|
||||
if debug.IsDebug() {
|
||||
options = append(options, gitea.SetDebugMode())
|
||||
}
|
||||
|
||||
if l.SSHCertPrincipal != "" {
|
||||
if err := l.askForSSHPassphrase(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Failed to read SSH passphrase: %s\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
options = append(options, gitea.UseSSHCert(l.SSHCertPrincipal, l.SSHKeyPath(), l.SSHPassphrase))
|
||||
}
|
||||
|
||||
if l.SSHKeyFingerprint != "" {
|
||||
if err := l.askForSSHPassphrase(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Failed to read SSH passphrase: %s\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
options = append(options, gitea.UseSSHPubkey(l.SSHKeyFingerprint, l.SSHKeyPath(), l.SSHPassphrase))
|
||||
}
|
||||
|
||||
client, err := gitea.NewClient(l.URL, options...)
|
||||
if err != nil {
|
||||
var versionError *gitea.ErrUnknownVersion
|
||||
if !errors.As(err, &versionError) {
|
||||
fmt.Fprintf(os.Stderr, "Failed to create Gitea client: %s\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "WARNING: could not detect gitea version: %s\nINFO: set gitea version: to last supported one\n", versionError)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func (l *Login) askForSSHPassphrase() error {
|
||||
if ok, err := utils.IsKeyEncrypted(l.SSHKeyPath()); ok && err == nil && l.SSHPassphrase == "" {
|
||||
return huh.NewInput().
|
||||
Title("ssh-key is encrypted please enter the passphrase: ").
|
||||
Validate(huh.ValidateNotEmpty()).
|
||||
EchoMode(huh.EchoModePassword).
|
||||
Value(&l.SSHPassphrase).
|
||||
WithTheme(theme.GetTheme()).
|
||||
Run()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SSHKeyPath returns the on-disk SSH key to use, or an empty string when the
|
||||
// login is configured to authenticate through a running ssh-agent.
|
||||
func (l *Login) SSHKeyPath() string {
|
||||
if l.SSHAgent {
|
||||
return ""
|
||||
}
|
||||
return l.SSHKey
|
||||
}
|
||||
|
||||
// GetSSHHost returns SSH host name
|
||||
func (l *Login) GetSSHHost() string {
|
||||
if l.SSHHost != "" {
|
||||
return l.SSHHost
|
||||
}
|
||||
|
||||
u, err := url.Parse(l.URL)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return u.Host
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
gitea "gitea.dev/sdk"
|
||||
"golang.org/x/crypto/ssh"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestLoginClientWithSSHPubkeyDoesNotDeadlockOnFirstRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
sshKeyPath, fingerprint := writeTestSSHKey(t)
|
||||
|
||||
var versionRequests atomic.Int32
|
||||
var issueRequests atomic.Int32
|
||||
var signedVersionRequests atomic.Int32
|
||||
var signedIssueRequests atomic.Int32
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/version":
|
||||
versionRequests.Add(1)
|
||||
if r.Header.Get("Signature") != "" {
|
||||
signedVersionRequests.Add(1)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"version":"1.26.4"}`))
|
||||
case "/api/v1/repos/gitea/tea/issues":
|
||||
issueRequests.Add(1)
|
||||
if r.Header.Get("Signature") != "" {
|
||||
signedIssueRequests.Add(1)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
default:
|
||||
t.Errorf("unexpected path %s", r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
login := &Login{
|
||||
Name: "ssh-login",
|
||||
URL: server.URL,
|
||||
SSHKey: sshKeyPath,
|
||||
SSHKeyFingerprint: fingerprint,
|
||||
VersionCheck: true,
|
||||
}
|
||||
|
||||
type result struct {
|
||||
issues []*gitea.Issue
|
||||
err error
|
||||
}
|
||||
|
||||
done := make(chan result, 1)
|
||||
go func() {
|
||||
issues, _, err := login.Client().Issues.ListRepoIssues(context.Background(), "gitea", "tea", gitea.ListIssueOption{})
|
||||
done <- result{issues: issues, err: err}
|
||||
}()
|
||||
|
||||
select {
|
||||
case res := <-done:
|
||||
require.NoError(t, res.err)
|
||||
assert.Empty(t, res.issues)
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("ListRepoIssues deadlocked while bootstrapping the server version for SSH-signed requests")
|
||||
}
|
||||
|
||||
assert.EqualValues(t, 1, versionRequests.Load())
|
||||
assert.EqualValues(t, 0, signedVersionRequests.Load())
|
||||
assert.EqualValues(t, 1, issueRequests.Load())
|
||||
assert.EqualValues(t, 1, signedIssueRequests.Load())
|
||||
}
|
||||
|
||||
func TestLoginSSHKeyPath(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
login Login
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "disk key",
|
||||
login: Login{SSHKey: "/tmp/id_ed25519"},
|
||||
want: "/tmp/id_ed25519",
|
||||
},
|
||||
{
|
||||
name: "ssh agent ignores disk key",
|
||||
login: Login{SSHKey: "/tmp/id_ed25519", SSHAgent: true},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "ssh agent without disk key",
|
||||
login: Login{SSHAgent: true},
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert.Equal(t, tt.want, tt.login.SSHKeyPath())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func writeTestSSHKey(t *testing.T) (string, string) {
|
||||
t.Helper()
|
||||
|
||||
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
require.NoError(t, err)
|
||||
|
||||
pkcs8, err := x509.MarshalPKCS8PrivateKey(privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8})
|
||||
sshKeyPath := filepath.Join(t.TempDir(), "id_ed25519")
|
||||
require.NoError(t, os.WriteFile(sshKeyPath, pemBytes, 0o600))
|
||||
|
||||
signer, err := ssh.NewSignerFromKey(privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
return sshKeyPath, ssh.FingerprintSHA256(signer.PublicKey())
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package config
|
||||
|
||||
import "time"
|
||||
|
||||
// AcquireConfigLockForTesting exposes the internal lock helper to integration tests.
|
||||
func AcquireConfigLockForTesting(lockPath string, timeout time.Duration) (func() error, error) {
|
||||
return acquireConfigLock(lockPath, timeout)
|
||||
}
|
||||
Reference in new issue
Block a user