Skip to content

Commit f79e692

Browse files
committed
Update AddHostKey to avoid always appending
1 parent 63518b5 commit f79e692

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

server.go

+12
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,18 @@ func (srv *Server) ListenAndServe() error {
315315
func (srv *Server) AddHostKey(key Signer) {
316316
// these are later added via AddHostKey on ServerConfig, which performs the
317317
// check for one of every algorithm.
318+
319+
// This check is based on the AddHostKey method from the x/crypto/ssh
320+
// library. This allows us to only keep one active key for each type on a
321+
// server at once. So, if you're dynamically updating keys at runtime, this
322+
// list will not keep growing.
323+
for i, k := range srv.HostSigners {
324+
if k.PublicKey().Type() == key.PublicKey().Type() {
325+
srv.HostSigners[i] = key
326+
return
327+
}
328+
}
329+
318330
srv.HostSigners = append(srv.HostSigners, key)
319331
}
320332

server_test.go

+20
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,26 @@ import (
88
"time"
99
)
1010

11+
func TestAddHostKey(t *testing.T) {
12+
s := Server{}
13+
signer, err := generateSigner()
14+
if err != nil {
15+
t.Fatal(err)
16+
}
17+
s.AddHostKey(signer)
18+
if len(s.HostSigners) != 1 {
19+
t.Fatal("Key was not properly added")
20+
}
21+
signer, err = generateSigner()
22+
if err != nil {
23+
t.Fatal(err)
24+
}
25+
s.AddHostKey(signer)
26+
if len(s.HostSigners) != 1 {
27+
t.Fatal("Key was not properly replaced")
28+
}
29+
}
30+
1131
func TestServerShutdown(t *testing.T) {
1232
l := newLocalListener()
1333
testBytes := []byte("Hello world\n")

0 commit comments

Comments
 (0)