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 97e14fe
Show file tree
Hide file tree
Showing 2 changed files with 78 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
77 changes: 77 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,75 @@ 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
headers map[string]string
payload map[string]interface{}
expectedAud string
}{
{
desc: "Valid audience slice",
headers: map[string]string{
audHeaderName: "my_custom_aud",
},
payload: map[string]interface{}{
"aud": "authenticated",
},
expectedAud: "my_custom_aud",
},
{
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))
for k, v := range c.headers {
req.Header.Set(k, v)
}

// set the token in the request context for requestAud
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 97e14fe

Please sign in to comment.