validators_sshkey.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package validators
  15. import (
  16. "context"
  17. "golang.org/x/crypto/ssh"
  18. "yunion.io/x/jsonutils"
  19. )
  20. type ValidatorSSHKey struct {
  21. Validator
  22. Value string
  23. Signer ssh.Signer
  24. }
  25. func NewSSHKeyValidator(key string) *ValidatorSSHKey {
  26. v := &ValidatorSSHKey{
  27. Validator: Validator{Key: key},
  28. }
  29. v.SetParent(v)
  30. return v
  31. }
  32. func (v *ValidatorSSHKey) parseKey(s string) (ssh.Signer, error) {
  33. signer, err := ssh.ParsePrivateKey([]byte(s))
  34. if err != nil {
  35. return nil, err
  36. }
  37. return signer, nil
  38. }
  39. func (v *ValidatorSSHKey) Default(s string) IValidator {
  40. _, err := v.parseKey(s)
  41. if err != nil {
  42. panic(err)
  43. }
  44. v.Validator.Default(s)
  45. return v
  46. }
  47. func (v *ValidatorSSHKey) getValue() interface{} {
  48. return v.Value
  49. }
  50. func (v *ValidatorSSHKey) Validate(ctx context.Context, data *jsonutils.JSONDict) error {
  51. if err, isSet := v.Validator.validateEx(data); err != nil || !isSet {
  52. return err
  53. }
  54. s, err := v.value.GetString()
  55. if err != nil {
  56. return newGeneralError(v.Key, err)
  57. }
  58. if signer, err := v.parseKey(s); err != nil {
  59. return newInvalidValueError(v.Key, s)
  60. } else {
  61. v.Signer = signer
  62. }
  63. data.Set(v.Key, jsonutils.NewString(s))
  64. v.Value = s
  65. return nil
  66. }