Skip to content

Commit 1c282de

Browse files
feat(sdk): take explicit consent and send a login or signup intent (#1922)
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 955885f commit 1c282de

23 files changed

Lines changed: 548 additions & 155 deletions

‎core/authenticate/authenticate.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,14 @@ func (f *Flow) Intent() FlowIntent {
141141
return FlowIntent(intent)
142142
}
143143

144+
// reject tags a rejection with the strategy this flow came through
145+
func (f *Flow) reject(err error) error {
146+
if f == nil || f.Method == "" {
147+
return err
148+
}
149+
return &FlowRejection{Err: err, Strategy: f.Method}
150+
}
151+
144152
// Consent reads what the user accepted from metadata, reporting whether the flow
145153
// carries one at all. A nil flow is allowed.
146154
//

‎core/authenticate/service.go‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,15 @@ var (
6767
ErrConsentRequired = errors.New("consent required for the configured documents")
6868
)
6969

70+
// FlowRejection is a login, signup rejection tagged with the strategy
71+
type FlowRejection struct {
72+
Err error
73+
Strategy string
74+
}
75+
76+
func (r *FlowRejection) Error() string { return r.Err.Error() }
77+
func (r *FlowRejection) Unwrap() error { return r.Err }
78+
7079
type UserService interface {
7180
GetByID(ctx context.Context, id string) (user.User, error)
7281
Create(context.Context, user.User) (user.User, error)
@@ -895,7 +904,7 @@ func (s Service) getOrCreateUser(ctx context.Context, flow *Flow, email, title s
895904
existingUser, err := s.userService.GetByID(ctx, email)
896905
if err == nil {
897906
if intent == FlowIntentSignup {
898-
return user.User{}, ErrSignupUserExists
907+
return user.User{}, flow.reject(ErrSignupUserExists)
899908
}
900909
// user is already registered: no consent record, because one written outside
901910
// a user creation would date an agreement made elsewhere
@@ -908,7 +917,7 @@ func (s Service) getOrCreateUser(ctx context.Context, flow *Flow, email, title s
908917
// the gate that matters: every strategy ends here, the last point before an
909918
// account would be created for someone trying to log in
910919
if intent == FlowIntentLogin {
911-
return user.User{}, ErrLoginUserNotFound
920+
return user.User{}, flow.reject(ErrLoginUserNotFound)
912921
}
913922

914923
// register a new user
@@ -978,7 +987,7 @@ func (s Service) resolveConsent(flow *Flow) ([]consent.Document, error) {
978987
documents, err := s.consentService.ResolveAll(consented.AcceptedDocumentIDs)
979988
if err != nil {
980989
// the wrapped error names what is missing, for the log not the response
981-
return nil, fmt.Errorf("%w: %w", ErrConsentRequired, err)
990+
return nil, flow.reject(fmt.Errorf("%w: %w", ErrConsentRequired, err))
982991
}
983992
return documents, nil
984993
}

‎core/authenticate/service_test.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1688,6 +1688,10 @@ func TestService_FinishFlow_Intent(t *testing.T) {
16881688
if tt.wantErr != nil {
16891689
assert.ErrorIs(t, err, tt.wantErr)
16901690
assert.Nil(t, got)
1691+
// the rejection names the strategy, for the client that cannot know it
1692+
var rejection *authenticate.FlowRejection
1693+
require.ErrorAs(t, err, &rejection)
1694+
assert.Equal(t, authenticate.MailOTPAuthMethod.String(), rejection.Strategy)
16911695
return
16921696
}
16931697
require.NoError(t, err)
@@ -1812,6 +1816,10 @@ func TestService_FinishFlow_Consent(t *testing.T) {
18121816
assert.ErrorIs(t, err, authenticate.ErrConsentRequired)
18131817
// the wrapped error still names what was missing
18141818
assert.ErrorIs(t, err, consent.ErrMissingDocuments)
1819+
// and the strategy it came through
1820+
var rejection *authenticate.FlowRejection
1821+
require.ErrorAs(t, err, &rejection)
1822+
assert.Equal(t, authenticate.MailOTPAuthMethod.String(), rejection.Strategy)
18151823
// the rejection is the error and nothing else
18161824
assert.Nil(t, got)
18171825
mockUserService.AssertNotCalled(t, "Create", mock.Anything, mock.Anything)

‎internal/api/v1beta1connect/authenticate.go‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,21 @@ type authFlowRejection struct {
3434
err error
3535
}
3636

37+
// toConnectError builds a connect error with details for flow rejection
38+
func (r authFlowRejection) toConnectError(err error) *connect.Error {
39+
connectErr := connect.NewError(r.code, r.err)
40+
var flowRejection *authenticate.FlowRejection
41+
if !errors.As(err, &flowRejection) {
42+
return connectErr
43+
}
44+
strategy := &frontierv1beta1.AuthStrategy{Name: flowRejection.Strategy}
45+
46+
if detail, detailErr := connect.NewErrorDetail(strategy); detailErr == nil {
47+
connectErr.AddDetail(detail)
48+
}
49+
return connectErr
50+
}
51+
3752
// lookupAuthFlowRejection maps the four errors both auth RPCs have to make
3853
// legible. FailedPrecondition separates a consent rejection from a bad code or
3954
// an expired flow, and ErrInvalidMethod shares it because what is wrong is the
@@ -128,7 +143,7 @@ func (h *ConnectHandler) Authenticate(ctx context.Context, request *connect.Requ
128143
errorLogger.LogServiceError(ctx, request, "Authenticate.StartFlow", err,
129144
"strategy", request.Msg.GetStrategyName(),
130145
"intent", intent.String())
131-
return nil, connect.NewError(rejection.code, rejection.err)
146+
return nil, rejection.toConnectError(err)
132147
}
133148
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("Authenticate: strategy=%s email=%s: %w", request.Msg.GetStrategyName(), request.Msg.GetEmail(), err))
134149
}
@@ -190,7 +205,7 @@ func (h *ConnectHandler) AuthCallback(ctx context.Context, request *connect.Requ
190205
errorLogger.LogServiceError(ctx, request, "AuthCallback.FinishFlow", err,
191206
"strategy", request.Msg.GetStrategyName(),
192207
"state", request.Msg.GetState())
193-
return nil, connect.NewError(rejection.code, rejection.err)
208+
return nil, rejection.toConnectError(err)
194209
}
195210

196211
// ErrUnsupportedMethod here means the strategy and state the client sent match

‎internal/api/v1beta1connect/authenticate_test.go‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,18 @@ import (
2323
"github.com/stretchr/testify/require"
2424
)
2525

26+
// authRejectionStrategy reads the one AuthStrategy detail a callback rejection
27+
// carries.
28+
func authRejectionStrategy(t *testing.T, connectErr *connect.Error) *frontierv1beta1.AuthStrategy {
29+
t.Helper()
30+
require.Len(t, connectErr.Details(), 1)
31+
msg, err := connectErr.Details()[0].Value()
32+
require.NoError(t, err)
33+
strategy, ok := msg.(*frontierv1beta1.AuthStrategy)
34+
require.True(t, ok, "detail is %T, want AuthStrategy", msg)
35+
return strategy
36+
}
37+
2638
func TestConnectHandler_AuthToken_ServiceUser(t *testing.T) {
2739
tests := []struct {
2840
name string
@@ -529,6 +541,9 @@ func TestConnectHandler_Authenticate_Rejections(t *testing.T) {
529541
assert.Equal(t, tt.wantCode, connectErr.Code())
530542
assert.Equal(t, tt.wantMsg, connectErr.Message())
531543
assert.NotContains(t, connectErr.Message(), "terms_of_service")
544+
// at flow start the client named the strategy itself, so nothing is
545+
// echoed back
546+
assert.Empty(t, connectErr.Details())
532547
})
533548
}
534549
}
@@ -593,6 +608,66 @@ func TestConnectHandler_AuthCallback_Rejections(t *testing.T) {
593608
}
594609
}
595610

611+
// TestConnectHandler_AuthCallback_RejectionNamesStrategy covers the
612+
// AuthStrategy detail the callback attaches so a client can put the message
613+
// under the button that caused it. A rejection with no flow behind it carries
614+
// no detail.
615+
func TestConnectHandler_AuthCallback_RejectionNamesStrategy(t *testing.T) {
616+
tests := []struct {
617+
name string
618+
err error
619+
620+
wantCode connect.Code
621+
wantStrategy string
622+
}{
623+
{
624+
name: "an oidc rejection names its provider",
625+
err: &authenticate.FlowRejection{Err: authenticate.ErrLoginUserNotFound, Strategy: "google"},
626+
wantCode: connect.CodeNotFound,
627+
wantStrategy: "google",
628+
},
629+
{
630+
name: "a wrapped consent rejection keeps its strategy",
631+
err: &authenticate.FlowRejection{
632+
Err: fmt.Errorf("%w: %w: terms_of_service", authenticate.ErrConsentRequired, consent.ErrMissingDocuments),
633+
Strategy: authenticate.MailOTPAuthMethod.String(),
634+
},
635+
wantCode: connect.CodeFailedPrecondition,
636+
wantStrategy: authenticate.MailOTPAuthMethod.String(),
637+
},
638+
{
639+
name: "a bare sentinel carries no detail",
640+
err: authenticate.ErrSignupUserExists,
641+
wantCode: connect.CodeAlreadyExists,
642+
},
643+
}
644+
645+
for _, tt := range tests {
646+
t.Run(tt.name, func(t *testing.T) {
647+
ctx := context.Background()
648+
649+
mockAuthnSrv := mocks.NewAuthnService(t)
650+
mockAuthnSrv.EXPECT().FinishFlow(ctx, mock.Anything).Return(nil, tt.err)
651+
652+
handler := &ConnectHandler{authnService: mockAuthnSrv}
653+
resp, err := handler.AuthCallback(ctx, connect.NewRequest(&frontierv1beta1.AuthCallbackRequest{
654+
State: "state",
655+
Code: "code",
656+
}))
657+
658+
assert.Nil(t, resp)
659+
connectErr := err.(*connect.Error)
660+
assert.Equal(t, tt.wantCode, connectErr.Code())
661+
assert.NotContains(t, connectErr.Message(), "terms_of_service")
662+
if tt.wantStrategy == "" {
663+
assert.Empty(t, connectErr.Details())
664+
return
665+
}
666+
assert.Equal(t, tt.wantStrategy, authRejectionStrategy(t, connectErr).GetName())
667+
})
668+
}
669+
}
670+
596671
// TestConnectHandler_AuthCallback_UnmappedErrorStaysInternal pins the boundary of
597672
// the closed code set: an error with no code of its own stays a 500.
598673
func TestConnectHandler_AuthCallback_UnmappedErrorStaysInternal(t *testing.T) {

‎web/apps/client-demo/src/pages/Callback.tsx‎

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,22 @@ import { useEffect, Suspense, useContext } from 'react';
22
import { Flex } from '@raystack/apsara';
33
import { useSearchParams, useNavigate } from 'react-router-dom';
44
import useAuthRedirect from '@/hooks/useAuthRedirect';
5-
import { FrontierServiceQueries, useQuery } from '@raystack/frontier/hooks';
5+
import {
6+
Code,
7+
ConnectError,
8+
FrontierServiceQueries,
9+
useQuery
10+
} from '@raystack/frontier/hooks';
11+
import { describeAuthError } from '@raystack/frontier/client';
612
import AuthContext from '@/contexts/auth';
713

14+
const REJECTION_ROUTE: Partial<Record<Code, string>> = {
15+
[Code.AlreadyExists]: '/signup',
16+
[Code.FailedPrecondition]: '/signup',
17+
[Code.NotFound]: '/login'
18+
};
19+
const DEFAULT_REJECTION_ROUTE = '/login';
20+
821
function CallbackComponent() {
922
const [searchParams] = useSearchParams();
1023
const navigate = useNavigate();
@@ -13,27 +26,28 @@ function CallbackComponent() {
1326
const state = searchParams.get('state') || '';
1427
const code = searchParams.get('code') || '';
1528

16-
const { isSuccess, isError, error, isLoading } = useQuery(
29+
const { isSuccess, isError, error } = useQuery(
1730
FrontierServiceQueries.authCallback,
1831
{
1932
state,
2033
code
2134
},
22-
{ enabled: !!state && !!code }
35+
{ enabled: !!state && !!code, retry: false }
2336
);
2437

2538
useEffect(() => {
26-
if (!isLoading) {
27-
if (isSuccess) {
28-
navigate('/');
29-
setIsAuthorized(true);
30-
} else if (isError) {
31-
console.error('Auth callback failed:', error);
32-
setIsAuthorized(false);
33-
navigate('/login', { replace: true });
34-
}
39+
if (isSuccess) {
40+
setIsAuthorized(true);
41+
navigate('/', { replace: true });
42+
} else if (isError) {
43+
setIsAuthorized(false);
44+
const route = REJECTION_ROUTE[ConnectError.from(error).code];
45+
navigate(route ?? DEFAULT_REJECTION_ROUTE, {
46+
replace: true,
47+
state: describeAuthError(error)
48+
});
3549
}
36-
}, [isSuccess, isError, navigate, error, isLoading, setIsAuthorized]);
50+
}, [isSuccess, isError, error, navigate, setIsAuthorized]);
3751

3852
return (
3953
<Flex
Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
import useAuthRedirect from '@/hooks/useAuthRedirect';
22
import { Flex } from '@raystack/apsara';
3-
import { SignInView } from '@raystack/frontier/client';
3+
import { SignInView, type AuthRejection } from '@raystack/frontier/client';
4+
import { useLocation } from 'react-router-dom';
45

56
export default function Login() {
67
useAuthRedirect();
8+
9+
const rejection = useLocation().state as AuthRejection | null;
10+
711
return (
812
<Flex
913
justify="center"
1014
align="center"
1115
style={{ height: '100vh', width: '100vw' }}
1216
>
13-
<SignInView />
17+
<SignInView error={rejection ?? undefined} />
1418
</Flex>
1519
);
1620
}
Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
11
import useAuthRedirect from '@/hooks/useAuthRedirect';
22
import { Flex } from '@raystack/apsara';
3-
import { SignUpView } from '@raystack/frontier/client';
3+
import { SignUpView, type AuthRejection } from '@raystack/frontier/client';
4+
import { useLocation } from 'react-router-dom';
45

56
export default function Signup() {
67
useAuthRedirect();
78

9+
const rejection = useLocation().state as AuthRejection | null;
10+
811
return (
912
<Flex
1013
justify="center"
1114
align="center"
1215
style={{ height: '100vh', width: '100vw' }}
1316
>
14-
<SignUpView />
17+
<SignUpView error={rejection ?? undefined} />
1518
</Flex>
1619
);
1720
}

‎web/pnpm-lock.yaml‎

Lines changed: 8 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)