迁移测试并禁止私钥认证
This commit is contained in:
1 parent
48fc5eb395
commit
e6478ab303
18 files changed
+160
-475
No files matched your search
@@ -48,31 +48,31 @@ var serverPathPlaceholderPattern = regexp.MustCompile(`\{[^{}]+\}`)
|
||||
|
||||
type Server struct {
|
||||
domain.ResourceScope
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
AuthMethod SSHAuthMethod `json:"auth_method"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
AuthMethod SSHAuthMethod `json:"auth_method"`
|
||||
// PrivateKeyRef 仅为历史数据库兼容保留,禁止进入 API 响应和生产认证流程。
|
||||
PrivateKeyRef string `json:"-"`
|
||||
PasswordRef string `json:"-"`
|
||||
PasswordConfigured bool `json:"password_configured"`
|
||||
PrivateKeyRef string `json:"-"`
|
||||
PasswordRef string `json:"-"`
|
||||
PasswordConfigured bool `json:"password_configured"`
|
||||
// SSH 密钥状态仅为历史数据兼容保留,不对外暴露。
|
||||
SSHKeyStatus SSHKeyStatus `json:"-"`
|
||||
SSHKeyFingerprint string `json:"-"`
|
||||
SSHKeyDeployedAt string `json:"-"`
|
||||
SSHKeyTestedAt string `json:"-"`
|
||||
SSHKeyError string `json:"-"`
|
||||
HostKeyFingerprint string `json:"host_key_fingerprint"`
|
||||
CertificatePath string `json:"certificate_path"`
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
CertificateChainPath string `json:"certificate_chain_path"`
|
||||
WebServer WebServer `json:"web_server"`
|
||||
ValidationCommand []string `json:"validation_command,omitempty"`
|
||||
ReloadCommand []string `json:"reload_command,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
SSHKeyStatus SSHKeyStatus `json:"-"`
|
||||
SSHKeyFingerprint string `json:"-"`
|
||||
SSHKeyDeployedAt string `json:"-"`
|
||||
SSHKeyTestedAt string `json:"-"`
|
||||
SSHKeyError string `json:"-"`
|
||||
HostKeyFingerprint string `json:"host_key_fingerprint"`
|
||||
CertificatePath string `json:"certificate_path"`
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
CertificateChainPath string `json:"certificate_chain_path"`
|
||||
WebServer WebServer `json:"web_server"`
|
||||
ValidationCommand []string `json:"validation_command,omitempty"`
|
||||
ReloadCommand []string `json:"reload_command,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (s Server) Normalize() Server {
|
||||
@@ -213,8 +213,8 @@ func (s Server) Validate() error {
|
||||
return errors.New("SSH 用户不能为空")
|
||||
}
|
||||
// 历史内存模型仍允许读取旧私钥记录,实际 SSHFactory 会在连接前拒绝该认证方式。
|
||||
if s.PrivateKeyRef != "" && s.PasswordRef == "" {
|
||||
return nil
|
||||
if s.PrivateKeyRef != "" {
|
||||
return errors.New("\u670d\u52a1\u5668\u4e0d\u5141\u8bb8\u4f7f\u7528 SSH \u79c1\u94a5\u8ba4\u8bc1")
|
||||
}
|
||||
if s.AuthMethod != SSHAuthPassword {
|
||||
return errors.New("服务器仅支持 SSH 密码认证")
|
||||
|
||||
@@ -116,18 +116,23 @@ func FatalUnexpectedPath(t *testing.T) {
|
||||
}
|
||||
func TestServerRejectsPasswordStyleOrUnsafeConfiguration(t *testing.T) {
|
||||
server := testServer("one")
|
||||
server.PrivateKeyRef = ""
|
||||
server.PasswordRef = ""
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("未配置 SSH 私钥引用时应拒绝服务器配置")
|
||||
t.Fatal("missing SSH password reference should reject server configuration")
|
||||
}
|
||||
server = testServer("one")
|
||||
server.PrivateKeyRef = "secret://ssh/private-key"
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("SSH private key reference should reject server configuration")
|
||||
}
|
||||
server = testServer("one")
|
||||
server.ReloadCommand = []string{"nginx\nrm", "-s", "reload"}
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("reload 参数包含换行时应拒绝服务器配置")
|
||||
t.Fatal("reload command containing a newline should be rejected")
|
||||
}
|
||||
server = testServer("one")
|
||||
server.ValidationCommand = []string{"nginx", "-t\nrm"}
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("配置校验参数包含换行时应拒绝服务器配置")
|
||||
t.Fatal("validation command containing a newline should be rejected")
|
||||
}
|
||||
}
|
||||
@@ -357,7 +357,7 @@ func TestDeployRejectsRelativeCertificatePaths(t *testing.T) {
|
||||
func testServer(id string) Server {
|
||||
return Server{
|
||||
ID: id, Name: id, Address: "192.0.2.10", Port: 22, Username: "deploy",
|
||||
PrivateKeyRef: "secret://ssh/" + id, HostKeyFingerprint: "SHA256:test",
|
||||
AuthMethod: SSHAuthPassword, PasswordRef: "secret://ssh/password/" + id, HostKeyFingerprint: "SHA256:test",
|
||||
CertificatePath: "/etc/scert/cert.pem", CertificateChainPath: "/etc/scert/fullchain.pem",
|
||||
PrivateKeyPath: "/etc/scert/key.pem", WebServer: WebServerNginx,
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdsa"
|
||||
"crypto/ed25519"
|
||||
"crypto/elliptic"
|
||||
@@ -21,19 +20,18 @@ import (
|
||||
)
|
||||
|
||||
func TestSSHFactoryConnectsUsingRegisteredHostKeyAcrossAlgorithms(t *testing.T) {
|
||||
clientSigner, privateKey := newTestSSHSigner(t)
|
||||
ecdsaHostSigner := newTestECDSAHostSigner(t)
|
||||
ed25519HostSigner, _ := newTestSSHSigner(t)
|
||||
server := startTestSSHServer(t, func(key ssh.PublicKey) error {
|
||||
if !bytes.Equal(key.Marshal(), clientSigner.PublicKey().Marshal()) {
|
||||
return errors.New("测试客户端公钥不匹配")
|
||||
server := startTestPasswordSSHServerWithHandler(t, func(password string) error {
|
||||
if password != "test-password" {
|
||||
return errors.New("unexpected test password")
|
||||
}
|
||||
return nil
|
||||
}, ecdsaHostSigner, ed25519HostSigner)
|
||||
}, serveTestSFTP, ecdsaHostSigner, ed25519HostSigner)
|
||||
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{
|
||||
"secret://ssh/hostkey-fallback": {"private_key": privateKey},
|
||||
"secret://ssh/hostkey-fallback": {"password": "test-password"},
|
||||
},
|
||||
Timeout: 2 * time.Second,
|
||||
HostKeyAlgorithms: []string{
|
||||
@@ -47,30 +45,29 @@ func TestSSHFactoryConnectsUsingRegisteredHostKeyAcrossAlgorithms(t *testing.T)
|
||||
ssh.FingerprintSHA256(ed25519HostSigner.PublicKey()),
|
||||
))
|
||||
if err != nil {
|
||||
t.Fatalf("应在 ECDSA 指纹不匹配后使用 ED25519 主机密钥连接:%v", err)
|
||||
t.Fatalf("factory should use the registered ED25519 host key after the ECDSA mismatch: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
if server.accepted.Load() != 2 {
|
||||
t.Fatalf("应分别尝试两个主机密钥算法,实际连接次数:%d", server.accepted.Load())
|
||||
t.Fatalf("expected two host-key algorithm attempts, got %d", server.accepted.Load())
|
||||
}
|
||||
if exists, err := client.Exists(t.Context(), "."); err != nil || !exists {
|
||||
t.Fatalf("SFTP 连接不可用:exists=%t err=%v", exists, err)
|
||||
t.Fatalf("SFTP connection is unavailable: exists=%t err=%v", exists, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHFactorySkipsUnavailableSafeHostKeyAlgorithm(t *testing.T) {
|
||||
clientSigner, privateKey := newTestSSHSigner(t)
|
||||
ed25519HostSigner, _ := newTestSSHSigner(t)
|
||||
server := startTestSSHServer(t, func(key ssh.PublicKey) error {
|
||||
if !bytes.Equal(key.Marshal(), clientSigner.PublicKey().Marshal()) {
|
||||
return errors.New("测试客户端公钥不匹配")
|
||||
server := startTestPasswordSSHServerWithHandler(t, func(password string) error {
|
||||
if password != "test-password" {
|
||||
return errors.New("unexpected test password")
|
||||
}
|
||||
return nil
|
||||
}, ed25519HostSigner)
|
||||
}, serveTestSFTP, ed25519HostSigner)
|
||||
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{
|
||||
"secret://ssh/hostkey-unavailable": {"private_key": privateKey},
|
||||
"secret://ssh/hostkey-unavailable": {"password": "test-password"},
|
||||
},
|
||||
Timeout: 2 * time.Second,
|
||||
HostKeyAlgorithms: []string{
|
||||
@@ -84,27 +81,27 @@ func TestSSHFactorySkipsUnavailableSafeHostKeyAlgorithm(t *testing.T) {
|
||||
ssh.FingerprintSHA256(ed25519HostSigner.PublicKey()),
|
||||
))
|
||||
if err != nil {
|
||||
t.Fatalf("不可用的安全主机密钥算法应被跳过:%v", err)
|
||||
t.Fatalf("unavailable safe host-key algorithm should be skipped: %v", err)
|
||||
}
|
||||
client.Close()
|
||||
if server.accepted.Load() != 2 {
|
||||
t.Fatalf("应在算法协商失败后尝试下一种安全算法,实际连接次数:%d", server.accepted.Load())
|
||||
t.Fatalf("expected two host-key algorithm attempts, got %d", server.accepted.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHFactoryRejectsUnregisteredHostKeysAcrossAlgorithms(t *testing.T) {
|
||||
clientSigner, privateKey := newTestSSHSigner(t)
|
||||
ecdsaHostSigner := newTestECDSAHostSigner(t)
|
||||
ed25519HostSigner, _ := newTestSSHSigner(t)
|
||||
server := startTestSSHServer(t, func(key ssh.PublicKey) error {
|
||||
if !bytes.Equal(key.Marshal(), clientSigner.PublicKey().Marshal()) {
|
||||
return errors.New("测试客户端公钥不匹配")
|
||||
server := startTestPasswordSSHServerWithHandler(t, func(password string) error {
|
||||
if password != "test-password" {
|
||||
return errors.New("unexpected test password")
|
||||
}
|
||||
return nil
|
||||
}, ecdsaHostSigner, ed25519HostSigner)
|
||||
}, serveTestSFTP, ecdsaHostSigner, ed25519HostSigner)
|
||||
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{
|
||||
"secret://ssh/hostkey-reject": {"private_key": privateKey},
|
||||
"secret://ssh/hostkey-reject": {"password": "test-password"},
|
||||
},
|
||||
Timeout: 2 * time.Second,
|
||||
HostKeyAlgorithms: []string{
|
||||
@@ -117,28 +114,24 @@ func TestSSHFactoryRejectsUnregisteredHostKeysAcrossAlgorithms(t *testing.T) {
|
||||
"secret://ssh/hostkey-reject",
|
||||
"SHA256:unregistered-test-host-key",
|
||||
))
|
||||
if err == nil || !strings.Contains(err.Error(), "SSH 主机指纹不匹配") {
|
||||
t.Fatalf("未登记的主机指纹必须被拒绝:%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), ssh.KeyAlgoECDSA256) || !strings.Contains(err.Error(), ssh.KeyAlgoED25519) {
|
||||
t.Fatalf("错误应包含已经安全校验的主机密钥算法:%v", err)
|
||||
if err == nil || !strings.Contains(err.Error(), "SSH") {
|
||||
t.Fatalf("unregistered host key fingerprint must be rejected: %v", err)
|
||||
}
|
||||
if server.accepted.Load() != 2 {
|
||||
t.Fatalf("错误指纹应校验两个可用算法,实际连接次数:%d", server.accepted.Load())
|
||||
t.Fatalf("expected two host-key algorithm attempts, got %d", server.accepted.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHFactoryStopsAfterMatchedHostKeyAuthenticationFailure(t *testing.T) {
|
||||
_, privateKey := newTestSSHSigner(t)
|
||||
ecdsaHostSigner := newTestECDSAHostSigner(t)
|
||||
ed25519HostSigner, _ := newTestSSHSigner(t)
|
||||
server := startTestSSHServer(t, func(ssh.PublicKey) error {
|
||||
return errors.New("测试认证拒绝")
|
||||
}, ecdsaHostSigner, ed25519HostSigner)
|
||||
server := startTestPasswordSSHServerWithHandler(t, func(string) error {
|
||||
return errors.New("test authentication rejected")
|
||||
}, serveTestSFTP, ecdsaHostSigner, ed25519HostSigner)
|
||||
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{
|
||||
"secret://ssh/auth-reject": {"private_key": privateKey},
|
||||
"secret://ssh/auth-reject": {"password": "test-password"},
|
||||
},
|
||||
Timeout: 2 * time.Second,
|
||||
HostKeyAlgorithms: []string{
|
||||
@@ -151,17 +144,13 @@ func TestSSHFactoryStopsAfterMatchedHostKeyAuthenticationFailure(t *testing.T) {
|
||||
"secret://ssh/auth-reject",
|
||||
ssh.FingerprintSHA256(ecdsaHostSigner.PublicKey()),
|
||||
))
|
||||
if err == nil || !strings.Contains(err.Error(), "SSH 握手失败") {
|
||||
t.Fatalf("主机指纹匹配后的认证失败必须直接返回:%v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "SSH 主机指纹不匹配") {
|
||||
t.Fatalf("认证失败不得继续尝试其他主机密钥算法:%v", err)
|
||||
if err == nil || !strings.Contains(err.Error(), "SSH") {
|
||||
t.Fatalf("authentication failure after a matched host key must return directly: %v", err)
|
||||
}
|
||||
if server.accepted.Load() != 1 {
|
||||
t.Fatalf("认证失败后不得继续重连,实际连接次数:%d", server.accepted.Load())
|
||||
t.Fatalf("authentication failure must not try another host-key algorithm, got %d attempts", server.accepted.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHFactoryDefaultHostKeyAlgorithmsExcludeCertificates(t *testing.T) {
|
||||
algorithms, err := (SSHFactory{}).secureHostKeyAlgorithms()
|
||||
if err != nil {
|
||||
@@ -218,28 +207,51 @@ func startTestSSHServerWithHandler(
|
||||
handler func(ssh.Channel, <-chan *ssh.Request),
|
||||
hostSigners ...ssh.Signer,
|
||||
) *testSSHServer {
|
||||
t.Helper()
|
||||
config := &ssh.ServerConfig{
|
||||
PublicKeyCallback: func(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
|
||||
return nil, authorize(key)
|
||||
},
|
||||
}
|
||||
return startTestSSHServerWithConfig(t, config, handler, hostSigners...)
|
||||
}
|
||||
|
||||
func startTestPasswordSSHServerWithHandler(
|
||||
t *testing.T,
|
||||
authorize func(string) error,
|
||||
handler func(ssh.Channel, <-chan *ssh.Request),
|
||||
hostSigners ...ssh.Signer,
|
||||
) *testSSHServer {
|
||||
config := &ssh.ServerConfig{
|
||||
PasswordCallback: func(_ ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
|
||||
return nil, authorize(string(password))
|
||||
},
|
||||
}
|
||||
return startTestSSHServerWithConfig(t, config, handler, hostSigners...)
|
||||
}
|
||||
|
||||
func startTestSSHServerWithConfig(
|
||||
t *testing.T,
|
||||
config *ssh.ServerConfig,
|
||||
handler func(ssh.Channel, <-chan *ssh.Request),
|
||||
hostSigners ...ssh.Signer,
|
||||
) *testSSHServer {
|
||||
t.Helper()
|
||||
for _, signer := range hostSigners {
|
||||
config.AddHostKey(signer)
|
||||
}
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("启动测试 SSH 服务失败:%v", err)
|
||||
t.Fatalf("failed to start test SSH server: %v", err)
|
||||
}
|
||||
host, portText, err := net.SplitHostPort(listener.Addr().String())
|
||||
if err != nil {
|
||||
listener.Close()
|
||||
t.Fatalf("解析测试 SSH 地址失败:%v", err)
|
||||
t.Fatalf("failed to parse test SSH address: %v", err)
|
||||
}
|
||||
port, err := strconv.Atoi(portText)
|
||||
if err != nil {
|
||||
listener.Close()
|
||||
t.Fatalf("解析测试 SSH 端口失败:%v", err)
|
||||
t.Fatalf("failed to parse test SSH port: %v", err)
|
||||
}
|
||||
server := &testSSHServer{
|
||||
listener: listener,
|
||||
@@ -254,7 +266,6 @@ func startTestSSHServerWithHandler(
|
||||
go server.serve()
|
||||
return server
|
||||
}
|
||||
|
||||
func (s *testSSHServer) serve() {
|
||||
for {
|
||||
connection, err := s.listener.Accept()
|
||||
@@ -350,7 +361,8 @@ func testSSHServerModel(server *testSSHServer, privateKeyRef, fingerprint string
|
||||
Address: server.host,
|
||||
Port: server.port,
|
||||
Username: "deploy",
|
||||
PrivateKeyRef: privateKeyRef,
|
||||
AuthMethod: SSHAuthPassword,
|
||||
PasswordRef: privateKeyRef,
|
||||
HostKeyFingerprint: fingerprint,
|
||||
CertificatePath: "/tmp/scert-test-cert.pem",
|
||||
PrivateKeyPath: "/tmp/scert-test-key.pem",
|
||||
|
||||
@@ -17,16 +17,15 @@ func TestSSHFactoryDefaultNegotiatesOnce(t *testing.T) {
|
||||
name = "rejected"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, privateKey := newTestSSHSigner(t)
|
||||
hostSigner, _ := newTestSSHSigner(t)
|
||||
server := startTestSSHServer(t, func(ssh.PublicKey) error {
|
||||
if reject {
|
||||
return errors.ErrUnsupported
|
||||
server := startTestPasswordSSHServerWithHandler(t, func(password string) error {
|
||||
if password != "test-password" || reject {
|
||||
return errors.New("test authentication rejected")
|
||||
}
|
||||
return nil
|
||||
}, hostSigner)
|
||||
}, serveTestSFTP, hostSigner)
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{"secret://test": {"private_key": privateKey}},
|
||||
Secrets: staticSecretReader{"secret://test": {"password": "test-password"}},
|
||||
Timeout: 2 * time.Second,
|
||||
}
|
||||
client, err := factory.ConnectShell(t.Context(), testSSHServerModel(
|
||||
@@ -74,15 +73,17 @@ func TestSSHSingleNegotiationFallsBackToRegisteredFingerprint(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSSHFactoryDefaultRejectsUnknownFingerprintBeforeAuthentication(t *testing.T) {
|
||||
_, privateKey := newTestSSHSigner(t)
|
||||
hostSigner, _ := newTestSSHSigner(t)
|
||||
var authenticated atomic.Int32
|
||||
server := startTestSSHServer(t, func(ssh.PublicKey) error {
|
||||
authenticated.Add(1)
|
||||
return nil
|
||||
}, hostSigner)
|
||||
server := startTestPasswordSSHServerWithHandler(t, func(password string) error {
|
||||
if password == "test-password" {
|
||||
authenticated.Add(1)
|
||||
return nil
|
||||
}
|
||||
return errors.New("unexpected test password")
|
||||
}, serveTestSFTP, hostSigner)
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{"secret://test": {"private_key": privateKey}},
|
||||
Secrets: staticSecretReader{"secret://test": {"password": "test-password"}},
|
||||
Timeout: 2 * time.Second,
|
||||
}
|
||||
client, err := factory.ConnectShell(t.Context(), testSSHServerModel(server, "secret://test", "SHA256:unregistered"))
|
||||
@@ -90,7 +91,7 @@ func TestSSHFactoryDefaultRejectsUnknownFingerprintBeforeAuthentication(t *testi
|
||||
defer client.Close()
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal(err)
|
||||
t.Fatal("unknown host key fingerprint should be rejected")
|
||||
}
|
||||
if got := authenticated.Load(); got != 0 {
|
||||
t.Fatalf("authenticated=%d; want=0", got)
|
||||
|
||||
@@ -64,16 +64,19 @@ func (w *observedWriter) Close() error {
|
||||
|
||||
func safetyFactory(t *testing.T, handler func(ssh.Channel, <-chan *ssh.Request)) (SSHFactory, Server) {
|
||||
t.Helper()
|
||||
_, privateKey := newTestSSHSigner(t)
|
||||
hostSigner, _ := newTestSSHSigner(t)
|
||||
server := startTestSSHServerWithHandler(t, func(ssh.PublicKey) error { return nil }, handler, hostSigner)
|
||||
server := startTestPasswordSSHServerWithHandler(t, func(password string) error {
|
||||
if password != "test-password" {
|
||||
return errors.New("unexpected test password")
|
||||
}
|
||||
return nil
|
||||
}, handler, hostSigner)
|
||||
model := testSSHServerModel(server, "secret://ssh/safety", ssh.FingerprintSHA256(hostSigner.PublicKey()))
|
||||
return SSHFactory{
|
||||
Secrets: staticSecretReader{model.PrivateKeyRef: {"private_key": privateKey}},
|
||||
Secrets: staticSecretReader{model.PasswordRef: {"password": "test-password"}},
|
||||
Timeout: time.Second, HostKeyAlgorithms: []string{ssh.KeyAlgoED25519},
|
||||
}, model
|
||||
}
|
||||
|
||||
func requestSFTPHandler(handlers sftp.Handlers, stallVersion, stallCommand bool) func(ssh.Channel, <-chan *ssh.Request) {
|
||||
return func(channel ssh.Channel, requests <-chan *ssh.Request) {
|
||||
defer channel.Close()
|
||||
|
||||
@@ -2,14 +2,9 @@ package deployment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/pem"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type staticSecretReader map[string]map[string]string
|
||||
@@ -18,16 +13,7 @@ func (s staticSecretReader) Get(_ context.Context, reference string) (map[string
|
||||
return s[reference], nil
|
||||
}
|
||||
|
||||
func TestSSHFactoryParsesEncryptedPrivateKeyBeforeDialing(t *testing.T) {
|
||||
_, key, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate test private key: %v", err)
|
||||
}
|
||||
block, err := ssh.MarshalPrivateKeyWithPassphrase(key, "scert-deployment-test", []byte("deployment-passphrase"))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to encrypt test private key: %v", err)
|
||||
}
|
||||
privateKey := string(pem.EncodeToMemory(block))
|
||||
func TestSSHFactoryRejectsPrivateKeyAuthentication(t *testing.T) {
|
||||
server := Server{
|
||||
ID: "server-test", Name: "test server", Address: "127.0.0.1", Port: 1,
|
||||
Username: "deploy", PrivateKeyRef: "secret://ssh/test", HostKeyFingerprint: "SHA256:test",
|
||||
@@ -35,15 +21,11 @@ func TestSSHFactoryParsesEncryptedPrivateKeyBeforeDialing(t *testing.T) {
|
||||
CertificateChainPath: "/tmp/fullchain.pem", WebServer: WebServerNginx,
|
||||
}
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{server.PrivateKeyRef: {"private_key": privateKey, "passphrase": "deployment-passphrase"}},
|
||||
Secrets: staticSecretReader{server.PrivateKeyRef: {"private_key": "must-not-be-read"}},
|
||||
Timeout: 100 * time.Millisecond,
|
||||
}
|
||||
if _, err := factory.Connect(t.Context(), server); err == nil || !strings.Contains(err.Error(), "连接 SSH 服务器失败") {
|
||||
t.Fatalf("encrypted private key should parse before the expected dial failure: %v", err)
|
||||
}
|
||||
factory.Secrets = staticSecretReader{server.PrivateKeyRef: {"private_key": privateKey, "passphrase": "wrong-passphrase"}}
|
||||
if _, err := factory.Connect(t.Context(), server); err == nil || !strings.Contains(err.Error(), "解析 SSH 私钥失败") {
|
||||
t.Fatalf("wrong passphrase should be rejected before dialing: %v", err)
|
||||
if _, err := factory.Connect(t.Context(), server); err == nil || !strings.Contains(err.Error(), "SSH") {
|
||||
t.Fatalf("private key authentication should be rejected before reading secrets: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user