4
0

ssh_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. package api
  2. import (
  3. "bytes"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "io/ioutil"
  11. "net/http"
  12. "net/http/httptest"
  13. "reflect"
  14. "strings"
  15. "testing"
  16. "time"
  17. "github.com/smallstep/assert"
  18. "github.com/smallstep/certificates/authority"
  19. "github.com/smallstep/certificates/authority/provisioner"
  20. "github.com/smallstep/certificates/logging"
  21. "github.com/smallstep/certificates/templates"
  22. "golang.org/x/crypto/ssh"
  23. )
  24. var (
  25. sshSignerKey = mustKey()
  26. sshUserKey = mustKey()
  27. sshHostKey = mustKey()
  28. )
  29. func mustKey() *ecdsa.PrivateKey {
  30. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  31. if err != nil {
  32. panic(err)
  33. }
  34. return priv
  35. }
  36. func signSSHCertificate(cert *ssh.Certificate) error {
  37. signerKey, err := ssh.NewPublicKey(sshSignerKey.Public())
  38. if err != nil {
  39. return err
  40. }
  41. signer, err := ssh.NewSignerFromSigner(sshSignerKey)
  42. if err != nil {
  43. return err
  44. }
  45. cert.SignatureKey = signerKey
  46. data := cert.Marshal()
  47. data = data[:len(data)-4]
  48. sig, err := signer.Sign(rand.Reader, data)
  49. if err != nil {
  50. return err
  51. }
  52. cert.Signature = sig
  53. return nil
  54. }
  55. func getSignedUserCertificate() (*ssh.Certificate, error) {
  56. key, err := ssh.NewPublicKey(sshUserKey.Public())
  57. if err != nil {
  58. return nil, err
  59. }
  60. t := time.Now()
  61. cert := &ssh.Certificate{
  62. Nonce: []byte("1234567890"),
  63. Key: key,
  64. Serial: 1234567890,
  65. CertType: ssh.UserCert,
  66. KeyId: "user@localhost",
  67. ValidPrincipals: []string{"user"},
  68. ValidAfter: uint64(t.Unix()),
  69. ValidBefore: uint64(t.Add(time.Hour).Unix()),
  70. Permissions: ssh.Permissions{
  71. CriticalOptions: map[string]string{},
  72. Extensions: map[string]string{
  73. "permit-X11-forwarding": "",
  74. "permit-agent-forwarding": "",
  75. "permit-port-forwarding": "",
  76. "permit-pty": "",
  77. "permit-user-rc": "",
  78. },
  79. },
  80. Reserved: []byte{},
  81. }
  82. if err := signSSHCertificate(cert); err != nil {
  83. return nil, err
  84. }
  85. return cert, nil
  86. }
  87. func getSignedHostCertificate() (*ssh.Certificate, error) {
  88. key, err := ssh.NewPublicKey(sshHostKey.Public())
  89. if err != nil {
  90. return nil, err
  91. }
  92. t := time.Now()
  93. cert := &ssh.Certificate{
  94. Nonce: []byte("1234567890"),
  95. Key: key,
  96. Serial: 1234567890,
  97. CertType: ssh.UserCert,
  98. KeyId: "internal.smallstep.com",
  99. ValidPrincipals: []string{"internal.smallstep.com"},
  100. ValidAfter: uint64(t.Unix()),
  101. ValidBefore: uint64(t.Add(time.Hour).Unix()),
  102. Permissions: ssh.Permissions{
  103. CriticalOptions: map[string]string{},
  104. Extensions: map[string]string{},
  105. },
  106. Reserved: []byte{},
  107. }
  108. if err := signSSHCertificate(cert); err != nil {
  109. return nil, err
  110. }
  111. return cert, nil
  112. }
  113. func TestSSHCertificate_MarshalJSON(t *testing.T) {
  114. user, err := getSignedUserCertificate()
  115. assert.FatalError(t, err)
  116. host, err := getSignedHostCertificate()
  117. assert.FatalError(t, err)
  118. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  119. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  120. type fields struct {
  121. Certificate *ssh.Certificate
  122. }
  123. tests := []struct {
  124. name string
  125. fields fields
  126. want []byte
  127. wantErr bool
  128. }{
  129. {"nil", fields{Certificate: nil}, []byte("null"), false},
  130. {"user", fields{Certificate: user}, []byte(`"` + userB64 + `"`), false},
  131. {"user", fields{Certificate: host}, []byte(`"` + hostB64 + `"`), false},
  132. }
  133. for _, tt := range tests {
  134. t.Run(tt.name, func(t *testing.T) {
  135. c := SSHCertificate{
  136. Certificate: tt.fields.Certificate,
  137. }
  138. got, err := c.MarshalJSON()
  139. if (err != nil) != tt.wantErr {
  140. t.Errorf("SSHCertificate.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  141. return
  142. }
  143. if !reflect.DeepEqual(got, tt.want) {
  144. t.Errorf("SSHCertificate.MarshalJSON() = %v, want %v", got, tt.want)
  145. }
  146. })
  147. }
  148. }
  149. func TestSSHCertificate_UnmarshalJSON(t *testing.T) {
  150. user, err := getSignedUserCertificate()
  151. assert.FatalError(t, err)
  152. host, err := getSignedHostCertificate()
  153. assert.FatalError(t, err)
  154. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  155. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  156. keyB64 := base64.StdEncoding.EncodeToString(user.Key.Marshal())
  157. type args struct {
  158. data []byte
  159. }
  160. tests := []struct {
  161. name string
  162. args args
  163. want *ssh.Certificate
  164. wantErr bool
  165. }{
  166. {"null", args{[]byte(`null`)}, nil, false},
  167. {"empty", args{[]byte(`""`)}, nil, false},
  168. {"user", args{[]byte(`"` + userB64 + `"`)}, user, false},
  169. {"host", args{[]byte(`"` + hostB64 + `"`)}, host, false},
  170. {"bad-string", args{[]byte(userB64)}, nil, true},
  171. {"bad-base64", args{[]byte(`"this-is-not-base64"`)}, nil, true},
  172. {"bad-key", args{[]byte(`"bm90LWEta2V5"`)}, nil, true},
  173. {"bat-cert", args{[]byte(`"` + keyB64 + `"`)}, nil, true},
  174. }
  175. for _, tt := range tests {
  176. t.Run(tt.name, func(t *testing.T) {
  177. c := &SSHCertificate{}
  178. if err := c.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr {
  179. t.Errorf("SSHCertificate.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  180. }
  181. if !reflect.DeepEqual(tt.want, c.Certificate) {
  182. t.Errorf("SSHCertificate.UnmarshalJSON() got = %v, want %v\n", c.Certificate, tt.want)
  183. }
  184. })
  185. }
  186. }
  187. func TestSignSSHRequest_Validate(t *testing.T) {
  188. type fields struct {
  189. PublicKey []byte
  190. OTT string
  191. CertType string
  192. Principals []string
  193. ValidAfter TimeDuration
  194. ValidBefore TimeDuration
  195. AddUserPublicKey []byte
  196. }
  197. tests := []struct {
  198. name string
  199. fields fields
  200. wantErr bool
  201. }{
  202. {"ok-empty", fields{[]byte("Zm9v"), "ott", "", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, false},
  203. {"ok-user", fields{[]byte("Zm9v"), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, false},
  204. {"ok-host", fields{[]byte("Zm9v"), "ott", "host", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, false},
  205. {"key", fields{nil, "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
  206. {"key", fields{[]byte(""), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
  207. {"type", fields{[]byte("Zm9v"), "ott", "foo", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
  208. {"ott", fields{[]byte("Zm9v"), "", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
  209. }
  210. for _, tt := range tests {
  211. t.Run(tt.name, func(t *testing.T) {
  212. s := &SSHSignRequest{
  213. PublicKey: tt.fields.PublicKey,
  214. OTT: tt.fields.OTT,
  215. CertType: tt.fields.CertType,
  216. Principals: tt.fields.Principals,
  217. ValidAfter: tt.fields.ValidAfter,
  218. ValidBefore: tt.fields.ValidBefore,
  219. AddUserPublicKey: tt.fields.AddUserPublicKey,
  220. }
  221. if err := s.Validate(); (err != nil) != tt.wantErr {
  222. t.Errorf("SignSSHRequest.Validate() error = %v, wantErr %v", err, tt.wantErr)
  223. }
  224. })
  225. }
  226. }
  227. func Test_caHandler_SSHSign(t *testing.T) {
  228. user, err := getSignedUserCertificate()
  229. assert.FatalError(t, err)
  230. host, err := getSignedHostCertificate()
  231. assert.FatalError(t, err)
  232. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  233. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  234. userReq, err := json.Marshal(SSHSignRequest{
  235. PublicKey: user.Key.Marshal(),
  236. OTT: "ott",
  237. })
  238. assert.FatalError(t, err)
  239. hostReq, err := json.Marshal(SSHSignRequest{
  240. PublicKey: host.Key.Marshal(),
  241. OTT: "ott",
  242. })
  243. assert.FatalError(t, err)
  244. userAddReq, err := json.Marshal(SSHSignRequest{
  245. PublicKey: user.Key.Marshal(),
  246. OTT: "ott",
  247. AddUserPublicKey: user.Key.Marshal(),
  248. })
  249. assert.FatalError(t, err)
  250. tests := []struct {
  251. name string
  252. req []byte
  253. authErr error
  254. signCert *ssh.Certificate
  255. signErr error
  256. addUserCert *ssh.Certificate
  257. addUserErr error
  258. body []byte
  259. statusCode int
  260. }{
  261. {"ok-user", userReq, nil, user, nil, nil, nil, []byte(fmt.Sprintf(`{"crt":"%s"}`, userB64)), http.StatusCreated},
  262. {"ok-host", hostReq, nil, host, nil, nil, nil, []byte(fmt.Sprintf(`{"crt":"%s"}`, hostB64)), http.StatusCreated},
  263. {"ok-user-add", userAddReq, nil, user, nil, user, nil, []byte(fmt.Sprintf(`{"crt":"%s","addUserCrt":"%s"}`, userB64, userB64)), http.StatusCreated},
  264. {"fail-body", []byte("bad-json"), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  265. {"fail-validate", []byte("{}"), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  266. {"fail-publicKey", []byte(`{"publicKey":"Zm9v","ott":"ott"}`), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  267. {"fail-publicKey", []byte(fmt.Sprintf(`{"publicKey":"%s","ott":"ott","addUserPublicKey":"Zm9v"}`, base64.StdEncoding.EncodeToString(user.Key.Marshal()))), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  268. {"fail-authorize", userReq, fmt.Errorf("an-error"), nil, nil, nil, nil, nil, http.StatusUnauthorized},
  269. {"fail-signSSH", userReq, nil, nil, fmt.Errorf("an-error"), nil, nil, nil, http.StatusForbidden},
  270. {"fail-SignSSHAddUser", userAddReq, nil, user, nil, nil, fmt.Errorf("an-error"), nil, http.StatusForbidden},
  271. }
  272. for _, tt := range tests {
  273. t.Run(tt.name, func(t *testing.T) {
  274. h := New(&mockAuthority{
  275. authorizeSign: func(ott string) ([]provisioner.SignOption, error) {
  276. return []provisioner.SignOption{}, tt.authErr
  277. },
  278. signSSH: func(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  279. return tt.signCert, tt.signErr
  280. },
  281. signSSHAddUser: func(key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error) {
  282. return tt.addUserCert, tt.addUserErr
  283. },
  284. }).(*caHandler)
  285. req := httptest.NewRequest("POST", "http://example.com/ssh/sign", bytes.NewReader(tt.req))
  286. w := httptest.NewRecorder()
  287. h.SSHSign(logging.NewResponseLogger(w), req)
  288. res := w.Result()
  289. if res.StatusCode != tt.statusCode {
  290. t.Errorf("caHandler.SignSSH StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  291. }
  292. body, err := ioutil.ReadAll(res.Body)
  293. res.Body.Close()
  294. if err != nil {
  295. t.Errorf("caHandler.SignSSH unexpected error = %v", err)
  296. }
  297. if tt.statusCode < http.StatusBadRequest {
  298. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  299. t.Errorf("caHandler.SignSSH Body = %s, wants %s", body, tt.body)
  300. }
  301. }
  302. })
  303. }
  304. }
  305. func Test_caHandler_SSHRoots(t *testing.T) {
  306. user, err := ssh.NewPublicKey(sshUserKey.Public())
  307. assert.FatalError(t, err)
  308. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  309. host, err := ssh.NewPublicKey(sshHostKey.Public())
  310. assert.FatalError(t, err)
  311. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  312. tests := []struct {
  313. name string
  314. keys *authority.SSHKeys
  315. keysErr error
  316. body []byte
  317. statusCode int
  318. }{
  319. {"ok", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host}, UserKeys: []ssh.PublicKey{user}}, nil, []byte(fmt.Sprintf(`{"userKey":["%s"],"hostKey":["%s"]}`, userB64, hostB64)), http.StatusOK},
  320. {"many", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host, host}, UserKeys: []ssh.PublicKey{user, user}}, nil, []byte(fmt.Sprintf(`{"userKey":["%s","%s"],"hostKey":["%s","%s"]}`, userB64, userB64, hostB64, hostB64)), http.StatusOK},
  321. {"user", &authority.SSHKeys{UserKeys: []ssh.PublicKey{user}}, nil, []byte(fmt.Sprintf(`{"userKey":["%s"]}`, userB64)), http.StatusOK},
  322. {"host", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host}}, nil, []byte(fmt.Sprintf(`{"hostKey":["%s"]}`, hostB64)), http.StatusOK},
  323. {"empty", &authority.SSHKeys{}, nil, nil, http.StatusNotFound},
  324. {"error", nil, fmt.Errorf("an error"), nil, http.StatusInternalServerError},
  325. }
  326. for _, tt := range tests {
  327. t.Run(tt.name, func(t *testing.T) {
  328. h := New(&mockAuthority{
  329. getSSHRoots: func() (*authority.SSHKeys, error) {
  330. return tt.keys, tt.keysErr
  331. },
  332. }).(*caHandler)
  333. req := httptest.NewRequest("GET", "http://example.com/ssh/roots", http.NoBody)
  334. w := httptest.NewRecorder()
  335. h.SSHRoots(logging.NewResponseLogger(w), req)
  336. res := w.Result()
  337. if res.StatusCode != tt.statusCode {
  338. t.Errorf("caHandler.SSHRoots StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  339. }
  340. body, err := ioutil.ReadAll(res.Body)
  341. res.Body.Close()
  342. if err != nil {
  343. t.Errorf("caHandler.SSHRoots unexpected error = %v", err)
  344. }
  345. if tt.statusCode < http.StatusBadRequest {
  346. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  347. t.Errorf("caHandler.SSHRoots Body = %s, wants %s", body, tt.body)
  348. }
  349. }
  350. })
  351. }
  352. }
  353. func Test_caHandler_SSHFederation(t *testing.T) {
  354. user, err := ssh.NewPublicKey(sshUserKey.Public())
  355. assert.FatalError(t, err)
  356. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  357. host, err := ssh.NewPublicKey(sshHostKey.Public())
  358. assert.FatalError(t, err)
  359. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  360. tests := []struct {
  361. name string
  362. keys *authority.SSHKeys
  363. keysErr error
  364. body []byte
  365. statusCode int
  366. }{
  367. {"ok", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host}, UserKeys: []ssh.PublicKey{user}}, nil, []byte(fmt.Sprintf(`{"userKey":["%s"],"hostKey":["%s"]}`, userB64, hostB64)), http.StatusOK},
  368. {"many", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host, host}, UserKeys: []ssh.PublicKey{user, user}}, nil, []byte(fmt.Sprintf(`{"userKey":["%s","%s"],"hostKey":["%s","%s"]}`, userB64, userB64, hostB64, hostB64)), http.StatusOK},
  369. {"user", &authority.SSHKeys{UserKeys: []ssh.PublicKey{user}}, nil, []byte(fmt.Sprintf(`{"userKey":["%s"]}`, userB64)), http.StatusOK},
  370. {"host", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host}}, nil, []byte(fmt.Sprintf(`{"hostKey":["%s"]}`, hostB64)), http.StatusOK},
  371. {"empty", &authority.SSHKeys{}, nil, nil, http.StatusNotFound},
  372. {"error", nil, fmt.Errorf("an error"), nil, http.StatusInternalServerError},
  373. }
  374. for _, tt := range tests {
  375. t.Run(tt.name, func(t *testing.T) {
  376. h := New(&mockAuthority{
  377. getSSHFederation: func() (*authority.SSHKeys, error) {
  378. return tt.keys, tt.keysErr
  379. },
  380. }).(*caHandler)
  381. req := httptest.NewRequest("GET", "http://example.com/ssh/federation", http.NoBody)
  382. w := httptest.NewRecorder()
  383. h.SSHFederation(logging.NewResponseLogger(w), req)
  384. res := w.Result()
  385. if res.StatusCode != tt.statusCode {
  386. t.Errorf("caHandler.SSHFederation StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  387. }
  388. body, err := ioutil.ReadAll(res.Body)
  389. res.Body.Close()
  390. if err != nil {
  391. t.Errorf("caHandler.SSHFederation unexpected error = %v", err)
  392. }
  393. if tt.statusCode < http.StatusBadRequest {
  394. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  395. t.Errorf("caHandler.SSHFederation Body = %s, wants %s", body, tt.body)
  396. }
  397. }
  398. })
  399. }
  400. }
  401. func Test_caHandler_SSHConfig(t *testing.T) {
  402. userOutput := []templates.Output{
  403. {Name: "config.tpl", Type: templates.File, Comment: "#", Path: "ssh/config", Content: []byte("UserKnownHostsFile /home/user/.step/ssh/known_hosts")},
  404. {Name: "known_host.tpl", Type: templates.File, Comment: "#", Path: "ssh/known_host", Content: []byte("@cert-authority * ecdsa-sha2-nistp256 AAAA...=")},
  405. }
  406. hostOutput := []templates.Output{
  407. {Name: "sshd_config.tpl", Type: templates.Snippet, Comment: "#", Path: "/etc/ssh/sshd_config", Content: []byte("TrustedUserCAKeys /etc/ssh/ca.pub")},
  408. {Name: "ca.tpl", Type: templates.File, Comment: "#", Path: "/etc/ssh/ca.pub", Content: []byte("ecdsa-sha2-nistp256 AAAA...=")},
  409. }
  410. userJSON, err := json.Marshal(userOutput)
  411. assert.FatalError(t, err)
  412. hostJSON, err := json.Marshal(hostOutput)
  413. assert.FatalError(t, err)
  414. tests := []struct {
  415. name string
  416. req string
  417. output []templates.Output
  418. err error
  419. body []byte
  420. statusCode int
  421. }{
  422. {"user", `{"type":"user"}`, userOutput, nil, []byte(fmt.Sprintf(`{"userTemplates":%s}`, userJSON)), http.StatusOK},
  423. {"host", `{"type":"host"}`, hostOutput, nil, []byte(fmt.Sprintf(`{"hostTemplates":%s}`, hostJSON)), http.StatusOK},
  424. {"noType", `{}`, userOutput, nil, []byte(fmt.Sprintf(`{"userTemplates":%s}`, userJSON)), http.StatusOK},
  425. {"badType", `{"type":"bad"}`, userOutput, nil, nil, http.StatusBadRequest},
  426. {"badData", `{"type":"user","data":{"bad"}}`, userOutput, nil, nil, http.StatusBadRequest},
  427. {"error", `{"type": "user"}`, nil, fmt.Errorf("an error"), nil, http.StatusInternalServerError},
  428. }
  429. for _, tt := range tests {
  430. t.Run(tt.name, func(t *testing.T) {
  431. h := New(&mockAuthority{
  432. getSSHConfig: func(typ string, data map[string]string) ([]templates.Output, error) {
  433. return tt.output, tt.err
  434. },
  435. }).(*caHandler)
  436. req := httptest.NewRequest("GET", "http://example.com/ssh/config", strings.NewReader(tt.req))
  437. w := httptest.NewRecorder()
  438. h.SSHConfig(logging.NewResponseLogger(w), req)
  439. res := w.Result()
  440. if res.StatusCode != tt.statusCode {
  441. t.Errorf("caHandler.SSHConfig StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  442. }
  443. body, err := ioutil.ReadAll(res.Body)
  444. res.Body.Close()
  445. if err != nil {
  446. t.Errorf("caHandler.SSHConfig unexpected error = %v", err)
  447. }
  448. if tt.statusCode < http.StatusBadRequest {
  449. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  450. t.Errorf("caHandler.SSHConfig Body = %s, wants %s", body, tt.body)
  451. }
  452. }
  453. })
  454. }
  455. }
  456. func Test_caHandler_SSHCheckHost(t *testing.T) {
  457. tests := []struct {
  458. name string
  459. req string
  460. exists bool
  461. err error
  462. body []byte
  463. statusCode int
  464. }{
  465. {"true", `{"type":"host","principal":"foo.example.com"}`, true, nil, []byte(`{"exists":true}`), http.StatusOK},
  466. {"false", `{"type":"host","principal":"bar.example.com"}`, false, nil, []byte(`{"exists":false}`), http.StatusOK},
  467. {"badType", `{"type":"user","principal":"bar.example.com"}`, false, nil, nil, http.StatusBadRequest},
  468. {"badPrincipal", `{"type":"host","principal":""}`, false, nil, nil, http.StatusBadRequest},
  469. {"badRequest", `{"foo"}`, false, nil, nil, http.StatusBadRequest},
  470. {"error", `{"type":"host","principal":"foo.example.com"}`, false, fmt.Errorf("an error"), nil, http.StatusInternalServerError},
  471. }
  472. for _, tt := range tests {
  473. t.Run(tt.name, func(t *testing.T) {
  474. h := New(&mockAuthority{
  475. checkSSHHost: func(_ string) (bool, error) {
  476. return tt.exists, tt.err
  477. },
  478. }).(*caHandler)
  479. req := httptest.NewRequest("GET", "http://example.com/ssh/check-host", strings.NewReader(tt.req))
  480. w := httptest.NewRecorder()
  481. h.SSHCheckHost(logging.NewResponseLogger(w), req)
  482. res := w.Result()
  483. if res.StatusCode != tt.statusCode {
  484. t.Errorf("caHandler.SSHCheckHost StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  485. }
  486. body, err := ioutil.ReadAll(res.Body)
  487. res.Body.Close()
  488. if err != nil {
  489. t.Errorf("caHandler.SSHCheckHost unexpected error = %v", err)
  490. }
  491. if tt.statusCode < http.StatusBadRequest {
  492. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  493. t.Errorf("caHandler.SSHCheckHost Body = %s, wants %s", body, tt.body)
  494. }
  495. }
  496. })
  497. }
  498. }
  499. func Test_caHandler_SSHBastion(t *testing.T) {
  500. bastion := &authority.Bastion{
  501. Hostname: "bastion.local",
  502. }
  503. bastionPort := &authority.Bastion{
  504. Hostname: "bastion.local",
  505. Port: "2222",
  506. }
  507. tests := []struct {
  508. name string
  509. bastion *authority.Bastion
  510. bastionErr error
  511. req []byte
  512. body []byte
  513. statusCode int
  514. }{
  515. {"ok", bastion, nil, []byte(`{"hostname":"host.local"}`), []byte(`{"hostname":"host.local","bastion":{"hostname":"bastion.local"}}`), http.StatusOK},
  516. {"ok", bastionPort, nil, []byte(`{"hostname":"host.local","user":"user"}`), []byte(`{"hostname":"host.local","bastion":{"hostname":"bastion.local","port":"2222"}}`), http.StatusOK},
  517. {"empty", nil, nil, []byte(`{"hostname":"host.local"}`), []byte(`{"hostname":"host.local"}`), http.StatusOK},
  518. {"bad json", bastion, nil, []byte(`bad json`), nil, http.StatusBadRequest},
  519. {"bad request", bastion, nil, []byte(`{"hostname": ""}`), nil, http.StatusBadRequest},
  520. {"error", nil, fmt.Errorf("an error"), []byte(`{"hostname":"host.local"}`), nil, http.StatusInternalServerError},
  521. }
  522. for _, tt := range tests {
  523. t.Run(tt.name, func(t *testing.T) {
  524. h := New(&mockAuthority{
  525. getSSHBastion: func(user, hostname string) (*authority.Bastion, error) {
  526. return tt.bastion, tt.bastionErr
  527. },
  528. }).(*caHandler)
  529. req := httptest.NewRequest("POST", "http://example.com/ssh/bastion", bytes.NewReader(tt.req))
  530. w := httptest.NewRecorder()
  531. h.SSHBastion(logging.NewResponseLogger(w), req)
  532. res := w.Result()
  533. if res.StatusCode != tt.statusCode {
  534. t.Errorf("caHandler.SSHBastion StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  535. }
  536. body, err := ioutil.ReadAll(res.Body)
  537. res.Body.Close()
  538. if err != nil {
  539. t.Errorf("caHandler.SSHBastion unexpected error = %v", err)
  540. }
  541. if tt.statusCode < http.StatusBadRequest {
  542. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  543. t.Errorf("caHandler.SSHBastion Body = %s, wants %s", body, tt.body)
  544. }
  545. }
  546. })
  547. }
  548. }
  549. func TestSSHPublicKey_MarshalJSON(t *testing.T) {
  550. key, err := ssh.NewPublicKey(sshUserKey.Public())
  551. assert.FatalError(t, err)
  552. keyB64 := base64.StdEncoding.EncodeToString(key.Marshal())
  553. tests := []struct {
  554. name string
  555. publicKey *SSHPublicKey
  556. want []byte
  557. wantErr bool
  558. }{
  559. {"ok", &SSHPublicKey{PublicKey: key}, []byte(`"` + keyB64 + `"`), false},
  560. {"null", nil, []byte("null"), false},
  561. {"null", &SSHPublicKey{PublicKey: nil}, []byte("null"), false},
  562. }
  563. for _, tt := range tests {
  564. t.Run(tt.name, func(t *testing.T) {
  565. got, err := tt.publicKey.MarshalJSON()
  566. if (err != nil) != tt.wantErr {
  567. t.Errorf("SSHPublicKey.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  568. return
  569. }
  570. if !reflect.DeepEqual(got, tt.want) {
  571. t.Errorf("SSHPublicKey.MarshalJSON() = %s, want %s", got, tt.want)
  572. }
  573. })
  574. }
  575. }
  576. func TestSSHPublicKey_UnmarshalJSON(t *testing.T) {
  577. key, err := ssh.NewPublicKey(sshUserKey.Public())
  578. assert.FatalError(t, err)
  579. keyB64 := base64.StdEncoding.EncodeToString(key.Marshal())
  580. type args struct {
  581. data []byte
  582. }
  583. tests := []struct {
  584. name string
  585. args args
  586. want *SSHPublicKey
  587. wantErr bool
  588. }{
  589. {"ok", args{[]byte(`"` + keyB64 + `"`)}, &SSHPublicKey{PublicKey: key}, false},
  590. {"empty", args{[]byte(`""`)}, &SSHPublicKey{}, false},
  591. {"null", args{[]byte(`null`)}, &SSHPublicKey{}, false},
  592. {"noString", args{[]byte("123")}, &SSHPublicKey{}, true},
  593. {"badB64", args{[]byte(`"bad"`)}, &SSHPublicKey{}, true},
  594. {"badKey", args{[]byte(`"Zm9vYmFyCg=="`)}, &SSHPublicKey{}, true},
  595. }
  596. for _, tt := range tests {
  597. t.Run(tt.name, func(t *testing.T) {
  598. p := &SSHPublicKey{}
  599. if err := p.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr {
  600. t.Errorf("SSHPublicKey.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  601. }
  602. if !reflect.DeepEqual(p, tt.want) {
  603. t.Errorf("SSHPublicKey.UnmarshalJSON() = %v, want %v", p, tt.want)
  604. }
  605. })
  606. }
  607. }