mugit/internal/ssh/ssh_test.go (view raw)
Oleksandr Smirnov
Oleksandr Smirnov
olexsmir@gmail.com ssh: some refactoring + test isAuthorized, 3 months ago
olexsmir@gmail.com ssh: some refactoring + test isAuthorized, 3 months ago
| 1 | package ssh |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "crypto/rsa" |
| 6 | "testing" |
| 7 | |
| 8 | gossh "golang.org/x/crypto/ssh" |
| 9 | "olexsmir.xyz/x/is" |
| 10 | ) |
| 11 | |
| 12 | func TestServer_isAuthorized(t *testing.T) { |
| 13 | key1, err := rsa.GenerateKey(rand.Reader, 2048) |
| 14 | is.Err(t, err, nil) |
| 15 | pub1, err := gossh.NewPublicKey(&key1.PublicKey) |
| 16 | is.Err(t, err, nil) |
| 17 | |
| 18 | key2, err := rsa.GenerateKey(rand.Reader, 2048) |
| 19 | is.Err(t, err, nil) |
| 20 | pub2, err := gossh.NewPublicKey(&key2.PublicKey) |
| 21 | is.Err(t, err, nil) |
| 22 | |
| 23 | tests := []struct { |
| 24 | name string |
| 25 | authKeys []gossh.PublicKey |
| 26 | checkKey gossh.PublicKey |
| 27 | wantAuth bool |
| 28 | }{ |
| 29 | { |
| 30 | name: "authorized key", |
| 31 | wantAuth: true, |
| 32 | authKeys: []gossh.PublicKey{pub1}, |
| 33 | checkKey: pub1, |
| 34 | }, |
| 35 | { |
| 36 | name: "unauthorized key", |
| 37 | wantAuth: false, |
| 38 | authKeys: []gossh.PublicKey{pub1}, |
| 39 | checkKey: pub2, |
| 40 | }, |
| 41 | { |
| 42 | name: "empty auth keys", |
| 43 | wantAuth: false, |
| 44 | authKeys: []gossh.PublicKey{}, |
| 45 | checkKey: pub1, |
| 46 | }, |
| 47 | { |
| 48 | name: "multiple auth keys - found", |
| 49 | wantAuth: true, |
| 50 | authKeys: []gossh.PublicKey{pub1, pub2}, |
| 51 | checkKey: pub2, |
| 52 | }, |
| 53 | } |
| 54 | |
| 55 | for _, tt := range tests { |
| 56 | t.Run(tt.name, func(t *testing.T) { |
| 57 | s := &Server{authKeys: tt.authKeys} |
| 58 | got := s.isAuthorized(tt.checkKey) |
| 59 | is.Equal(t, tt.wantAuth, got) |
| 60 | }) |
| 61 | } |
| 62 | } |