Skip to content

Commit ed17ed9

Browse files
AmanGIT07claude
andauthored
feat(auth): enforce per-endpoint credential restrictions and make the auth chain order-independent (#1718)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 655d4df commit ed17ed9

10 files changed

Lines changed: 303 additions & 52 deletions

File tree

‎core/authenticate/authenticate.go‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,6 @@ const (
3535
// AccessTokenClientAssertion is used to authenticate using access token generated
3636
// by the system for the user
3737
AccessTokenClientAssertion ClientAssertion = "access_token"
38-
// OpaqueTokenClientAssertion is used to authenticate using opaque token generated
39-
// for API clients
40-
OpaqueTokenClientAssertion ClientAssertion = "opaque"
4138
// JWTGrantClientAssertion is used to authenticate using JWT token generated
4239
// using public/private key pair that provides access token for the client
4340
JWTGrantClientAssertion ClientAssertion = "jwt_grant"
@@ -60,7 +57,6 @@ var APIAssertions = []ClientAssertion{
6057
PATClientAssertion,
6158
AccessTokenClientAssertion,
6259
JWTGrantClientAssertion,
63-
OpaqueTokenClientAssertion,
6460
// ClientCredentialsClientAssertion should be removed in future to avoid DDOS attacks on CPU
6561
// and should only be allowed to be used get access token for the client
6662
ClientCredentialsClientAssertion,
@@ -138,6 +134,8 @@ type Principal struct {
138134
// Type is the namespace of principal
139135
// E.g. app/user, app/serviceuser, app/pat
140136
Type string
137+
// AuthVia is the credential type that authenticated this principal
138+
AuthVia ClientAssertion
141139

142140
User *user.User
143141
ServiceUser *serviceuser.ServiceUser

‎core/authenticate/authenticators.go‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"github.com/lestrrat-go/jwx/v2/jwt"
99
frontiersession "github.com/raystack/frontier/core/authenticate/session"
1010
"github.com/raystack/frontier/core/authenticate/token"
11+
"github.com/raystack/frontier/core/serviceuser"
1112
patErrors "github.com/raystack/frontier/core/userpat/errors"
1213
"github.com/raystack/frontier/internal/bootstrap/schema"
1314
"github.com/raystack/frontier/pkg/errors"
@@ -26,7 +27,6 @@ var authenticators = map[ClientAssertion]AuthenticatorFunc{
2627
AccessTokenClientAssertion: authenticateWithAccessToken,
2728
JWTGrantClientAssertion: authenticateWithJWTGrant,
2829
ClientCredentialsClientAssertion: authenticateWithClientCredentials,
29-
OpaqueTokenClientAssertion: authenticateWithClientCredentials,
3030
PassthroughHeaderClientAssertion: authenticateWithPassthroughHeader,
3131
}
3232

@@ -189,8 +189,17 @@ func authenticateWithJWTGrant(ctx context.Context, s *Service) (Principal, error
189189
ServiceUser: &serviceUser,
190190
}, nil
191191
}
192-
s.log.DebugContext(ctx, "failed to parse as user token ", "err", err)
193-
return Principal{}, errors.ErrUnauthenticated
192+
switch {
193+
case errors.Is(err, serviceuser.ErrTokenNotJWT),
194+
errors.Is(err, serviceuser.ErrInvalidKeyID),
195+
errors.Is(err, serviceuser.ErrCredNotExist):
196+
return Principal{}, errSkip
197+
case errors.Is(err, serviceuser.ErrInvalidCred):
198+
s.log.DebugContext(ctx, "service user grant failed verification", "err", err)
199+
return Principal{}, errors.ErrUnauthenticated
200+
default:
201+
return Principal{}, err
202+
}
194203
}
195204

196205
// authenticateWithClientCredentials validates client_id:client_secret credentials.

‎core/authenticate/service.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,9 @@ func (s Service) GetPrincipal(ctx context.Context, assertions ...ClientAssertion
757757
}
758758

759759
if val, ok := GetPrincipalFromContext(ctx); ok {
760+
if len(assertions) > 0 && !slices.Contains(assertions, val.AuthVia) {
761+
return Principal{}, errors.ErrUnauthenticated
762+
}
760763
return *val, nil
761764
}
762765

@@ -772,6 +775,7 @@ func (s Service) GetPrincipal(ctx context.Context, assertions ...ClientAssertion
772775
}
773776
principal, err := authenticator(ctx, &s)
774777
if err == nil {
778+
principal.AuthVia = assertion
775779
return principal, nil
776780
}
777781
if !errors.Is(err, errSkip) {

‎core/authenticate/service_test.go‎

Lines changed: 88 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import (
2424
"github.com/raystack/frontier/core/authenticate/token"
2525
"github.com/raystack/frontier/core/serviceuser"
2626
"github.com/raystack/frontier/core/user"
27+
patModels "github.com/raystack/frontier/core/userpat/models"
2728
"github.com/raystack/frontier/internal/bootstrap/schema"
2829
mailerMock "github.com/raystack/frontier/pkg/mailer/mocks"
2930
pkgMetadata "github.com/raystack/frontier/pkg/metadata"
@@ -88,8 +89,9 @@ func TestService_GetPrincipal(t *testing.T) {
8889
assertions: []authenticate.ClientAssertion{authenticate.SessionClientAssertion},
8990
},
9091
want: authenticate.Principal{
91-
ID: userID.String(),
92-
Type: schema.UserPrincipal,
92+
ID: userID.String(),
93+
Type: schema.UserPrincipal,
94+
AuthVia: authenticate.SessionClientAssertion,
9395
User: &user.User{
9496
ID: userID.String(),
9597
},
@@ -149,8 +151,9 @@ func TestService_GetPrincipal(t *testing.T) {
149151
assertions: []authenticate.ClientAssertion{authenticate.AccessTokenClientAssertion},
150152
},
151153
want: authenticate.Principal{
152-
ID: userID.String(),
153-
Type: schema.UserPrincipal,
154+
ID: userID.String(),
155+
Type: schema.UserPrincipal,
156+
AuthVia: authenticate.AccessTokenClientAssertion,
154157
User: &user.User{
155158
ID: userID.String(),
156159
},
@@ -195,8 +198,9 @@ func TestService_GetPrincipal(t *testing.T) {
195198
assertions: []authenticate.ClientAssertion{authenticate.JWTGrantClientAssertion},
196199
},
197200
want: authenticate.Principal{
198-
ID: userID.String(),
199-
Type: schema.ServiceUserPrincipal,
201+
ID: userID.String(),
202+
Type: schema.ServiceUserPrincipal,
203+
AuthVia: authenticate.JWTGrantClientAssertion,
200204
ServiceUser: &serviceuser.ServiceUser{
201205
ID: userID.String(),
202206
},
@@ -240,35 +244,9 @@ func TestService_GetPrincipal(t *testing.T) {
240244
assertions: []authenticate.ClientAssertion{authenticate.ClientCredentialsClientAssertion},
241245
},
242246
want: authenticate.Principal{
243-
ID: userID.String(),
244-
Type: schema.ServiceUserPrincipal,
245-
ServiceUser: &serviceuser.ServiceUser{
246-
ID: userID.String(),
247-
},
248-
},
249-
wantErr: false,
250-
setup: func() *authenticate.Service {
251-
mockFlow, mockUserService, mockTokenService, mockSessionService, mockServiceUserService := createMocks(t)
252-
253-
mockServiceUserService.EXPECT().GetBySecret(mock.Anything, "user", "password").Return(serviceuser.ServiceUser{
254-
ID: userID.String(),
255-
}, nil)
256-
257-
return authenticate.NewService(nil, authenticate.Config{},
258-
mockFlow, nil, mockTokenService, mockSessionService, mockUserService, mockServiceUserService, nil, nil)
259-
},
260-
},
261-
{
262-
name: "fetch principal from opaque token",
263-
args: args{
264-
ctx: metadata.NewIncomingContext(context.Background(), map[string][]string{
265-
consts.UserSecretGatewayKey: {userToken},
266-
}),
267-
assertions: []authenticate.ClientAssertion{authenticate.OpaqueTokenClientAssertion},
268-
},
269-
want: authenticate.Principal{
270-
ID: userID.String(),
271-
Type: schema.ServiceUserPrincipal,
247+
ID: userID.String(),
248+
Type: schema.ServiceUserPrincipal,
249+
AuthVia: authenticate.ClientCredentialsClientAssertion,
272250
ServiceUser: &serviceuser.ServiceUser{
273251
ID: userID.String(),
274252
},
@@ -457,3 +435,78 @@ func TestService_StartFlow(t *testing.T) {
457435
})
458436
}
459437
}
438+
439+
func TestService_GetPrincipal_JWTGrantSkipsNonGrantToken(t *testing.T) {
440+
userID := uuid.New()
441+
patValue := "fpt_opaque-not-a-jwt"
442+
443+
mockFlow, mockUserService, mockTokenService, mockSessionService, mockServiceUserService := createMocks(t)
444+
mockPATService := mocks.NewUserPATService(t)
445+
446+
mockServiceUserService.EXPECT().GetByJWT(mock.Anything, patValue).
447+
Return(serviceuser.ServiceUser{}, serviceuser.ErrTokenNotJWT)
448+
pat := patModels.PAT{ID: "pat-1", UserID: userID.String(), ExpiresAt: time.Now().Add(time.Hour)}
449+
mockPATService.EXPECT().Validate(mock.Anything, patValue).Return(pat, nil)
450+
mockUserService.EXPECT().GetByID(mock.Anything, userID.String()).
451+
Return(user.User{ID: userID.String()}, nil)
452+
453+
svc := authenticate.NewService(slog.New(slog.NewTextHandler(io.Discard, nil)), authenticate.Config{},
454+
mockFlow, nil, mockTokenService, mockSessionService, mockUserService, mockServiceUserService, nil, mockPATService)
455+
456+
ctx := metadata.NewIncomingContext(context.Background(), map[string][]string{
457+
consts.UserTokenGatewayKey: {patValue},
458+
})
459+
460+
got, err := svc.GetPrincipal(ctx,
461+
authenticate.JWTGrantClientAssertion, authenticate.PATClientAssertion)
462+
require.NoError(t, err)
463+
assert.Equal(t, schema.PATPrincipal, got.Type)
464+
require.NotNil(t, got.PAT)
465+
assert.Equal(t, "pat-1", got.ID)
466+
}
467+
468+
func TestService_GetPrincipal_RestrictsByAuthVia(t *testing.T) {
469+
// lists mirror what the handlers pass: session.go uses {Session}; AuthToken uses the token-exchange set.
470+
sessionOnly := []authenticate.ClientAssertion{authenticate.SessionClientAssertion}
471+
authTokenSet := []authenticate.ClientAssertion{
472+
authenticate.SessionClientAssertion,
473+
authenticate.ClientCredentialsClientAssertion,
474+
authenticate.JWTGrantClientAssertion,
475+
authenticate.PATClientAssertion,
476+
}
477+
478+
tests := []struct {
479+
name string
480+
authVia authenticate.ClientAssertion
481+
allowed []authenticate.ClientAssertion
482+
wantErr bool
483+
}{
484+
{"session endpoints accept a session", authenticate.SessionClientAssertion, sessionOnly, false},
485+
{"session endpoints reject a PAT", authenticate.PATClientAssertion, sessionOnly, true},
486+
{"session endpoints reject an access token", authenticate.AccessTokenClientAssertion, sessionOnly, true},
487+
{"session endpoints reject client credentials", authenticate.ClientCredentialsClientAssertion, sessionOnly, true},
488+
{"session endpoints reject a jwt grant", authenticate.JWTGrantClientAssertion, sessionOnly, true},
489+
490+
{"authtoken accepts a session", authenticate.SessionClientAssertion, authTokenSet, false},
491+
{"authtoken accepts client credentials", authenticate.ClientCredentialsClientAssertion, authTokenSet, false},
492+
{"authtoken accepts a jwt grant", authenticate.JWTGrantClientAssertion, authTokenSet, false},
493+
{"authtoken accepts a PAT", authenticate.PATClientAssertion, authTokenSet, false},
494+
{"authtoken rejects an access token", authenticate.AccessTokenClientAssertion, authTokenSet, true},
495+
{"authtoken rejects passthrough", authenticate.PassthroughHeaderClientAssertion, authTokenSet, true},
496+
}
497+
498+
svc := authenticate.NewService(nil, authenticate.Config{}, nil, nil, nil, nil, nil, nil, nil, nil)
499+
500+
for _, tt := range tests {
501+
t.Run(tt.name, func(t *testing.T) {
502+
ctx := authenticate.SetContextWithPrincipal(context.Background(), &authenticate.Principal{
503+
ID: "principal-1",
504+
Type: schema.UserPrincipal,
505+
AuthVia: tt.authVia,
506+
})
507+
if _, err := svc.GetPrincipal(ctx, tt.allowed...); (err != nil) != tt.wantErr {
508+
t.Errorf("GetPrincipal() error = %v, wantErr %v", err, tt.wantErr)
509+
}
510+
})
511+
}
512+
}

‎core/serviceuser/errors.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ var (
88
ErrInvalidCred = errors.New("service user credential is invalid")
99
ErrInvalidID = errors.New("service user id is invalid")
1010
ErrInvalidKeyID = errors.New("service user key is invalid")
11+
ErrTokenNotJWT = errors.New("token is not a jwt")
1112
ErrConflict = errors.New("service user already exist")
1213
ErrEmptyKey = errors.New("empty key")
1314
ErrDisabled = errors.New("service user is disabled")

‎core/serviceuser/service.go‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -363,21 +363,28 @@ func (s Service) GetBySecret(ctx context.Context, credID string, reqSecret strin
363363
func (s Service) GetByJWT(ctx context.Context, token string) (ServiceUser, error) {
364364
insecureToken, err := jwt.ParseInsecure([]byte(token))
365365
if err != nil {
366-
return ServiceUser{}, fmt.Errorf("invalid serviceuser token: %w", err)
366+
return ServiceUser{}, fmt.Errorf("%w: %v", ErrTokenNotJWT, err)
367367
}
368368
tokenKID, ok := insecureToken.Get(jwk.KeyIDKey)
369369
if !ok {
370-
return ServiceUser{}, fmt.Errorf("invalid key id from token")
370+
return ServiceUser{}, fmt.Errorf("missing key id in token: %w", ErrInvalidKeyID)
371371
}
372-
cred, err := s.credRepo.Get(ctx, tokenKID.(string))
372+
kid, ok := tokenKID.(string)
373+
if !ok {
374+
return ServiceUser{}, fmt.Errorf("key id is not a string: %w", ErrInvalidKeyID)
375+
}
376+
if _, err := uuid.Parse(kid); err != nil {
377+
return ServiceUser{}, fmt.Errorf("key id is not a valid uuid: %w", ErrInvalidKeyID)
378+
}
379+
cred, err := s.credRepo.Get(ctx, kid)
373380
if err != nil {
374-
return ServiceUser{}, fmt.Errorf("credential invalid of kid %s: %w", tokenKID.(string), err)
381+
return ServiceUser{}, fmt.Errorf("credential invalid of kid %s: %w", kid, err)
375382
}
376383

377384
// verify token
378385
_, err = jwt.Parse([]byte(token), jwt.WithKeySet(cred.PublicKey))
379386
if err != nil {
380-
return ServiceUser{}, fmt.Errorf("invalid serviceuser token: %w", err)
387+
return ServiceUser{}, fmt.Errorf("%w: %v", ErrInvalidCred, err)
381388
}
382389
return s.repo.GetByID(ctx, cred.ServiceUserID)
383390
}

‎core/serviceuser/service_test.go‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,16 @@ import (
66
"io"
77
"log/slog"
88
"testing"
9+
"time"
910

11+
"github.com/lestrrat-go/jwx/v2/jwa"
12+
"github.com/lestrrat-go/jwx/v2/jwk"
13+
"github.com/lestrrat-go/jwx/v2/jwt"
1014
"github.com/raystack/frontier/core/relation"
1115
"github.com/raystack/frontier/core/serviceuser"
1216
"github.com/raystack/frontier/core/serviceuser/mocks"
1317
"github.com/raystack/frontier/internal/bootstrap/schema"
18+
"github.com/raystack/frontier/pkg/utils"
1419
)
1520

1621
func newTestService(t *testing.T) (*serviceuser.Service, *mocks.Repository, *mocks.CredentialRepository, *mocks.RelationService, *mocks.MembershipService) {
@@ -227,3 +232,86 @@ func TestService_ListByOrg(t *testing.T) {
227232
})
228233
}
229234
}
235+
236+
func TestService_GetByJWT_Classification(t *testing.T) {
237+
ctx := context.Background()
238+
239+
// buildToken signs a jwt carrying kid in its claims and returns the matching public set.
240+
buildToken := func(t *testing.T, kid string) ([]byte, jwk.Set) {
241+
t.Helper()
242+
key, err := utils.CreateJWKWithKID(kid)
243+
if err != nil {
244+
t.Fatalf("CreateJWKWithKID: %v", err)
245+
}
246+
tok, err := utils.BuildToken(key, "issuer", "subject", time.Hour, nil)
247+
if err != nil {
248+
t.Fatalf("BuildToken: %v", err)
249+
}
250+
set := jwk.NewSet()
251+
if err := set.AddKey(key); err != nil {
252+
t.Fatalf("AddKey: %v", err)
253+
}
254+
pub, err := utils.GetPublicKeySet(ctx, set)
255+
if err != nil {
256+
t.Fatalf("GetPublicKeySet: %v", err)
257+
}
258+
return tok, pub
259+
}
260+
261+
t.Run("not a jwt skips with ErrTokenNotJWT", func(t *testing.T) {
262+
svc, _, _, _, _ := newTestService(t)
263+
if _, err := svc.GetByJWT(ctx, "fpt_not-a-jwt"); !errors.Is(err, serviceuser.ErrTokenNotJWT) {
264+
t.Errorf("GetByJWT() error = %v, want errors.Is(ErrTokenNotJWT)", err)
265+
}
266+
})
267+
268+
t.Run("malformed (non-uuid) kid skips with ErrInvalidKeyID", func(t *testing.T) {
269+
svc, _, _, _, _ := newTestService(t)
270+
tok, _ := buildToken(t, "not-a-uuid")
271+
// credRepo.Get must not be called for a malformed kid
272+
if _, err := svc.GetByJWT(ctx, string(tok)); !errors.Is(err, serviceuser.ErrInvalidKeyID) {
273+
t.Errorf("GetByJWT() error = %v, want errors.Is(ErrInvalidKeyID)", err)
274+
}
275+
})
276+
277+
t.Run("non-string kid skips with ErrInvalidKeyID", func(t *testing.T) {
278+
svc, _, _, _, _ := newTestService(t)
279+
key, err := utils.CreateJWKWithKID("33333333-3333-3333-3333-333333333333")
280+
if err != nil {
281+
t.Fatalf("CreateJWKWithKID: %v", err)
282+
}
283+
tok, err := jwt.NewBuilder().Claim(jwk.KeyIDKey, 12345).Build()
284+
if err != nil {
285+
t.Fatalf("Build: %v", err)
286+
}
287+
signed, err := jwt.Sign(tok, jwt.WithKey(jwa.RS256, key))
288+
if err != nil {
289+
t.Fatalf("Sign: %v", err)
290+
}
291+
if _, err := svc.GetByJWT(ctx, string(signed)); !errors.Is(err, serviceuser.ErrInvalidKeyID) {
292+
t.Errorf("GetByJWT() error = %v, want errors.Is(ErrInvalidKeyID)", err)
293+
}
294+
})
295+
296+
t.Run("unknown kid skips with ErrCredNotExist", func(t *testing.T) {
297+
svc, _, credRepo, _, _ := newTestService(t)
298+
kid := "11111111-1111-1111-1111-111111111111"
299+
tok, _ := buildToken(t, kid)
300+
credRepo.On("Get", ctx, kid).Return(serviceuser.Credential{}, serviceuser.ErrCredNotExist)
301+
if _, err := svc.GetByJWT(ctx, string(tok)); !errors.Is(err, serviceuser.ErrCredNotExist) {
302+
t.Errorf("GetByJWT() error = %v, want errors.Is(ErrCredNotExist)", err)
303+
}
304+
})
305+
306+
t.Run("bad signature stops with ErrInvalidCred", func(t *testing.T) {
307+
svc, _, credRepo, _, _ := newTestService(t)
308+
kid := "22222222-2222-2222-2222-222222222222"
309+
tok, _ := buildToken(t, kid) // signed by one key
310+
_, otherPub := buildToken(t, kid) // verified against a different key with the same kid
311+
credRepo.On("Get", ctx, kid).Return(
312+
serviceuser.Credential{ID: kid, ServiceUserID: "su-1", PublicKey: otherPub}, nil)
313+
if _, err := svc.GetByJWT(ctx, string(tok)); !errors.Is(err, serviceuser.ErrInvalidCred) {
314+
t.Errorf("GetByJWT() error = %v, want errors.Is(ErrInvalidCred)", err)
315+
}
316+
})
317+
}

0 commit comments

Comments
 (0)