summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/SDLPermissionManager.m
blob: 3b5bd301725dd90ac3881623ec9aec3c0255f087 (plain)
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
//
//  SDLPermissionManager.m
//  SmartDeviceLink-iOS
//
//  Created by Joel Fischer on 10/14/15.
//  Copyright © 2015 smartdevicelink. All rights reserved.
//

#import "SDLPermissionManager.h"

#import "SDLHMIPermissions.h"
#import "SDLNotificationConstants.h"
#import "SDLOnHMIStatus.h"
#import "SDLOnPermissionsChange.h"
#import "SDLParameterPermissions.h"
#import "SDLPermissionFilter.h"
#import "SDLPermissionItem.h"
#import "SDLPredefinedWindows.h"
#import "SDLRPCNotificationNotification.h"
#import "SDLStateMachine.h"


NS_ASSUME_NONNULL_BEGIN

@interface SDLPermissionManager ()

@property (strong, nonatomic) NSMutableDictionary<SDLPermissionRPCName, SDLPermissionItem *> *permissions;
@property (strong, nonatomic) NSMutableArray<SDLPermissionFilter *> *filters;
@property (copy, nonatomic, nullable) SDLHMILevel currentHMILevel;
@property (assign, nonatomic) BOOL requiresEncryption;

@end


@implementation SDLPermissionManager

#pragma mark - Lifecycle

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }

    _currentHMILevel = nil;
    _permissions = [NSMutableDictionary<SDLPermissionRPCName, SDLPermissionItem *> dictionary];
    _filters = [NSMutableArray<SDLPermissionFilter *> array];

    // Set up SDL status notifications
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sdl_permissionsDidChange:) name:SDLDidChangePermissionsNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sdl_hmiLevelDidChange:) name:SDLDidChangeHMIStatusNotification object:nil];

    return self;
}

- (void)startWithCompletionHandler:(void (^)(BOOL, NSError *_Nullable))completionHandler {
    completionHandler(YES, nil);
}

- (void)stop {
    _permissions = [NSMutableDictionary<SDLPermissionRPCName, SDLPermissionItem *> dictionary];
    _filters = [NSMutableArray<SDLPermissionFilter *> array];
    _currentHMILevel = nil;
}


#pragma mark - Permissions available

- (BOOL)isRPCAllowed:(NSString *)rpcName {
    return [self isRPCNameAllowed:rpcName];
}

- (BOOL)isRPCNameAllowed:(SDLRPCFunctionName)rpcName {
    if (self.permissions[rpcName] == nil || self.currentHMILevel == nil) {
        return NO;
    }

    SDLPermissionItem *item = self.permissions[rpcName];
    return [item.hmiPermissions.allowed containsObject:self.currentHMILevel];
}

- (SDLPermissionGroupStatus)groupStatusOfRPCs:(NSArray<SDLPermissionRPCName> *)rpcNames {
    return [self groupStatusOfRPCNames:[self sdl_createPermissionElementFromRPCNames:rpcNames]];
}

- (SDLPermissionGroupStatus)groupStatusOfRPCNames:(NSArray<SDLPermissionElement *> *)rpcNames {
    if (self.currentHMILevel == nil) {
        return SDLPermissionGroupStatusUnknown;
    }

    return [self.class sdl_groupStatusOfRPCs:rpcNames withPermissions:[self.permissions copy] hmiLevel:self.currentHMILevel];
}

+ (SDLPermissionGroupStatus)sdl_groupStatusOfRPCs:(NSArray<SDLPermissionElement *> *)rpcNames withPermissions:(NSDictionary<SDLPermissionRPCName, SDLPermissionItem *> *)permissions hmiLevel:(SDLHMILevel)hmiLevel {
    // If we don't have an HMI level, then just say everything is disallowed
    if (hmiLevel == nil) {
        return SDLPermissionGroupStatusUnknown;
    }

    BOOL hasAllowed = NO;
    BOOL hasDisallowed = NO;

    // Loop through all the RPCs we need to check
    for (SDLPermissionElement *permissionElement in rpcNames) {
        NSString *rpcName = permissionElement.rpcName;

        // If at this point in the loop, we have both allowed and disallowed RPCs, return the mixed result
        if (hasAllowed && hasDisallowed) {
            return SDLPermissionGroupStatusMixed;
        }

        // If we don't have a status for this permission, set it as disallowed
        if (permissions[rpcName] == nil) {
            hasDisallowed = YES;
            continue;
        }

        // Check the permission's "allowed" array for the current HMI level
        if ([permissions[rpcName].hmiPermissions.allowed containsObject:hmiLevel]) {
            hasAllowed = YES;
        } else {
            hasDisallowed = YES;
        }
    }

    if (hasAllowed && hasDisallowed) {
        return SDLPermissionGroupStatusMixed;
    } else if (hasAllowed) {
        return SDLPermissionGroupStatusAllowed;
    } else {
        return SDLPermissionGroupStatusDisallowed;
    }
}

- (NSDictionary<SDLPermissionRPCName, NSNumber *> *)statusOfRPCs:(NSArray<SDLPermissionRPCName> *)rpcNames {
    return [self sdl_convertPermissionElementsDictionary:[self statusesOfRPCNames:[self sdl_createPermissionElementFromRPCNames:rpcNames]]];
}

- (NSDictionary<SDLPermissionElement *, NSNumber *> *)statusesOfRPCNames:(NSArray<SDLPermissionElement *> *)rpcNames {
    NSMutableDictionary<SDLPermissionElement *, NSNumber *> *permissionAllowedDict = [NSMutableDictionary dictionary];
    
    for (SDLPermissionElement *permissionElement in rpcNames) {
        permissionAllowedDict[permissionElement] = @([self isRPCNameAllowed:permissionElement.rpcName]);
    }

    return [permissionAllowedDict copy];
}


#pragma mark - Permissions observers

#pragma mark Add Observers

- (SDLPermissionObserverIdentifier)addObserverForRPCs:(NSArray<SDLPermissionRPCName> *)rpcNames groupType:(SDLPermissionGroupType)groupType withHandler:(nonnull SDLPermissionsChangedHandler)handler {
    SDLPermissionFilter *filter = [SDLPermissionFilter filterWithRPCNames:[self sdl_createPermissionElementFromRPCNames:rpcNames] groupType:groupType observer:handler];

    // Store the filter for later use
    [self.filters addObject:filter];

    // If there are permissions that fit the specifications, send immediately. Then return the identifier.
    [self sdl_callFilterObserver:filter];

    return filter.identifier;
}

- (SDLPermissionObserverIdentifier)subscribeToRPCNames:(NSArray<SDLPermissionElement *> *)rpcNames groupType:(SDLPermissionGroupType)groupType withHandler:(SDLPermissionElementsChangedHandler)handler {
    SDLPermissionFilter *filter = [SDLPermissionFilter filterWithRPCNames:rpcNames groupType:groupType observer:handler];

    // Store the filter for later use
    [self.filters addObject:filter];

    // Check permission status and group type to see if we need to call handler immediately after setting the observer
    SDLPermissionGroupStatus permissionStatus = [self groupStatusOfRPCNames:filter.permissionElements];
    if ((groupType == SDLPermissionGroupTypeAny) || (groupType == SDLPermissionGroupTypeAllAllowed && permissionStatus == SDLPermissionGroupStatusAllowed)) {
        [self sdl_callFilterObserver:filter];
    }

    return filter.identifier;
}

- (void)sdl_callFilterObserver:(SDLPermissionFilter *)filter {
    SDLPermissionGroupStatus permissionStatus = [self groupStatusOfRPCNames:filter.permissionElements];
    NSDictionary<SDLPermissionElement *, NSNumber *> *allowedDict = [self statusesOfRPCNames:filter.permissionElements];

    filter.handler(allowedDict, permissionStatus);
}

#pragma mark Remove Observers

- (void)removeAllObservers {
    [self.filters removeAllObjects];
}

- (void)removeObserverForIdentifier:(SDLPermissionObserverIdentifier)identifier {
    NSArray<SDLPermissionFilter *> *filters = [self.filters copy];
    for (NSUInteger i = 0; i < filters.count; i++) {
        SDLPermissionFilter *filter = filters[i];

        if ([filter.identifier isEqual:identifier]) {
            [self.filters removeObjectAtIndex:i];
            break;
        }
    }
}


#pragma mark - SDL Notification Observers

- (void)sdl_permissionsDidChange:(SDLRPCNotificationNotification *)notification {
    if (![notification isNotificationMemberOfClass:[SDLOnPermissionsChange class]]) {
        return;
    }

    SDLOnPermissionsChange *onPermissionChange = notification.notification;

    NSArray<SDLPermissionItem *> *newPermissionItems = [onPermissionChange.permissionItem copy];
    NSArray<SDLPermissionFilter *> *currentFilters = [self.filters copy];

    // We can eliminate calling those filters who had no permission changes, so we'll filter down and see which had permissions that changed
    NSArray<SDLPermissionFilter *> *modifiedFilters = [self.class sdl_filterPermissionChangesForFilters:currentFilters currentPermissions:self.permissions updatedPermissions:newPermissionItems];

    // We need the old group status and new group status for all allowed filters so we know if they should be called
    NSDictionary<SDLPermissionObserverIdentifier, NSNumber<SDLInt> *> *allAllowedFiltersWithOldStatus = [self sdl_currentStatusForFilters:modifiedFilters];

    // Set the updated permissions on our stored permissions object
    for (SDLPermissionItem *item in newPermissionItems) {
        self.permissions[item.rpcName] = item;
    }

    // Check if the observer should be called based on the group type
    NSMutableArray<SDLPermissionFilter *> *filtersToCall = [NSMutableArray array];
    for (SDLPermissionFilter *filter in modifiedFilters) {
        if (filter.groupType == SDLPermissionGroupTypeAllAllowed) {
            SDLPermissionGroupStatus oldStatus = [allAllowedFiltersWithOldStatus[filter.identifier] unsignedIntegerValue];
            SDLPermissionGroupStatus newStatus = [self groupStatusOfRPCNames:filter.permissionElements];

            // We've already eliminated the case where the permissions could stay the same, so if the permissions changed *to* allowed or *away* from allowed, we need to call the observer.
            if (newStatus == SDLPermissionGroupStatusAllowed || oldStatus == SDLPermissionGroupStatusAllowed) {
                [filtersToCall addObject:filter];
            }
        } else {
            // The filter is an `any` type and we know it changed, so we'll call it
            [filtersToCall addObject:filter];
        }
    }

    // For all the modified filters we care about, call them
    for (SDLPermissionFilter *filter in filtersToCall) {
        [self sdl_callFilterObserver:filter];
    }

    self.requiresEncryption = (onPermissionChange.requireEncryption != nil) ? onPermissionChange.requireEncryption.boolValue : [self sdl_containsAtLeastOneRPCThatRequiresEncryption];
}

- (void)sdl_hmiLevelDidChange:(SDLRPCNotificationNotification *)notification {
    if (![notification isNotificationMemberOfClass:[SDLOnHMIStatus class]]) {
        return;
    }

    SDLOnHMIStatus *hmiStatus = notification.notification;

    if (hmiStatus.windowID != nil && hmiStatus.windowID.integerValue != SDLPredefinedWindowsDefaultWindow) {
        return;
    }
    
    SDLHMILevel oldHMILevel = [self.currentHMILevel copy];
    self.currentHMILevel = hmiStatus.hmiLevel;
    NSArray<SDLPermissionFilter *> *filters = [self.filters copy];


    NSMutableArray<SDLPermissionFilter *> *mutableFiltersToCall = [NSMutableArray arrayWithCapacity:filters.count];
    for (SDLPermissionFilter *filter in filters) {
        // Check if the filter changed, according to its group type settings.
        BOOL filterChanged = [self sdl_didFilterChange:filter fromHMILevel:oldHMILevel toHMILevel:self.currentHMILevel];

        if (filterChanged) {
            [mutableFiltersToCall addObject:filter];
        }
    }

    NSArray<SDLPermissionFilter *> *filtersToCall = [mutableFiltersToCall copy];

    // For all the modified filters, call if necessary
    for (SDLPermissionFilter *filter in filtersToCall) {
        [self sdl_callFilterObserver:filter];
    }
}


#pragma mark Helper Methods

- (NSDictionary<SDLPermissionRPCName, NSNumber *> *)sdl_convertPermissionElementsDictionary:(NSDictionary<SDLPermissionElement*, NSNumber *> *)permissionElementsDictionary {
    NSMutableDictionary *rpcNameDictionary = [[NSMutableDictionary alloc] init];
    for (SDLPermissionElement *key in permissionElementsDictionary.allKeys) {
        SDLPermissionRPCName rpcName = key.rpcName;
        [rpcNameDictionary setObject:permissionElementsDictionary[key] forKey:rpcName];
    }

    return rpcNameDictionary;
}

- (NSArray<SDLPermissionElement *> *)sdl_createPermissionElementFromRPCNames:(NSArray<NSString *> *)rpcNames {
    NSMutableArray *permissionElements = [NSMutableArray new];
    for (NSString *rpcName in rpcNames) {
        SDLPermissionElement *permissionElement = [[SDLPermissionElement alloc] initWithRPCName:rpcName parameterPermissions:nil];
        [permissionElements addObject:permissionElement];
    }

    return permissionElements;
}

/**
 *  Determine if a filter changes based on an HMI level change and the filter's group type settings. This will run through the filter's RPCs, check the permission for each and see if any permission within the filter changes based on some permission now being allowed when it wasn't, or not allowed when it was. This also takes into account the group type setting, so an All Allowed filter will return YES if and only if some permission changed *and* that causes a status change *to* or *from* Allowed.
 *
 *  @param filter      The filter to check
 *  @param oldHMILevel The old HMI level
 *  @param newHMILevel The new HMI level
 *
 *  @return Whether or not the filter changed based on the difference in HMI levels.
 */
- (BOOL)sdl_didFilterChange:(SDLPermissionFilter *)filter fromHMILevel:(SDLHMILevel)oldHMILevel toHMILevel:(SDLHMILevel)newHMILevel {
    BOOL changed = NO;
    for (NSString *rpcName in [filter getRPCNamesFromPermissionElements:filter.permissionElements]) {
        SDLPermissionItem *item = self.permissions[rpcName];
        BOOL newAllowed = [item.hmiPermissions.allowed containsObject:self.currentHMILevel];
        BOOL oldAllowed = [item.hmiPermissions.allowed containsObject:oldHMILevel];

        if ((newAllowed && !oldAllowed) || (!newAllowed && oldAllowed)) {
            // Now permitted when it was not before, or not permitted when it was before
            if (filter.groupType == SDLPermissionGroupTypeAny) {
                return YES;
            } else {
                changed = YES;
                break;
            }
        }
    }

    // This is only for the All Allowed group type. Unlike with the Any group type, we need to know if the group status has changed
    if (changed) {
        SDLPermissionGroupStatus oldStatus = [self.class sdl_groupStatusOfRPCs:filter.permissionElements withPermissions:self.permissions hmiLevel:oldHMILevel];
        SDLPermissionGroupStatus newStatus = [self.class sdl_groupStatusOfRPCs:filter.permissionElements withPermissions:self.permissions hmiLevel:newHMILevel];

        // We've already eliminated the case where the permissions could stay the same, so if the permissions changed *to* allowed or *away* from allowed, we need to call the observer.
        if (newStatus == SDLPermissionGroupStatusAllowed || oldStatus == SDLPermissionGroupStatusAllowed) {
            return YES;
        }
    }

    return NO;
}

/**
 *  Get a dictionary of the current group status for filters passed in.
 *
 *  @param filters The filters to check
 *
 *  @return A dictionary of filters as the keys and an NSNumber wrapper for the SDLPermissionGroupStatus
 */
- (NSDictionary<NSUUID *, NSNumber<SDLInt> *> *)sdl_currentStatusForFilters:(NSArray<SDLPermissionFilter *> *)filters {
    // Create a dictionary that has the all allowed filters and stores their group status for future reference
    NSMutableDictionary<SDLPermissionFilter *, NSNumber<SDLInt> *> *filtersWithStatus = [NSMutableDictionary dictionary];
    for (SDLPermissionFilter *filter in filters) {
        if (filter.groupType == SDLPermissionGroupTypeAllAllowed) {
            filtersWithStatus[filter.identifier] = @([self groupStatusOfRPCNames:filter.permissionElements]);
        }
    }

    return [filtersWithStatus copy];
}

/**
 Takes a set of filters and a set of updated permission items. Loops through each permission for each filter and determines if the filter contains a permission that was updated. Returns the set of filters that contain an updated permission.

 @param filters The set of filters to check
 @param currentPermissions The current set of permissions to check the updated permissions and make sure they were modified
 @param updatedPermissions The set of updated permissions to test each filter against
 @return An array of filters that contained one of the passed permissions
 */
+ (NSArray<SDLPermissionFilter *> *)sdl_filterPermissionChangesForFilters:(NSArray<SDLPermissionFilter *> *)filters currentPermissions:(NSMutableDictionary<SDLPermissionRPCName, SDLPermissionItem *> *)currentPermissions updatedPermissions:(NSArray<SDLPermissionItem *> *)updatedPermissions {
    NSMutableArray<SDLPermissionFilter *> *modifiedFilters = [NSMutableArray arrayWithCapacity:filters.count];

    // Loop through each updated permission item for each filter, if the filter had something modified, store it and go to the next filter
    for (SDLPermissionFilter *filter in filters) {
        NSArray<SDLPermissionItem *> *modifiedPermissionItems = [self sdl_modifiedUpdatedPermissions:updatedPermissions comparedToCurrentPermissions:currentPermissions];
        for (SDLPermissionItem *item in modifiedPermissionItems) {
            if ([[filter getRPCNamesFromPermissionElements:filter.permissionElements] containsObject:item.rpcName]) {
                [modifiedFilters addObject:filter];
                break;
            }
        }
    }

    return [modifiedFilters copy];
}

+ (NSArray<SDLPermissionItem *> *)sdl_modifiedUpdatedPermissions:(NSArray<SDLPermissionItem *> *)permissionItems comparedToCurrentPermissions:(NSMutableDictionary<SDLPermissionRPCName, SDLPermissionItem *> *)currentPermissions {
    NSMutableArray<SDLPermissionItem *> *modifiedPermissions = [NSMutableArray arrayWithCapacity:permissionItems.count];

    for (SDLPermissionItem *item in permissionItems) {
        SDLPermissionItem *currentItem = currentPermissions[item.rpcName];
        if (![item isEqual:currentItem]) {
            [modifiedPermissions addObject:item];
        }
    }

    return [modifiedPermissions copy];
}

- (BOOL)sdl_containsAtLeastOneRPCThatRequiresEncryption {
    for (SDLPermissionItem *item in self.permissions.allValues) {
        if (item.requireEncryption) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)rpcRequiresEncryption:(SDLPermissionRPCName)rpcName {
    return [self rpcNameRequiresEncryption:rpcName];
}

- (BOOL)rpcNameRequiresEncryption:(SDLRPCFunctionName)rpcName {
    if (self.permissions[rpcName].requireEncryption != nil) {
        return self.permissions[rpcName].requireEncryption.boolValue;
    }
    return NO;
}

- (BOOL)isPermissionParameterAllowed:(SDLRPCFunctionName)rpcName parameter:(NSString *)parameter {
    return [self isPermissionParameterAllowed:rpcName parameter:parameter permissionItems:self.permissions hmiLevel:self.currentHMILevel];
}

- (BOOL)isPermissionParameterAllowed:(SDLRPCFunctionName)rpcName parameter:(NSString *)parameter permissionItems:(NSMutableDictionary<SDLPermissionRPCName, SDLPermissionItem *> *)permissionItems hmiLevel:(SDLHMILevel)hmiLevel {

    SDLPermissionItem *permissionItem = permissionItems[rpcName];
    if (permissionItem == nil || ![self isRPCNameAllowed:rpcName] || permissionItem.parameterPermissions == nil || permissionItem.parameterPermissions.allowed == nil) {
        return NO;
    } else if (permissionItem.parameterPermissions.userDisallowed != nil) {
        return [permissionItem.parameterPermissions.allowed containsObject:parameter] && ![permissionItem.parameterPermissions.userDisallowed containsObject:parameter];
    } else {
        return [permissionItem.parameterPermissions.allowed containsObject:parameter];
    }
}

@end

NS_ASSUME_NONNULL_END