From dfe89dfb6bf22dcbd2a6203bef8aa262e65ea085 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sun, 23 Aug 2026 12:44:52 +0000 Subject: [PATCH 1/4] fix(deps): update go toolchain directive to v1.26.6 [security] (#1103) Co-authored-by: Renovate Bot --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index fba7910c..2f0b38e4 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module gitea.dev/tea go 1.26.0 -toolchain go1.26.5 +toolchain go1.26.6 require ( charm.land/glamour/v2 v2.0.1 From bfda25be63dc3c35593140efb28c386b5ca7d8f0 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 23 Aug 2026 12:46:22 +0000 Subject: [PATCH 2/4] Read issue/PR description from stdin or a file (#1096) Closes #1095. `tea issues create` and `tea pulls create` now resolve the description in the same way as comments: when stdin is piped and neither `--description` nor `--description-file` is given, the body is read from stdin. Both create and edit commands also accept: ```text --description-file # '-' reads stdin ``` This avoids the PowerShell 5.1 argument mangling and ANSI code page issues described in #1095. ## Changes - Add `--description-file` to `issues create`, `issues edit`, `pulls create`, and `pulls edit`. - Create commands fall back to piped stdin when no description flag is set. - Add unit tests for the new body resolution. --------- Co-authored-by: bircni Reviewed-on: https://gitea.com/gitea/tea/pulls/1096 Reviewed-by: bircni Co-authored-by: Lunny Xiao --- cmd/flags/body.go | 73 +++++++++++++++++++ cmd/flags/body_test.go | 161 +++++++++++++++++++++++++++++++++++++++++ cmd/flags/issue_pr.go | 33 +++++++-- docs/CLI.md | 8 ++ 4 files changed, 270 insertions(+), 5 deletions(-) create mode 100644 cmd/flags/body.go create mode 100644 cmd/flags/body_test.go diff --git a/cmd/flags/body.go b/cmd/flags/body.go new file mode 100644 index 00000000..211e3d28 --- /dev/null +++ b/cmd/flags/body.go @@ -0,0 +1,73 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package flags + +import ( + "fmt" + "io" + "os" + + "golang.org/x/term" +) + +// stdinPiped reports whether stdin is not a terminal, e.g. when a description +// is piped from a file, command substitution, or a CI harness. +func stdinPiped() bool { + return !term.IsTerminal(int(os.Stdin.Fd())) +} + +// resolveCreateBody returns the issue/PR description for create commands. +// +// Precedence: +// 1. --description-file (read from the file, or stdin when the path is "-") +// 2. --description +// 3. piped stdin +func resolveCreateBody(description, descriptionFile string, descriptionFileSet, stdinPiped bool, stdin io.Reader) (string, error) { + if descriptionFileSet { + return readDescriptionSource(descriptionFile, stdin) + } + if description != "" { + return description, nil + } + if stdinPiped { + return readDescriptionStdin(stdin) + } + return "", nil +} + +// resolveEditBody returns the new issue/PR body when a description flag was +// provided, or nil when the caller should leave the body unchanged. +func resolveEditBody(description string, descriptionSet bool, descriptionFile string, descriptionFileSet bool, stdin io.Reader) (*string, error) { + if descriptionFileSet { + body, err := readDescriptionSource(descriptionFile, stdin) + if err != nil { + return nil, err + } + return &body, nil + } + if descriptionSet { + body := description + return &body, nil + } + return nil, nil +} + +func readDescriptionSource(source string, stdin io.Reader) (string, error) { + if source == "-" { + return readDescriptionStdin(stdin) + } + data, err := os.ReadFile(source) + if err != nil { + return "", fmt.Errorf("could not read description file %q: %w", source, err) + } + return string(data), nil +} + +func readDescriptionStdin(stdin io.Reader) (string, error) { + data, err := io.ReadAll(stdin) + if err != nil { + return "", fmt.Errorf("could not read description from stdin: %w", err) + } + return string(data), nil +} diff --git a/cmd/flags/body_test.go b/cmd/flags/body_test.go new file mode 100644 index 00000000..dc3651bb --- /dev/null +++ b/cmd/flags/body_test.go @@ -0,0 +1,161 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package flags + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestResolveCreateBody(t *testing.T) { + file := filepath.Join(t.TempDir(), "body.md") + require.NoError(t, os.WriteFile(file, []byte("from file"), 0o600)) + + tests := []struct { + name string + description string + descriptionFile string + descriptionFileSet bool + stdinPiped bool + stdin string + want string + }{ + { + name: "description flag", + description: "from -d", + want: "from -d", + }, + { + name: "description file", + descriptionFile: file, + descriptionFileSet: true, + want: "from file", + }, + { + name: "description file wins over description", + description: "from -d", + descriptionFile: file, + descriptionFileSet: true, + want: "from file", + }, + { + name: "dash reads stdin", + descriptionFile: "-", + descriptionFileSet: true, + stdin: "from stdin", + want: "from stdin", + }, + { + name: "description wins over piped stdin", + description: "from -d", + stdinPiped: true, + stdin: "from stdin", + want: "from -d", + }, + { + name: "piped stdin", + stdinPiped: true, + stdin: "from stdin", + want: "from stdin", + }, + { + name: "empty description falls back to piped stdin", + description: "", + stdinPiped: true, + stdin: "from stdin", + want: "from stdin", + }, + { + name: "empty when no source provided", + want: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := resolveCreateBody(tt.description, tt.descriptionFile, tt.descriptionFileSet, tt.stdinPiped, strings.NewReader(tt.stdin)) + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestResolveEditBody(t *testing.T) { + file := filepath.Join(t.TempDir(), "body.md") + require.NoError(t, os.WriteFile(file, []byte("from file"), 0o600)) + + tests := []struct { + name string + description string + descriptionSet bool + descriptionFile string + descriptionFileSet bool + stdin string + wantBody string + wantSet bool + }{ + { + name: "no description flag", + }, + { + name: "description flag", + description: "from -d", + descriptionSet: true, + wantBody: "from -d", + wantSet: true, + }, + { + name: "empty description clears body", + descriptionSet: true, + wantSet: true, + }, + { + name: "description file", + descriptionFile: file, + descriptionFileSet: true, + wantBody: "from file", + wantSet: true, + }, + { + name: "description file wins over description", + description: "from -d", + descriptionSet: true, + descriptionFile: file, + descriptionFileSet: true, + wantBody: "from file", + wantSet: true, + }, + { + name: "dash reads stdin", + descriptionFile: "-", + descriptionFileSet: true, + stdin: "from stdin", + wantBody: "from stdin", + wantSet: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := resolveEditBody(tt.description, tt.descriptionSet, tt.descriptionFile, tt.descriptionFileSet, strings.NewReader(tt.stdin)) + require.NoError(t, err) + if !tt.wantSet { + assert.Nil(t, got) + return + } + require.NotNil(t, got) + assert.Equal(t, tt.wantBody, *got) + }) + } +} + +func TestResolveDescriptionSourceError(t *testing.T) { + _, err := resolveCreateBody("", filepath.Join(t.TempDir(), "missing.md"), true, false, strings.NewReader("")) + require.ErrorContains(t, err, "could not read description file") +} diff --git a/cmd/flags/issue_pr.go b/cmd/flags/issue_pr.go index 65d96da2..3259c885 100644 --- a/cmd/flags/issue_pr.go +++ b/cmd/flags/issue_pr.go @@ -100,6 +100,10 @@ var issuePRFlags = append([]cli.Flag{ Name: "description", Aliases: []string{"d"}, }, + &cli.StringFlag{ + Name: "description-file", + Usage: "Read description from file ('-' for stdin)", + }, &cli.StringFlag{ Name: "referenced-version", Aliases: []string{"v"}, @@ -133,12 +137,22 @@ var IssuePRCreateFlags = append([]cli.Flag{ // GetIssuePRCreateFlags parses all IssuePREditFlags func GetIssuePRCreateFlags(requestCtx stdctx.Context, ctx *context.TeaContext) (*gitea.CreateIssueOption, error) { + body, err := resolveCreateBody( + ctx.String("description"), + ctx.String("description-file"), + ctx.IsSet("description-file"), + stdinPiped(), + ctx.Reader, + ) + if err != nil { + return nil, err + } + opts := gitea.CreateIssueOption{ Title: ctx.String("title"), - Body: ctx.String("description"), + Body: body, Assignees: strings.Split(ctx.String("assignees"), ","), } - var err error date := ctx.String("deadline") if date != "" { @@ -208,9 +222,18 @@ func GetIssuePREditFlags(ctx *context.TeaContext) (*task.EditIssueOption, error) val := ctx.String("title") opts.Title = &val } - if ctx.IsSet("description") { - val := ctx.String("description") - opts.Body = &val + body, err := resolveEditBody( + ctx.String("description"), + ctx.IsSet("description"), + ctx.String("description-file"), + ctx.IsSet("description-file"), + ctx.Reader, + ) + if err != nil { + return nil, err + } + if body != nil { + opts.Body = body } if ctx.IsSet("referenced-version") { val := ctx.String("referenced-version") diff --git a/docs/CLI.md b/docs/CLI.md index 3f74a38e..e9a57e65 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -221,6 +221,8 @@ Create an issue on repository **--description, -d**="": +**--description-file**="": Read description from file ('-' for stdin) + **--labels, -L**="": Comma-separated list of labels to assign **--login, -l**="": Use a different Gitea Login. Optional @@ -247,6 +249,8 @@ Edit one or more issues **--description, -d**="": +**--description-file**="": Read description from file ('-' for stdin) + **--login, -l**="": Use a different Gitea Login. Optional **--milestone, -m**="": Milestone to assign @@ -379,6 +383,8 @@ Create a pull-request **--description, -d**="": +**--description-file**="": Read description from file ('-' for stdin) + **--draft**: Create as a draft (prepends "WIP: " to the title; Gitea treats WIP-prefixed PRs as drafts) **--head**="": Branch name of the PR source (default is current one). To specify a different head repo, use : @@ -437,6 +443,8 @@ Edit one or more pull requests **--description, -d**="": +**--description-file**="": Read description from file ('-' for stdin) + **--draft**: Mark as draft by prepending "WIP: " to the title (idempotent) **--login, -l**="": Use a different Gitea Login. Optional From 22d43ec9b6530d636294845209e11fec4d98ff1f Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 23 Aug 2026 19:20:19 +0000 Subject: [PATCH 3/4] fix(login): avoid panic when parsing auto-discovered SSH keys (#1100) ## Problem `tea login add` can panic while auto-discovering SSH keys. The interactive login flow calls `regexp.FindStringSubmatch` and immediately indexes `[1]` without checking whether the regex matched. When the selected key display string does not have the expected format, the returned slice is `nil` and tea crashes with: ``` panic: runtime error: index out of range [1] with length 0 ``` This is the crash reported in #527. ## Root cause `regexp.Regexp.FindStringSubmatch` returns `nil` when the input does not match. Indexing that result with `[1]` assumes a match and causes the panic. The same unchecked pattern exists for SSH certificates and plain public keys in `modules/interact/login.go`. ## Changes - Extract auto-discovered SSH key/certificate display parsing into `parseSSHPubkeySelection`. - Add a `regexpSubmatch` helper that returns an error when a regex does not match, so login fails with a descriptive error instead of panicking. - Add table-driven tests for local/agent keys, local/agent certificates, and malformed input. Fixes #527 --------- Co-authored-by: bircni Reviewed-on: https://gitea.com/gitea/tea/pulls/1100 Reviewed-by: bircni Co-authored-by: Lunny Xiao --- modules/interact/login.go | 56 +++++++++++++++++---------- modules/interact/login_test.go | 69 ++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 19 deletions(-) create mode 100644 modules/interact/login_test.go diff --git a/modules/interact/login.go b/modules/interact/login.go index b59d24b9..d0c0d2e2 100644 --- a/modules/interact/login.go +++ b/modules/interact/login.go @@ -200,25 +200,9 @@ func CreateLogin(ctx context.Context) error { } printTitleAndContent("Selected ssh-key:", sshKey) - // ssh certificate - if strings.Contains(sshKey, "principals") { - sshCertPrincipal = regexp.MustCompile(`.*?principals: (.*?)[,|\s]`).FindStringSubmatch(sshKey)[1] - if strings.Contains(sshKey, "(ssh-agent)") { - sshAgent = true - sshKey = "" - } else { - sshKey = regexp.MustCompile(`\((.*?)\)$`).FindStringSubmatch(sshKey)[1] - sshKey = strings.TrimSuffix(sshKey, "-cert.pub") - } - } else { - sshKeyFingerprint = regexp.MustCompile(`(SHA256:.*?)\s`).FindStringSubmatch(sshKey)[1] - if strings.Contains(sshKey, "(ssh-agent)") { - sshAgent = true - sshKey = "" - } else { - sshKey = regexp.MustCompile(`\((.*?)\)$`).FindStringSubmatch(sshKey)[1] - sshKey = strings.TrimSuffix(sshKey, ".pub") - } + sshKey, sshCertPrincipal, sshKeyFingerprint, sshAgent, err = parseSSHPubkeySelection(sshKey) + if err != nil { + return err } } } @@ -274,6 +258,40 @@ func CreateLogin(ctx context.Context) error { return task.CreateLogin(ctx, name, token, user, passwd, otp, scopes, sshKey, giteaURL, sshCertPrincipal, sshKeyFingerprint, insecure, sshAgent, versionCheck, helper) } +func parseSSHPubkeySelection(display string) (sshKey, sshCertPrincipal, sshKeyFingerprint string, sshAgent bool, err error) { + if strings.Contains(display, "principals") { + if sshCertPrincipal, err = regexpSubmatch(regexp.MustCompile(`.*?principals: (.*?)[,|\s]`), display); err != nil { + return "", "", "", false, fmt.Errorf("failed to parse SSH certificate principal from %q: %w", display, err) + } + if strings.HasSuffix(display, "(ssh-agent)") { + return "", sshCertPrincipal, "", true, nil + } + if sshKey, err = regexpSubmatch(regexp.MustCompile(`\((.*?)\)$`), display); err != nil { + return "", "", "", false, fmt.Errorf("failed to parse SSH certificate path from %q: %w", display, err) + } + return strings.TrimSuffix(sshKey, "-cert.pub"), sshCertPrincipal, "", false, nil + } + + if sshKeyFingerprint, err = regexpSubmatch(regexp.MustCompile(`(SHA256:.*?)\s`), display); err != nil { + return "", "", "", false, fmt.Errorf("failed to parse SSH key fingerprint from %q: %w", display, err) + } + if strings.HasSuffix(display, "(ssh-agent)") { + return "", "", sshKeyFingerprint, true, nil + } + if sshKey, err = regexpSubmatch(regexp.MustCompile(`\((.*?)\)$`), display); err != nil { + return "", "", "", false, fmt.Errorf("failed to parse SSH key path from %q: %w", display, err) + } + return strings.TrimSuffix(sshKey, ".pub"), "", sshKeyFingerprint, false, nil +} + +func regexpSubmatch(re *regexp.Regexp, s string) (string, error) { + match := re.FindStringSubmatch(s) + if len(match) < 2 { + return "", fmt.Errorf("no match") + } + return match[1], nil +} + var tokenScopeOpts = []string{ string(gitea.AccessTokenScopeAll), string(gitea.AccessTokenScopeRepo), diff --git a/modules/interact/login_test.go b/modules/interact/login_test.go new file mode 100644 index 00000000..e763ce4b --- /dev/null +++ b/modules/interact/login_test.go @@ -0,0 +1,69 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package interact + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParseSSHPubkeySelection(t *testing.T) { + tests := []struct { + name string + display string + wantSSHKey string + wantCertPrincipal string + wantKeyFingerprint string + wantSSHAgent bool + wantErr bool + }{ + { + name: "local ed25519 key", + display: "SHA256:abc ssh-ed25519 comment (/home/user/.ssh/id_ed25519.pub)", + wantSSHKey: "/home/user/.ssh/id_ed25519", + wantKeyFingerprint: "SHA256:abc", + }, + { + name: "agent ed25519 key", + display: "SHA256:abc ssh-ed25519 comment (ssh-agent)", + wantKeyFingerprint: "SHA256:abc", + wantSSHAgent: true, + }, + { + name: "local certificate", + display: "SHA256:abc ssh-ed25519-cert-v01@openssh.com comment - principals: user1,user2 (/home/user/.ssh/id_ed25519-cert.pub)", + wantSSHKey: "/home/user/.ssh/id_ed25519", + wantCertPrincipal: "user1", + }, + { + name: "agent certificate", + display: "SHA256:abc ssh-ed25519-cert-v01@openssh.com comment - principals: user1 (ssh-agent)", + wantCertPrincipal: "user1", + wantSSHAgent: true, + }, + { + name: "unexpected display", + display: "ssh-ed25519 comment", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sshKey, certPrincipal, keyFingerprint, sshAgent, err := parseSSHPubkeySelection(tt.display) + if tt.wantErr { + require.Error(t, err) + return + } + + require.NoError(t, err) + assert.Equal(t, tt.wantSSHKey, sshKey) + assert.Equal(t, tt.wantCertPrincipal, certPrincipal) + assert.Equal(t, tt.wantKeyFingerprint, keyFingerprint) + assert.Equal(t, tt.wantSSHAgent, sshAgent) + }) + } +} From 8bfdec40c6708f8be14d10b05e69aea487e607c1 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 28 Aug 2026 23:55:13 +0000 Subject: [PATCH 4/4] feat(login): add status command (#1087) (#1105) Implements #1087. Adds `tea login status [] [-o ]`, which verifies the stored token for one or all configured logins and reports: - login name/URL and default status - whether the token is valid (via `GET /api/v1/user`) - auth method and token expiry - whether the git credential helper is configured Machine-readable output is available via the usual `-o` formats with fields `name`, `url`, `user`, `valid`, `auth_method`, `token_expiry`, `helper`, and `default`. Reviewed-on: https://gitea.com/gitea/tea/pulls/1105 Reviewed-by: bircni --- cmd/login.go | 1 + cmd/login/status.go | 59 ++++++++++++ docs/CLI.md | 6 ++ modules/config/login.go | 8 ++ modules/print/login_status.go | 145 +++++++++++++++++++++++++++++ modules/print/login_status_test.go | 38 ++++++++ modules/task/login_create.go | 23 +++++ modules/task/login_status.go | 67 +++++++++++++ modules/task/login_status_test.go | 75 +++++++++++++++ 9 files changed, 422 insertions(+) create mode 100644 cmd/login/status.go create mode 100644 modules/print/login_status.go create mode 100644 modules/print/login_status_test.go create mode 100644 modules/task/login_status.go create mode 100644 modules/task/login_status_test.go diff --git a/cmd/login.go b/cmd/login.go index fddf6f4b..0a2de65d 100644 --- a/cmd/login.go +++ b/cmd/login.go @@ -31,6 +31,7 @@ var CmdLogin = cli.Command{ &login.CmdLoginSetDefault, &login.CmdLoginHelper, &login.CmdLoginOAuthRefresh, + &login.CmdLoginStatus, }, } diff --git a/cmd/login/status.go b/cmd/login/status.go new file mode 100644 index 00000000..9cb852ba --- /dev/null +++ b/cmd/login/status.go @@ -0,0 +1,59 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package login + +import ( + "context" + "fmt" + + "gitea.dev/tea/cmd/flags" + "gitea.dev/tea/modules/config" + "gitea.dev/tea/modules/print" + "gitea.dev/tea/modules/task" + + "github.com/urfave/cli/v3" +) + +// CmdLoginStatus represents a command to show authentication status for logins. +var CmdLoginStatus = cli.Command{ + Name: "status", + Usage: "Show authentication status for Gitea logins", + Description: `Verify the stored token for one or all Gitea logins and report its validity.`, + ArgsUsage: "[]", + Action: RunLoginStatus, + Flags: []cli.Flag{&flags.OutputFlag}, +} + +// RunLoginStatus verifies one login, or every configured login when no name is +// provided, and prints a short authentication report. +func RunLoginStatus(requestCtx context.Context, cmd *cli.Command) error { + var logins []config.Login + + switch cmd.Args().Len() { + case 0: + var err error + logins, err = config.GetLogins() + if err != nil { + return err + } + case 1: + login, err := config.GetLoginByName(cmd.Args().First()) + if err != nil { + return err + } + if login == nil { + return fmt.Errorf("login '%s' not found", cmd.Args().First()) + } + logins = []config.Login{*login} + default: + return fmt.Errorf("too many arguments") + } + + statuses := make([]print.LoginStatus, 0, len(logins)) + for i := range logins { + statuses = append(statuses, task.CheckLoginStatus(requestCtx, &logins[i])) + } + + return print.LoginStatuses(statuses, cmd.String("output")) +} diff --git a/docs/CLI.md b/docs/CLI.md index e9a57e65..2363574b 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -109,6 +109,12 @@ Return the stored token for a URL (git credential protocol) Refresh an OAuth token +### status + +Show authentication status for Gitea logins + +**--output, -o**="": Output format. (simple, table, csv, tsv, yaml, json) + ## logout Log out from a Gitea server diff --git a/modules/config/login.go b/modules/config/login.go index 3cd1adb7..7ae7968b 100644 --- a/modules/config/login.go +++ b/modules/config/login.go @@ -446,6 +446,14 @@ func (l *Login) Client(options ...gitea.ClientOption) *gitea.Client { 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. diff --git a/modules/print/login_status.go b/modules/print/login_status.go new file mode 100644 index 00000000..6ceb00ba --- /dev/null +++ b/modules/print/login_status.go @@ -0,0 +1,145 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package print + +import ( + "fmt" + "strings" + "time" +) + +// LoginStatus contains the authentication status of a single configured login. +type LoginStatus struct { + Name string + URL string + User string + Valid bool + AuthMethod string + TokenExpiry time.Time + Helper bool + Default bool + Error string +} + +// LoginStatusFields are the available fields to print with LoginStatuses. +var LoginStatusFields = []string{ + "name", + "url", + "user", + "valid", + "auth_method", + "token_expiry", + "helper", + "default", +} + +// LoginStatuses prints authentication status for one or more logins. +func LoginStatuses(statuses []LoginStatus, output string) error { + if output != "" { + printables := make([]printable, len(statuses)) + for i := range statuses { + printables[i] = statuses[i] + } + t := tableFromItems(LoginStatusFields, printables, isMachineReadable(output)) + return t.print(output) + } + + if len(statuses) == 0 { + fmt.Println("No logins configured.") + return nil + } + + for i, status := range statuses { + if i > 0 { + fmt.Println() + } + printLoginStatusReport(status) + } + return nil +} + +func printLoginStatusReport(status LoginStatus) { + name := status.Name + if status.Default { + name += " (default)" + } + fmt.Println(name) + + if status.Valid { + line := " ✔ Logged in to " + status.URL + if status.User != "" { + line += " as " + status.User + } + fmt.Println(line) + + tokenLine := " ✔ Token is valid" + if status.AuthMethod != "" { + tokenLine += " (" + status.AuthMethod + if !status.TokenExpiry.IsZero() { + tokenLine += ", " + formatTokenExpiry(status.TokenExpiry) + } + tokenLine += ")" + } + fmt.Println(tokenLine) + } else { + message := status.Error + if message == "" { + message = "Login failed" + } + fmt.Println(" ✗ " + message) + } + + if status.Helper { + fmt.Println(" ✔ Git credential helper configured") + } else { + fmt.Println(" ✗ Git credential helper not configured") + } +} + +func formatExpiryDuration(t time.Time) string { + d := time.Until(t) + if d < 0 { + return "expired" + } + if d < time.Minute { + return "in less than a minute" + } + return "in " + strings.TrimSuffix(d.Truncate(time.Minute).String(), "0s") +} + +func formatTokenExpiry(t time.Time) string { + if t.Before(time.Now()) { + return "expired" + } + return "expires " + formatExpiryDuration(t) +} + +// FormatField implements the printable interface for LoginStatus. +func (s LoginStatus) FormatField(field string, machineReadable bool) string { + switch field { + case "name": + return s.Name + case "url": + return s.URL + case "user": + return s.User + case "valid": + return formatBoolean(s.Valid, !machineReadable) + case "auth_method": + return s.AuthMethod + case "token_expiry": + if s.TokenExpiry.IsZero() { + return "" + } + if machineReadable { + return FormatTime(s.TokenExpiry, true) + } + return formatExpiryDuration(s.TokenExpiry) + case "helper": + return formatBoolean(s.Helper, !machineReadable) + case "default": + return formatBoolean(s.Default, !machineReadable) + } + return "" +} diff --git a/modules/print/login_status_test.go b/modules/print/login_status_test.go new file mode 100644 index 00000000..0f196e0a --- /dev/null +++ b/modules/print/login_status_test.go @@ -0,0 +1,38 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package print + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestLoginStatusFormatField(t *testing.T) { + status := LoginStatus{ + Name: "gitea", + URL: "https://gitea.com", + User: "alice", + Valid: true, + AuthMethod: "oauth", + TokenExpiry: time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC), + Helper: true, + Default: true, + } + + assert.Equal(t, "gitea", status.FormatField("name", false)) + assert.Equal(t, "https://gitea.com", status.FormatField("url", false)) + assert.Equal(t, "alice", status.FormatField("user", false)) + assert.Equal(t, "true", status.FormatField("valid", true)) + assert.Equal(t, "✔", status.FormatField("valid", false)) + assert.Equal(t, "oauth", status.FormatField("auth_method", true)) + assert.Equal(t, "2026-08-27T12:00:00Z", status.FormatField("token_expiry", true)) + assert.Equal(t, "true", status.FormatField("helper", true)) + assert.Equal(t, "✔", status.FormatField("default", false)) +} + +func TestFormatExpiryDurationExpired(t *testing.T) { + assert.Equal(t, "expired", formatExpiryDuration(time.Now().Add(-time.Hour))) +} diff --git a/modules/task/login_create.go b/modules/task/login_create.go index 2a0e1050..5b0b6720 100644 --- a/modules/task/login_create.go +++ b/modules/task/login_create.go @@ -48,6 +48,29 @@ func SetupHelper(login config.Login) (ok bool, err error) { return true, nil } +// HasGitCredentialHelper reports whether tea is registered as a git credential +// helper for the given login. It mirrors the global git config lookup used by +// SetupHelper. +func HasGitCredentialHelper(login config.Login) bool { + if login.URL == "" { + return false + } + + helperKey := fmt.Sprintf("credential.%s.helper", login.URL) + currentHelpers, err := exec.Command("git", "config", "--global", "--get-all", helperKey).Output() + if err != nil { + return false + } + + for _, line := range strings.Split(strings.ReplaceAll(string(currentHelpers), "\r", ""), "\n") { + if strings.HasSuffix(strings.TrimSpace(line), "login helper") { + return true + } + } + + return false +} + // CreateLogin create a login to be stored in config func CreateLogin(ctx stdctx.Context, name, token, user, passwd, otp, scopes, sshKey, giteaURL, sshCertPrincipal, sshKeyFingerprint string, insecure, sshAgent, versionCheck, addHelper bool) error { // checks ... diff --git a/modules/task/login_status.go b/modules/task/login_status.go new file mode 100644 index 00000000..b76a8974 --- /dev/null +++ b/modules/task/login_status.go @@ -0,0 +1,67 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package task + +import ( + "context" + "fmt" + "strings" + "time" + + "gitea.dev/tea/modules/config" + "gitea.dev/tea/modules/print" +) + +// CheckLoginStatus verifies the stored token for a login against the server and +// returns a printable status. Unlike config.Login.Client, refresh failures are +// captured in the returned status instead of terminating the process. +func CheckLoginStatus(ctx context.Context, login *config.Login) print.LoginStatus { + status := print.LoginStatus{ + Name: login.Name, + URL: login.URL, + AuthMethod: loginAuthMethod(login), + TokenExpiry: loginTokenExpiry(login), + Helper: HasGitCredentialHelper(*login), + Default: login.Default, + } + + if login.GetAccessToken() == "" { + status.Error = "Login failed: no access token configured" + return status + } + + if err := login.RefreshOAuthTokenIfNeeded(); err != nil { + status.Error = "Token refresh failed: " + strings.TrimPrefix(err.Error(), "failed to refresh token: ") + return status + } + + // A successful refresh updates the token in the secure store, so re-read the + // expiry for the status line. + status.TokenExpiry = loginTokenExpiry(login) + + user, _, err := login.ClientWithoutRefresh().Users.GetMyUserInfo(ctx) + if err != nil { + status.Error = fmt.Sprintf("Login failed: %s", err) + return status + } + + status.Valid = true + status.User = user.UserName + return status +} + +func loginAuthMethod(login *config.Login) string { + if login.IsOAuth() { + return config.AuthMethodOAuth + } + return "token" +} + +func loginTokenExpiry(login *config.Login) time.Time { + expiry := login.GetTokenExpiry() + if expiry.Equal(time.Unix(0, 0)) { + return time.Time{} + } + return expiry +} diff --git a/modules/task/login_status_test.go b/modules/task/login_status_test.go new file mode 100644 index 00000000..8fb4ac9c --- /dev/null +++ b/modules/task/login_status_test.go @@ -0,0 +1,75 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package task + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "gitea.dev/tea/modules/config" + + "github.com/stretchr/testify/assert" +) + +func TestCheckLoginStatus(t *testing.T) { + // Keep helper detection isolated from the developer's real git config. + t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(t.TempDir(), ".gitconfig")) + + t.Run("valid token", func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/api/v1/user", r.URL.Path) + assert.Equal(t, "token secret-token", r.Header.Get("Authorization")) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":1,"login":"alice"}`)) + })) + defer server.Close() + + status := CheckLoginStatus(context.Background(), &config.Login{ + Name: "test", + URL: server.URL, + Token: "secret-token", + VersionCheck: false, + }) + + assert.True(t, status.Valid) + assert.Empty(t, status.Error) + assert.Equal(t, "test", status.Name) + assert.Equal(t, server.URL, status.URL) + assert.Equal(t, "alice", status.User) + assert.Equal(t, "token", status.AuthMethod) + assert.False(t, status.Helper) + }) + + t.Run("invalid token", func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"message":"token is invalid"}`)) + })) + defer server.Close() + + status := CheckLoginStatus(context.Background(), &config.Login{ + Name: "test", + URL: server.URL, + Token: "expired-token", + VersionCheck: false, + }) + + assert.False(t, status.Valid) + assert.Contains(t, status.Error, "token is invalid") + }) + + t.Run("missing token", func(t *testing.T) { + status := CheckLoginStatus(context.Background(), &config.Login{ + Name: "test", + URL: "https://gitea.example.com", + }) + + assert.False(t, status.Valid) + assert.Contains(t, status.Error, "no access token configured") + }) +}