restapi_auth_jwt_test.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. privateKey, publicKeyPath := createKeys(t)
  40. defer os.Remove(publicKeyPath)
  41. cfg := config.DefaultConfig()
  42. cfg.AuthJwtPubKeyPath = publicKeyPath
  43. cfg.AuthJwtClaimUsername = "sub"
  44. cfg.AuthJwtClaimUserGroup = "olivetinGroup"
  45. cfg.AuthJwtCookieName = "authorization_token"
  46. token := jwt.New(jwt.SigningMethodRS256)
  47. claims := token.Claims.(jwt.MapClaims)
  48. claims["nbf"] = time.Now().Unix() - 1000
  49. claims["exp"] = time.Now().Unix() + expire
  50. claims["sub"] = "test"
  51. claims["olivetinGroup"] = "test"
  52. /*
  53. tokenStr, _ := token.SignedString(privateKey)
  54. mux := newMux()
  55. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
  56. username, usergroup := parseJwtCookie(cfg, r)
  57. if username == "" {
  58. w.WriteHeader(403)
  59. }
  60. w.Write([]byte(fmt.Sprintf("username=%v, usergroup=%v", username, usergroup)))
  61. })
  62. srv := setupTestingServer(mux, t)
  63. req, client := newReq("")
  64. req.AddCookie(&http.Cookie{
  65. Name: "authorization_token",
  66. Value: tokenStr,
  67. MaxAge: 300,
  68. })
  69. res, err := client.Do(req)
  70. if err != nil {
  71. t.Fatalf("Client err: %+v", err)
  72. } else {
  73. defer res.Body.Close()
  74. assert.Equal(t, expectCode, res.StatusCode)
  75. body, _ := io.ReadAll(res.Body)
  76. fmt.Println(string(body))
  77. }
  78. err = srv.Shutdown(context.TODO())
  79. if err != nil {
  80. t.Fatalf("Server shutdown error: %+v", err)
  81. }
  82. */
  83. }
  84. func TestJWTSignatureVerificationSucceeds(t *testing.T) {
  85. testJwkValidation(t, 1000, 200)
  86. }
  87. func TestJWTSignatureVerificationFails(t *testing.T) {
  88. testJwkValidation(t, -500, 403)
  89. }
  90. func TestJWTHeader(t *testing.T) {
  91. privateKey, publicKeyPath := createKeys(t)
  92. defer os.Remove(publicKeyPath)
  93. cfg := config.DefaultConfig()
  94. cfg.AuthJwtPubKeyPath = publicKeyPath
  95. cfg.AuthJwtClaimUsername = "sub"
  96. cfg.AuthJwtClaimUserGroup = "olivetinGroup"
  97. cfg.AuthJwtHeader = "Authorization"
  98. token := jwt.New(jwt.SigningMethodRS256)
  99. claims := token.Claims.(jwt.MapClaims)
  100. claims["nbf"] = time.Now().Unix() - 1000
  101. claims["exp"] = time.Now().Unix() + 2000
  102. claims["sub"] = "test"
  103. claims["olivetinGroup"] = []string{"test", "test2"}
  104. /*
  105. tokenStr, _ := token.SignedString(privateKey)
  106. mux := newMux()
  107. mux.HandlePath("GET", "/", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
  108. username, usergroup := parseJwtHeader(cfg, r)
  109. if username == "" {
  110. w.WriteHeader(403)
  111. }
  112. assert.Equal(t, "test", username)
  113. assert.Equal(t, "test test2", usergroup)
  114. w.Write([]byte(fmt.Sprintf("username=%v, usergroup=%v", username, usergroup)))
  115. })
  116. srv := setupTestingServer(mux, t)
  117. req, client := newReq("")
  118. req.Header.Set("Authorization", "Bearer "+tokenStr)
  119. res, err := client.Do(req)
  120. if err != nil {
  121. t.Fatalf("Client err: %+v", err)
  122. } else {
  123. defer res.Body.Close()
  124. assert.Equal(t, 200, res.StatusCode)
  125. body, _ := io.ReadAll(res.Body)
  126. fmt.Println(string(body))
  127. }
  128. srv.Shutdown(context.TODO())
  129. */
  130. }