-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
subscription.ts
737 lines (644 loc) · 20.8 KB
/
subscription.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { GraphQLResult } from '@aws-amplify/api';
import { InternalAPI } from '@aws-amplify/api/internals';
import {
ConsoleLogger,
Hub,
HubCapsule,
fetchAuthSession,
} from '@aws-amplify/core';
import {
BackgroundProcessManager,
Category,
CustomUserAgentDetails,
DataStoreAction,
GraphQLAuthMode,
JwtPayload,
} from '@aws-amplify/core/internals/utils';
import { Observable, Observer, SubscriptionLike } from 'rxjs';
import { CONTROL_MSG as PUBSUB_CONTROL_MSG } from '@aws-amplify/api-graphql';
import {
AmplifyContext,
AuthModeStrategy,
ErrorHandler,
InternalSchema,
ModelPredicate,
PersistentModel,
PredicatesGroup,
ProcessName,
SchemaModel,
SchemaNamespace,
} from '../../types';
import {
RTFError,
TransformerMutationType,
buildSubscriptionGraphQLOperation,
generateRTFRemediation,
getAuthorizationRules,
getModelAuthModes,
getTokenForCustomAuth,
getUserGroupsFromToken,
predicateToGraphQLFilter,
} from '../utils';
import { ModelPredicateCreator } from '../../predicates';
import { validatePredicate } from '../../util';
import { getSubscriptionErrorType } from './errorMaps';
const logger = new ConsoleLogger('DataStore');
export enum CONTROL_MSG {
CONNECTED = 'CONNECTED',
}
export enum USER_CREDENTIALS {
'none',
'unauth',
'auth',
}
interface AuthorizationInfo {
authMode: GraphQLAuthMode;
isOwner: boolean;
ownerField?: string;
ownerValue?: string;
}
class SubscriptionProcessor {
private readonly typeQuery = new WeakMap<
SchemaModel,
[TransformerMutationType, string, string][]
>();
private buffer: [TransformerMutationType, SchemaModel, PersistentModel][] =
[];
private dataObserver!: Observer<any>;
private runningProcesses = new BackgroundProcessManager();
constructor(
private readonly schema: InternalSchema,
private readonly syncPredicates: WeakMap<
SchemaModel,
ModelPredicate<any> | null
>,
private readonly amplifyConfig: Record<string, any> = {},
private readonly authModeStrategy: AuthModeStrategy,
private readonly errorHandler: ErrorHandler,
private readonly amplifyContext: AmplifyContext = {
InternalAPI,
},
) {}
private buildSubscription(
namespace: SchemaNamespace,
model: SchemaModel,
transformerMutationType: TransformerMutationType,
userCredentials: USER_CREDENTIALS,
oidcTokenPayload: JwtPayload | undefined,
authMode: GraphQLAuthMode,
filterArg = false,
): {
opType: TransformerMutationType;
opName: string;
query: string;
authMode: GraphQLAuthMode;
isOwner: boolean;
ownerField?: string;
ownerValue?: string;
} {
const { aws_appsync_authenticationType } = this.amplifyConfig;
const { isOwner, ownerField, ownerValue } =
this.getAuthorizationInfo(
model,
userCredentials,
aws_appsync_authenticationType,
oidcTokenPayload,
authMode,
) || {};
const [opType, opName, query] = buildSubscriptionGraphQLOperation(
namespace,
model,
transformerMutationType,
isOwner,
ownerField!,
filterArg,
);
return { authMode, opType, opName, query, isOwner, ownerField, ownerValue };
}
private getAuthorizationInfo(
model: SchemaModel,
userCredentials: USER_CREDENTIALS,
defaultAuthType: GraphQLAuthMode,
oidcTokenPayload: JwtPayload | undefined,
authMode: GraphQLAuthMode,
): AuthorizationInfo {
const rules = getAuthorizationRules(model);
// Return null if user doesn't have proper credentials for private API with IAM auth
const iamPrivateAuth =
authMode === 'iam' &&
rules.find(
rule => rule.authStrategy === 'private' && rule.provider === 'iam',
);
if (iamPrivateAuth && userCredentials === USER_CREDENTIALS.unauth) {
return null!;
}
// Group auth should take precedence over owner auth, so we are checking
// if rule(s) have group authorization as well as if either the Cognito or
// OIDC token has a groupClaim. If so, we are returning auth info before
// any further owner-based auth checks.
const groupAuthRules = rules.filter(
rule =>
rule.authStrategy === 'groups' &&
['userPools', 'oidc'].includes(rule.provider),
);
const validGroup =
(authMode === 'oidc' || authMode === 'userPool') &&
// eslint-disable-next-line array-callback-return
groupAuthRules.find(groupAuthRule => {
// validate token against groupClaim
if (oidcTokenPayload) {
const oidcUserGroups = getUserGroupsFromToken(
oidcTokenPayload,
groupAuthRule,
);
return [...oidcUserGroups].find(userGroup => {
return groupAuthRule.groups.find(group => group === userGroup);
});
}
});
if (validGroup) {
return {
authMode,
isOwner: false,
};
}
let ownerAuthInfo: AuthorizationInfo;
if (ownerAuthInfo!) {
return ownerAuthInfo!;
}
// Owner auth needs additional values to be returned in order to create the subscription with
// the correct parameters so we are getting the owner value from the OIDC token via the
// identityClaim from the auth rule.
const oidcOwnerAuthRules =
authMode === 'oidc' || authMode === 'userPool'
? rules.filter(
rule =>
rule.authStrategy === 'owner' &&
(rule.provider === 'oidc' || rule.provider === 'userPools'),
)
: [];
oidcOwnerAuthRules.forEach(ownerAuthRule => {
const ownerValue = oidcTokenPayload?.[ownerAuthRule.identityClaim];
const singleOwner =
model.fields[ownerAuthRule.ownerField]?.isArray !== true;
const isOwnerArgRequired =
singleOwner && !ownerAuthRule.areSubscriptionsPublic;
if (ownerValue) {
ownerAuthInfo = {
authMode,
isOwner: isOwnerArgRequired,
ownerField: ownerAuthRule.ownerField,
ownerValue: String(ownerValue),
};
}
});
if (ownerAuthInfo!) {
return ownerAuthInfo!;
}
// Fallback: return authMode or default auth type
return {
authMode: authMode || defaultAuthType,
isOwner: false,
};
}
private hubQueryCompletionListener(
completed: () => void,
capsule: HubCapsule<'datastore', { event: string }>,
) {
const {
payload: { event },
} = capsule;
if (event === PUBSUB_CONTROL_MSG.SUBSCRIPTION_ACK) {
completed();
}
}
start(): [
Observable<CONTROL_MSG>,
Observable<[TransformerMutationType, SchemaModel, PersistentModel]>,
] {
this.runningProcesses =
this.runningProcesses || new BackgroundProcessManager();
const ctlObservable = new Observable<CONTROL_MSG>(observer => {
const promises: Promise<void>[] = [];
// Creating subs for each model/operation combo so they can be unsubscribed
// independently, since the auth retry behavior is asynchronous.
let subscriptions: Record<
string,
{
[TransformerMutationType.CREATE]: SubscriptionLike[];
[TransformerMutationType.UPDATE]: SubscriptionLike[];
[TransformerMutationType.DELETE]: SubscriptionLike[];
}
> = {};
let oidcTokenPayload: JwtPayload | undefined;
let userCredentials = USER_CREDENTIALS.none;
this.runningProcesses.add(async () => {
try {
// retrieving current AWS Credentials
const credentials = (await fetchAuthSession()).tokens?.accessToken;
userCredentials = credentials
? USER_CREDENTIALS.auth
: USER_CREDENTIALS.unauth;
} catch (err) {
// best effort to get AWS credentials
}
try {
// retrieving current token info from Cognito UserPools
const session = await fetchAuthSession();
oidcTokenPayload = session.tokens?.idToken?.payload;
} catch (err) {
// best effort to get jwt from Cognito
}
Object.values(this.schema.namespaces).forEach(namespace => {
Object.values(namespace.models)
.filter(({ syncable }) => syncable)
.forEach(
modelDefinition =>
this.runningProcesses.isOpen &&
this.runningProcesses.add(async () => {
const modelAuthModes = await getModelAuthModes({
authModeStrategy: this.authModeStrategy,
defaultAuthMode:
this.amplifyConfig.aws_appsync_authenticationType,
modelName: modelDefinition.name,
schema: this.schema,
});
// subscriptions are created only based on the READ auth mode(s)
const readAuthModes = modelAuthModes.READ;
subscriptions = {
...subscriptions,
[modelDefinition.name]: {
[TransformerMutationType.CREATE]: [],
[TransformerMutationType.UPDATE]: [],
[TransformerMutationType.DELETE]: [],
},
};
const operations = [
TransformerMutationType.CREATE,
TransformerMutationType.UPDATE,
TransformerMutationType.DELETE,
];
const operationAuthModeAttempts = {
[TransformerMutationType.CREATE]: 0,
[TransformerMutationType.UPDATE]: 0,
[TransformerMutationType.DELETE]: 0,
};
const predicatesGroup = ModelPredicateCreator.getPredicates(
this.syncPredicates.get(modelDefinition)!,
false,
);
const addFilterArg = predicatesGroup !== undefined;
// Retry subscriptions that failed for one of the following reasons:
// 1. unauthorized - retry with next auth mode (if available)
// 2. RTF error - retry without sending filter arg. (filtering will fall back to clientside)
const subscriptionRetry = async (
operation,
addFilter = addFilterArg,
) => {
const {
opType: transformerMutationType,
opName,
query,
isOwner,
ownerField,
ownerValue,
authMode,
} = this.buildSubscription(
namespace,
modelDefinition,
operation,
userCredentials,
oidcTokenPayload,
readAuthModes[operationAuthModeAttempts[operation]],
addFilter,
);
const authToken = await getTokenForCustomAuth(
authMode,
this.amplifyConfig,
);
const variables = {};
const customUserAgentDetails: CustomUserAgentDetails = {
category: Category.DataStore,
action: DataStoreAction.Subscribe,
};
if (addFilter && predicatesGroup) {
(variables as any).filter =
predicateToGraphQLFilter(predicatesGroup);
}
if (isOwner) {
if (!ownerValue) {
observer.error(
'Owner field required, sign in is needed in order to perform this operation',
);
return;
}
variables[ownerField!] = ownerValue;
}
logger.debug(
`Attempting ${operation} subscription with authMode: ${
readAuthModes[operationAuthModeAttempts[operation]]
}`,
);
const queryObservable =
this.amplifyContext.InternalAPI.graphql(
{
query,
variables,
...{ authMode },
authToken,
},
undefined,
customUserAgentDetails,
) as unknown as Observable<
GraphQLResult<Record<string, PersistentModel>>
>;
let subscriptionReadyCallback: (param?: unknown) => void;
// TODO: consider onTerminate.then(() => API.cancel(...))
subscriptions[modelDefinition.name][
transformerMutationType
].push(
queryObservable.subscribe({
next: result => {
const { data, errors } = result;
if (Array.isArray(errors) && errors.length > 0) {
const messages = (
errors as {
message: string;
}[]
).map(({ message }) => message);
logger.warn(
`Skipping incoming subscription. Messages: ${messages.join(
'\n',
)}`,
);
this.drainBuffer();
return;
}
const resolvedPredicatesGroup =
ModelPredicateCreator.getPredicates(
this.syncPredicates.get(modelDefinition)!,
false,
);
const { [opName]: record } = data;
// checking incoming subscription against syncPredicate.
// once AppSync implements filters on subscriptions, we'll be
// able to set these when establishing the subscription instead.
// Until then, we'll need to filter inbound
if (
this.passesPredicateValidation(
record,
resolvedPredicatesGroup!,
)
) {
this.pushToBuffer(
transformerMutationType,
modelDefinition,
record,
);
}
this.drainBuffer();
},
error: async subscriptionError => {
const {
errors: [{ message = '' } = {}],
} = ({
// eslint-disable-next-line no-empty-pattern
errors: [],
} = subscriptionError);
const isRTFError =
// only attempt catch if a filter variable was added to the subscription query
addFilter &&
this.catchRTFError(
message,
modelDefinition,
predicatesGroup,
);
// Catch RTF errors
if (isRTFError) {
// Unsubscribe and clear subscription array for model/operation
subscriptions[modelDefinition.name][
transformerMutationType
].forEach(subscription =>
subscription.unsubscribe(),
);
subscriptions[modelDefinition.name][
transformerMutationType
] = [];
// retry subscription connection without filter
subscriptionRetry(operation, false);
return;
}
if (
message.includes(
PUBSUB_CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR,
) ||
message.includes(
PUBSUB_CONTROL_MSG.CONNECTION_FAILED,
)
) {
// Unsubscribe and clear subscription array for model/operation
subscriptions[modelDefinition.name][
transformerMutationType
].forEach(subscription =>
subscription.unsubscribe(),
);
subscriptions[modelDefinition.name][
transformerMutationType
] = [];
operationAuthModeAttempts[operation]++;
if (
operationAuthModeAttempts[operation] >=
readAuthModes.length
) {
// last auth mode retry. Continue with error
logger.debug(
`${operation} subscription failed with authMode: ${
readAuthModes[
operationAuthModeAttempts[operation] - 1
]
}`,
);
} else {
// retry with different auth mode. Do not trigger
// observer error or error handler
logger.debug(
`${operation} subscription failed with authMode: ${
readAuthModes[
operationAuthModeAttempts[operation] - 1
]
}. Retrying with authMode: ${
readAuthModes[
operationAuthModeAttempts[operation]
]
}`,
);
subscriptionRetry(operation);
return;
}
}
logger.warn('subscriptionError', message);
try {
// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
await this.errorHandler({
recoverySuggestion:
'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',
localModel: null!,
message,
model: modelDefinition.name,
operation,
errorType:
getSubscriptionErrorType(subscriptionError),
process: ProcessName.subscribe,
remoteModel: null!,
cause: subscriptionError,
});
} catch (e) {
logger.error(
'Subscription error handler failed with:',
e,
);
}
if (typeof subscriptionReadyCallback === 'function') {
subscriptionReadyCallback();
}
if (
message.includes('"errorType":"Unauthorized"') ||
message.includes('"errorType":"OperationDisabled"')
) {
return;
}
observer.error(message);
},
}),
);
promises.push(
(async () => {
let boundFunction: any;
let removeBoundFunctionListener: () => void;
await new Promise(resolve => {
subscriptionReadyCallback = resolve;
boundFunction = this.hubQueryCompletionListener.bind(
this,
resolve,
);
removeBoundFunctionListener = Hub.listen(
'api',
boundFunction,
);
});
removeBoundFunctionListener();
})(),
);
};
operations.forEach(op => subscriptionRetry(op));
}),
);
});
this.runningProcesses.isOpen &&
this.runningProcesses.add(() =>
Promise.all(promises).then(() => {
observer.next(CONTROL_MSG.CONNECTED);
}),
);
}, 'subscription processor new subscriber');
return this.runningProcesses.addCleaner(async () => {
Object.keys(subscriptions).forEach(modelName => {
subscriptions[modelName][TransformerMutationType.CREATE].forEach(
subscription => {
subscription.unsubscribe();
},
);
subscriptions[modelName][TransformerMutationType.UPDATE].forEach(
subscription => {
subscription.unsubscribe();
},
);
subscriptions[modelName][TransformerMutationType.DELETE].forEach(
subscription => {
subscription.unsubscribe();
},
);
});
});
});
const dataObservable = new Observable<
[TransformerMutationType, SchemaModel, PersistentModel]
>(observer => {
this.dataObserver = observer;
this.drainBuffer();
return this.runningProcesses.addCleaner(async () => {
this.dataObserver = null!;
});
});
return [ctlObservable, dataObservable];
}
public async stop() {
await this.runningProcesses.close();
await this.runningProcesses.open();
}
private passesPredicateValidation(
record: PersistentModel,
predicatesGroup: PredicatesGroup<any>,
): boolean {
if (!predicatesGroup) {
return true;
}
const { predicates, type } = predicatesGroup;
return validatePredicate(record, type, predicates);
}
private pushToBuffer(
transformerMutationType: TransformerMutationType,
modelDefinition: SchemaModel,
data: PersistentModel,
) {
this.buffer.push([transformerMutationType, modelDefinition, data]);
}
private drainBuffer() {
if (this.dataObserver) {
this.buffer.forEach(data => {
this.dataObserver.next!(data);
});
this.buffer = [];
}
}
/**
* @returns true if the service returned an RTF subscription error
* @remarks logs a warning with remediation instructions
*
*/
private catchRTFError(
message: string,
modelDefinition: SchemaModel,
predicatesGroup: PredicatesGroup<any> | undefined,
): boolean {
const header =
'Backend subscriptions filtering error.\n' +
'Subscriptions filtering will be applied clientside.\n';
const messageErrorTypeMap = {
'UnknownArgument: Unknown field argument filter': RTFError.UnknownField,
'Filters exceed maximum attributes limit': RTFError.MaxAttributes,
'Filters combination exceed maximum limit': RTFError.MaxCombinations,
'filter uses same fieldName multiple time': RTFError.RepeatedFieldname,
"The variables input contains a field name 'not'": RTFError.NotGroup,
'The variables input contains a field that is not defined for input object type':
RTFError.FieldNotInType,
};
const [_errorMsg, errorType] =
Object.entries(messageErrorTypeMap).find(([errorMsg]) =>
message.includes(errorMsg),
) || [];
if (errorType !== undefined) {
const remediationMessage = generateRTFRemediation(
errorType,
modelDefinition,
predicatesGroup,
);
logger.warn(`${header}\n${message}\n${remediationMessage}`);
return true;
}
return false;
}
}
export { SubscriptionProcessor };