Skip to content

Commit e3ebc31

Browse files
committed
AuthenticationMW fixed; rbac tests added;
1 parent 133b697 commit e3ebc31

File tree

3 files changed

+79
-4
lines changed

3 files changed

+79
-4
lines changed

internal/api/middleware.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,13 +129,13 @@ func AuthenticationMW(prov *auth.Provider, logger *zap.Logger, secretKey string)
129129

130130
if errUserID := setUserIDFromClaims(claims, c, logger); errUserID != nil {
131131
logger.Error("failed to set userID from claims", zap.Error(errUserID))
132-
c.Abort()
132+
apiErrors.RaiseNotAuthorizedErr(c, apiErrors.ErrAuthTokenInvalid)
133133
return
134134
}
135135

136136
if groupsErr := setGroupsFromClaims(claims, c, logger); groupsErr != nil {
137137
logger.Error("failed to set groups from claims", zap.Error(groupsErr))
138-
c.Abort()
138+
apiErrors.RaiseNotAuthorizedErr(c, apiErrors.ErrAuthTokenInvalid)
139139
return
140140
}
141141

@@ -174,6 +174,7 @@ func SetJWTClaims(
174174

175175
claims, ok := token.Claims.(jwt.MapClaims)
176176
if !ok {
177+
logger.Error("authentication failed: unable to extract claims from token")
177178
apiErrors.RaiseNotAuthorizedErr(c, apiErrors.ErrAuthTokenInvalid)
178179
return
179180
}

internal/api/middleware_test.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,16 @@ func TestAuthenticationMW_HMAC_SuccessAndFailures(t *testing.T) {
123123
w := performRequestWithAuth(mw, "Bearer "+signed)
124124
assert.Equal(t, http.StatusOK, w.Code, "expected middleware to allow valid HMAC token")
125125

126+
invalidGroupsTkn := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
127+
"preferred_username": "test-user",
128+
"groups": "sd_admins",
129+
})
130+
invalidSigned, err := invalidGroupsTkn.SignedString([]byte(secret))
131+
require.NoError(t, err, "failed to sign token with invalid groups claim")
132+
133+
w = performRequestWithAuth(mw, "Bearer "+invalidSigned)
134+
assert.Equal(t, http.StatusUnauthorized, w.Code, "expected 401 when groups claim has invalid type")
135+
126136
w = performRequestWithAuth(mw, "")
127137
assert.Equal(t, http.StatusUnauthorized, w.Code, "expected 401 when no Authorization header")
128138

@@ -136,8 +146,8 @@ func TestAuthenticationMW_RSA_ValidToken(t *testing.T) {
136146
require.NoError(t, err, "failed to generate rsa key")
137147

138148
claims := jwt.MapClaims{
139-
"sub": "rsa-user",
140-
"groups": []interface{}{"/sd-admins"},
149+
"preferred_username": "rsa-user",
150+
"groups": []interface{}{"/sd-admins"},
141151
}
142152
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
143153
signed, err := token.SignedString(priv)

tests/v2_events_rbac_test.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -714,3 +714,67 @@ func TestV2HasExtendedViewBehavior(t *testing.T) {
714714
assert.GreaterOrEqual(t, len(resp.Data), 1, "should see at least the planned event")
715715
})
716716
}
717+
718+
func TestV2InvalidTokenAndClaims(t *testing.T) {
719+
truncateIncidents(t)
720+
r := initTestsWithHMAC(t)
721+
722+
creatorToken := generateTestToken("user-a", []string{"sd_creators"})
723+
724+
components := []int{1, 2}
725+
impact := 0
726+
system := false
727+
startDate := time.Now().Add(time.Hour).UTC()
728+
endDate := time.Now().Add(2 * time.Hour).UTC()
729+
730+
incData := v2.IncidentData{
731+
Title: "Test event", Description: "test",
732+
ContactEmail: "test@example.com", Impact: &impact,
733+
Components: components, StartDate: startDate,
734+
EndDate: &endDate, System: &system, Type: event.TypeMaintenance,
735+
}
736+
737+
t.Run("invalid token signature returns 401", func(t *testing.T) {
738+
wrongSecretToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
739+
"preferred_username": "user-a",
740+
"groups": []interface{}{"sd_creators"},
741+
})
742+
invalidToken, err := wrongSecretToken.SignedString([]byte("wrong-secret"))
743+
require.NoError(t, err)
744+
745+
data, _ := json.Marshal(incData)
746+
w := httptest.NewRecorder()
747+
req, _ := http.NewRequest(http.MethodPost, "/v2/events", bytes.NewReader(data))
748+
req.Header.Set("Authorization", "Bearer "+invalidToken)
749+
r.ServeHTTP(w, req)
750+
751+
assert.Equal(t, http.StatusUnauthorized, w.Code)
752+
})
753+
754+
t.Run("valid token with invalid groups claim returns 401", func(t *testing.T) {
755+
invalidClaimsToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
756+
"preferred_username": "user-a",
757+
"groups": "sd_creators",
758+
})
759+
tokenWithInvalidClaims, err := invalidClaimsToken.SignedString([]byte(testHMACSecret))
760+
require.NoError(t, err)
761+
762+
data, _ := json.Marshal(incData)
763+
w := httptest.NewRecorder()
764+
req, _ := http.NewRequest(http.MethodPost, "/v2/events", bytes.NewReader(data))
765+
req.Header.Set("Authorization", "Bearer "+tokenWithInvalidClaims)
766+
r.ServeHTTP(w, req)
767+
768+
assert.Equal(t, http.StatusUnauthorized, w.Code)
769+
})
770+
771+
t.Run("valid token with valid claims succeeds", func(t *testing.T) {
772+
data, _ := json.Marshal(incData)
773+
w := httptest.NewRecorder()
774+
req, _ := http.NewRequest(http.MethodPost, "/v2/events", bytes.NewReader(data))
775+
req.Header.Set("Authorization", "Bearer "+creatorToken)
776+
r.ServeHTTP(w, req)
777+
778+
assert.Equal(t, http.StatusOK, w.Code)
779+
})
780+
}

0 commit comments

Comments
 (0)