oidc_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 handler
  15. import (
  16. "reflect"
  17. "testing"
  18. "time"
  19. "yunion.io/x/pkg/util/netutils"
  20. "yunion.io/x/onecloud/pkg/apigateway/clientman"
  21. )
  22. func TestClientInfo(t *testing.T) {
  23. clientman.SetupTest()
  24. cases := []struct {
  25. ip string
  26. user string
  27. project string
  28. }{
  29. {
  30. ip: "0.0.0.0",
  31. user: "sysadmin",
  32. project: "system",
  33. },
  34. {
  35. ip: "10.168.26.253",
  36. user: "ab9502de-c6b6-4150-880b-d0e3e6ba8ec8",
  37. project: "a2049cfadf4c40888b9da136faba5cc8",
  38. },
  39. }
  40. for _, c := range cases {
  41. info := SOIDCClientInfo{}
  42. info.Timestamp = time.Now().UnixNano()
  43. info.Ip, _ = netutils.NewIPV4Addr(c.ip)
  44. info.UserId = c.user
  45. info.ProjectId = c.project
  46. msg := info.toBytes()
  47. if len(msg) != 14+len(info.UserId)+len(info.ProjectId)+len(info.Region) {
  48. t.Fatalf("incorrect msg size")
  49. }
  50. info2, err := decodeOIDCClientInfo(msg)
  51. if err != nil {
  52. t.Fatalf("decode error %s", err)
  53. }
  54. if info2.Timestamp != info.Timestamp {
  55. t.Fatalf("incorrect timestamp")
  56. }
  57. if info2.Ip.String() != info.Ip.String() {
  58. t.Fatalf("incorrect ip")
  59. }
  60. if info2.UserId != info.UserId {
  61. t.Fatalf("incorrect user id")
  62. }
  63. if info2.ProjectId != info.ProjectId {
  64. t.Fatalf("incorrect project id")
  65. }
  66. if info2.Region != info.Region {
  67. t.Fatalf("incorrect region id")
  68. }
  69. token := SOIDCClientToken{
  70. Info: info,
  71. }
  72. tokenStr := token.encode()
  73. token2, err := decodeOIDCClientToken(tokenStr)
  74. if err != nil {
  75. t.Fatalf("decodeOIDCClientToken fail %s", err)
  76. }
  77. if !reflect.DeepEqual(token2.Info, info2) {
  78. t.Fatalf("token2 info not equal to info2")
  79. }
  80. }
  81. }