restapi_auth_jwt_test.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. package httpservers
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/pem"
  7. "fmt"
  8. // config "github.com/OliveTin/OliveTin/internal/config"
  9. // "github.com/golang-jwt/jwt/v4"
  10. // "github.com/stretchr/testify/assert"
  11. "net/http"
  12. "os"
  13. "testing"
  14. // "time"
  15. )
  16. func createKeys(t *testing.T) (*rsa.PrivateKey, string) {
  17. tmpFile, _ := os.CreateTemp(os.TempDir(), "olivetin-jwt-")
  18. fmt.Println("Created File: " + tmpFile.Name())
  19. privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
  20. pubKey := &privateKey.PublicKey
  21. // https://stackoverflow.com/questions/13555085/save-and-load-crypto-rsa-privatekey-to-and-from-the-disk
  22. pkixPubKey, _ := x509.MarshalPKIXPublicKey(pubKey)
  23. pubPem := pem.EncodeToMemory(
  24. &pem.Block{
  25. Type: "RSA PUBLIC KEY",
  26. Bytes: pkixPubKey,
  27. },
  28. )
  29. if err := os.WriteFile(tmpFile.Name(), pubPem, 0755); err != nil {
  30. t.Fatalf("error when dumping pubKey: %s \n", err)
  31. }
  32. return privateKey, tmpFile.Name()
  33. }
  34. func newMux() *http.ServeMux {
  35. mux := http.NewServeMux()
  36. return mux
  37. }
  38. func testJwkValidation(t *testing.T, expire int64, expectCode int) {
  39. /*
  40. privateKey, publicKeyPath := createKeys(t)
  41. defer os.Remove(publicKeyPath)
  42. cfg := config.DefaultConfig()
  43. cfg.AuthJwtPubKeyPath = publicKeyPath
  44. cfg.AuthJwtClaimUsername = "sub"
  45. cfg.AuthJwtClaimUserGroup = "olivetinGroup"
  46. cfg.AuthJwtCookieName = "authorization_token"
  47. token := jwt.New(jwt.SigningMethodRS256)
  48. claims := token.Claims.(jwt.MapClaims)
  49. claims["nbf"] = time.Now().Unix() - 1000
  50. claims["exp"] = time.Now().Unix() + expire
  51. claims["sub"] = "test"
  52. claims["olivetinGroup"] = "test"
  53. */
  54. /*
  55. tokenStr, _ := token.SignedString(privateKey)
  56. mux := newMux()
  57. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
  58. username, usergroup := parseJwtCookie(cfg, r)
  59. if username == "" {
  60. w.WriteHeader(403)
  61. }
  62. w.Write([]byte(fmt.Sprintf("username=%v, usergroup=%v", username, usergroup)))
  63. })
  64. srv := setupTestingServer(mux, t)
  65. req, client := newReq("")
  66. req.AddCookie(&http.Cookie{
  67. Name: "authorization_token",
  68. Value: tokenStr,
  69. MaxAge: 300,
  70. })
  71. res, err := client.Do(req)
  72. if err != nil {
  73. t.Fatalf("Client err: %+v", err)
  74. } else {
  75. defer res.Body.Close()
  76. assert.Equal(t, expectCode, res.StatusCode)
  77. body, _ := io.ReadAll(res.Body)
  78. fmt.Println(string(body))
  79. }
  80. err = srv.Shutdown(context.TODO())
  81. if err != nil {
  82. t.Fatalf("Server shutdown error: %+v", err)
  83. }
  84. */
  85. }
  86. func TestJWTSignatureVerificationSucceeds(t *testing.T) {
  87. testJwkValidation(t, 1000, 200)
  88. }
  89. func TestJWTSignatureVerificationFails(t *testing.T) {
  90. testJwkValidation(t, -500, 403)
  91. }
  92. func TestJWTHeader(t *testing.T) {
  93. /*
  94. privateKey, publicKeyPath := createKeys(t)
  95. defer os.Remove(publicKeyPath)
  96. cfg := config.DefaultConfig()
  97. cfg.AuthJwtPubKeyPath = publicKeyPath
  98. cfg.AuthJwtClaimUsername = "sub"
  99. cfg.AuthJwtClaimUserGroup = "olivetinGroup"
  100. cfg.AuthJwtHeader = "Authorization"
  101. token := jwt.New(jwt.SigningMethodRS256)
  102. claims := token.Claims.(jwt.MapClaims)
  103. claims["nbf"] = time.Now().Unix() - 1000
  104. claims["exp"] = time.Now().Unix() + 2000
  105. claims["sub"] = "test"
  106. claims["olivetinGroup"] = []string{"test", "test2"}
  107. */
  108. /*
  109. tokenStr, _ := token.SignedString(privateKey)
  110. mux := newMux()
  111. mux.HandlePath("GET", "/", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
  112. username, usergroup := parseJwtHeader(cfg, r)
  113. if username == "" {
  114. w.WriteHeader(403)
  115. }
  116. assert.Equal(t, "test", username)
  117. assert.Equal(t, "test test2", usergroup)
  118. w.Write([]byte(fmt.Sprintf("username=%v, usergroup=%v", username, usergroup)))
  119. })
  120. srv := setupTestingServer(mux, t)
  121. req, client := newReq("")
  122. req.Header.Set("Authorization", "Bearer "+tokenStr)
  123. res, err := client.Do(req)
  124. if err != nil {
  125. t.Fatalf("Client err: %+v", err)
  126. } else {
  127. defer res.Body.Close()
  128. assert.Equal(t, 200, res.StatusCode)
  129. body, _ := io.ReadAll(res.Body)
  130. fmt.Println(string(body))
  131. }
  132. srv.Shutdown(context.TODO())
  133. */
  134. }