gitea.tea/modules/utils/ssh_host_test.go
GyeongHo Kim 511884b2af
fix(login): default SSH host to URL hostname
Use the server URL hostname when a login has no explicit SSHHost configured, so an HTTP(S) port from the Gitea URL is not reused as the SSH endpoint.

Add shared SSH host normalization and resolution helpers with tests for host and host:port values.

Signed-off-by: GyeongHo Kim <gyeongho.dev@proton.me>
2026-07-29 14:05:35 +09:00

132 lines
2.5 KiB
Go

// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package utils
import (
"net/url"
"testing"
)
func TestNormalizeSSHHost(t *testing.T) {
tests := []struct {
name string
raw string
want string
wantErr bool
}{
{
name: "empty",
raw: "",
want: "",
},
{
name: "host",
raw: "gitea.example.com",
want: "gitea.example.com",
},
{
name: "host with port",
raw: "gitea.example.com:2222",
want: "gitea.example.com:2222",
},
{
name: "trim spaces",
raw: " gitea.example.com:2222 ",
want: "gitea.example.com:2222",
},
{
name: "bracketed IPv6 with port",
raw: "[::1]:2222",
want: "[::1]:2222",
},
{
name: "URL",
raw: "ssh://gitea.example.com:2222",
wantErr: true,
},
{
name: "path",
raw: "gitea.example.com/owner/repo",
wantErr: true,
},
{
name: "user",
raw: "git@gitea.example.com",
wantErr: true,
},
{
name: "invalid port",
raw: "gitea.example.com:ssh",
wantErr: true,
},
{
name: "missing port",
raw: "gitea.example.com:",
wantErr: true,
},
{
name: "missing host",
raw: ":2222",
wantErr: true,
},
{
name: "bare IPv6",
raw: "::1",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NormalizeSSHHost(tt.raw)
if (err != nil) != tt.wantErr {
t.Fatalf("NormalizeSSHHost() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Fatalf("NormalizeSSHHost() = %q, want %q", got, tt.want)
}
})
}
}
func TestResolveSSHHost(t *testing.T) {
serverURL, err := url.Parse("https://gitea.example.com:3000")
if err != nil {
t.Fatal(err)
}
tests := []struct {
name string
explicitSSHHost string
want string
}{
{
name: "uses URL hostname by default",
want: "gitea.example.com",
},
{
name: "uses explicit host",
explicitSSHHost: "ssh.example.com",
want: "ssh.example.com",
},
{
name: "uses explicit host with port",
explicitSSHHost: "ssh.example.com:2222",
want: "ssh.example.com:2222",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ResolveSSHHost(serverURL, tt.explicitSSHHost)
if err != nil {
t.Fatalf("ResolveSSHHost() error = %v", err)
}
if got != tt.want {
t.Fatalf("ResolveSSHHost() = %q, want %q", got, tt.want)
}
})
}
}