creds_utils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package nkeys
  2. import (
  3. "bytes"
  4. "errors"
  5. "regexp"
  6. )
  7. var userConfigRE = regexp.MustCompile(`\s*(?:(?:[-]{3,}.*[-]{3,}\r?\n)([\w\-.=]+)(?:\r?\n[-]{3,}.*[-]{3,}\r?\n))`)
  8. // ParseDecoratedJWT takes a creds file and returns the JWT portion.
  9. func ParseDecoratedJWT(contents []byte) (string, error) {
  10. items := userConfigRE.FindAllSubmatch(contents, -1)
  11. if len(items) == 0 {
  12. return string(contents), nil
  13. }
  14. // First result should be the user JWT.
  15. // We copy here so that if the file contained a seed file too we wipe appropriately.
  16. raw := items[0][1]
  17. tmp := make([]byte, len(raw))
  18. copy(tmp, raw)
  19. return string(tmp), nil
  20. }
  21. // ParseDecoratedNKey takes a creds file, finds the NKey portion and creates a
  22. // key pair from it.
  23. func ParseDecoratedNKey(contents []byte) (KeyPair, error) {
  24. var seed []byte
  25. items := userConfigRE.FindAllSubmatch(contents, -1)
  26. if len(items) > 1 {
  27. seed = items[1][1]
  28. } else {
  29. lines := bytes.Split(contents, []byte("\n"))
  30. for _, line := range lines {
  31. if bytes.HasPrefix(bytes.TrimSpace(line), []byte("SO")) ||
  32. bytes.HasPrefix(bytes.TrimSpace(line), []byte("SA")) ||
  33. bytes.HasPrefix(bytes.TrimSpace(line), []byte("SU")) {
  34. seed = line
  35. break
  36. }
  37. }
  38. }
  39. if seed == nil {
  40. return nil, errors.New("no nkey seed found")
  41. }
  42. if !bytes.HasPrefix(seed, []byte("SO")) &&
  43. !bytes.HasPrefix(seed, []byte("SA")) &&
  44. !bytes.HasPrefix(seed, []byte("SU")) {
  45. return nil, errors.New("doesn't contain a seed nkey")
  46. }
  47. kp, err := FromSeed(seed)
  48. if err != nil {
  49. return nil, err
  50. }
  51. return kp, nil
  52. }
  53. // ParseDecoratedUserNKey takes a creds file, finds the NKey portion and creates a
  54. // key pair from it. Similar to ParseDecoratedNKey but fails for non-user keys.
  55. func ParseDecoratedUserNKey(contents []byte) (KeyPair, error) {
  56. nk, err := ParseDecoratedNKey(contents)
  57. if err != nil {
  58. return nil, err
  59. }
  60. seed, err := nk.Seed()
  61. if err != nil {
  62. return nil, err
  63. }
  64. if !bytes.HasPrefix(seed, []byte("SU")) {
  65. return nil, errors.New("doesn't contain an user seed nkey")
  66. }
  67. kp, err := FromSeed(seed)
  68. if err != nil {
  69. return nil, err
  70. }
  71. return kp, nil
  72. }