You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

auth_test.go 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package actions
  4. import (
  5. "net/http"
  6. "testing"
  7. "code.gitea.io/gitea/modules/json"
  8. "code.gitea.io/gitea/modules/setting"
  9. "github.com/golang-jwt/jwt/v5"
  10. "github.com/stretchr/testify/assert"
  11. )
  12. func TestCreateAuthorizationToken(t *testing.T) {
  13. var taskID int64 = 23
  14. token, err := CreateAuthorizationToken(taskID, 1, 2)
  15. assert.Nil(t, err)
  16. assert.NotEqual(t, "", token)
  17. claims := jwt.MapClaims{}
  18. _, err = jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (any, error) {
  19. return setting.GetGeneralTokenSigningSecret(), nil
  20. })
  21. assert.Nil(t, err)
  22. scp, ok := claims["scp"]
  23. assert.True(t, ok, "Has scp claim in jwt token")
  24. assert.Contains(t, scp, "Actions.Results:1:2")
  25. taskIDClaim, ok := claims["TaskID"]
  26. assert.True(t, ok, "Has TaskID claim in jwt token")
  27. assert.Equal(t, float64(taskID), taskIDClaim, "Supplied taskid must match stored one")
  28. acClaim, ok := claims["ac"]
  29. assert.True(t, ok, "Has ac claim in jwt token")
  30. ac, ok := acClaim.(string)
  31. assert.True(t, ok, "ac claim is a string for buildx gha cache")
  32. scopes := []actionsCacheScope{}
  33. err = json.Unmarshal([]byte(ac), &scopes)
  34. assert.NoError(t, err, "ac claim is a json list for buildx gha cache")
  35. assert.GreaterOrEqual(t, len(scopes), 1, "Expected at least one action cache scope for buildx gha cache")
  36. }
  37. func TestParseAuthorizationToken(t *testing.T) {
  38. var taskID int64 = 23
  39. token, err := CreateAuthorizationToken(taskID, 1, 2)
  40. assert.Nil(t, err)
  41. assert.NotEqual(t, "", token)
  42. headers := http.Header{}
  43. headers.Set("Authorization", "Bearer "+token)
  44. rTaskID, err := ParseAuthorizationToken(&http.Request{
  45. Header: headers,
  46. })
  47. assert.Nil(t, err)
  48. assert.Equal(t, taskID, rTaskID)
  49. }
  50. func TestParseAuthorizationTokenNoAuthHeader(t *testing.T) {
  51. headers := http.Header{}
  52. rTaskID, err := ParseAuthorizationToken(&http.Request{
  53. Header: headers,
  54. })
  55. assert.Nil(t, err)
  56. assert.Equal(t, int64(0), rTaskID)
  57. }