Skip to content

Commit

Permalink
fix: check for empty aud string
Browse files Browse the repository at this point in the history
  • Loading branch information
kangmingtay committed Jul 4, 2024
1 parent 3c8d765 commit 7c2f1b4
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/api/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (a *API) requestAud(ctx context.Context, r *http.Request) string {

if claims != nil {
aud, _ := claims.GetAudience()
if len(aud) != 0 {
if len(aud) != 0 && aud[0] != "" {
return aud[0]
}
}
Expand Down
69 changes: 69 additions & 0 deletions internal/api/helpers_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package api

import (
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"testing"

"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/require"
"github.com/supabase/auth/internal/conf"
)

func TestIsValidCodeChallenge(t *testing.T) {
Expand Down Expand Up @@ -72,3 +77,67 @@ func TestIsValidPKCEParams(t *testing.T) {
})
}
}

func TestRequestAud(ts *testing.T) {
mockAPI := API{
config: &conf.GlobalConfiguration{
JWT: conf.JWTConfiguration{
Aud: "authenticated",
Secret: "test-secret",
},
},
}

cases := []struct {
desc string
payload map[string]interface{}
expectedAud string
}{
{
desc: "Valid audience slice",
payload: map[string]interface{}{
"aud": []string{"aud_1", "aud_2"},
},
expectedAud: "aud_1",
},
{
desc: "Valid custom audience",
payload: map[string]interface{}{
"aud": "my_custom_aud",
},
expectedAud: "my_custom_aud",
},
{
desc: "Invalid audience",
payload: map[string]interface{}{
"aud": "",
},
expectedAud: mockAPI.config.JWT.Aud,
},
{
desc: "Missing audience",
payload: map[string]interface{}{
"sub": "d6044b6e-b0ec-4efe-a055-0d2d6ff1dbd8",
},
expectedAud: mockAPI.config.JWT.Aud,
},
}

for _, c := range cases {
ts.Run(c.desc, func(t *testing.T) {
claims := jwt.MapClaims(c.payload)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString([]byte(mockAPI.config.JWT.Secret))
require.NoError(t, err)

req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("Authorization", fmt.Sprintf("Bearer: %s", signed))

ctx, err := mockAPI.parseJWTClaims(signed, req)
require.NoError(t, err)
aud := mockAPI.requestAud(ctx, req)
require.Equal(t, c.expectedAud, aud)
})
}

}

0 comments on commit 7c2f1b4

Please sign in to comment.