aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java
blob: ed7f82a45fdbb2c62848be48a46136dc4f792611 (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
/*-
 * ============LICENSE_START=======================================================
 * VID
 * ================================================================================
 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.vid.roles;


import static java.util.Collections.emptyMap;
import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.assertj.core.util.Lists;
import org.mockito.Mock;
import org.onap.vid.aai.AaiResponse;
import org.onap.vid.aai.exceptions.RoleParsingException;
import org.onap.vid.category.CategoryParametersResponse;
import org.onap.vid.model.CategoryParameter.Family;
import org.onap.vid.model.Subscriber;
import org.onap.vid.model.SubscriberList;
import org.onap.vid.services.AaiService;
import org.onap.vid.services.CategoryParameterService;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class RoleProviderTest {

    private static final String SAMPLE_SUBSCRIBER = "sampleSubscriber";
    private static final String SAMPLE_SUBSCRIBER_ID = "subscriberId";
    private static final String SERVICE_TYPE_LOGS = "LOGS";
    private static final String TENANT_PERMITTED = "PERMITTED";
    private static final String SAMPLE_SERVICE = "sampleService";
    private static final String SAMPLE_TENANT = "sampleTenant";
    private static final String SAMPLE_ROLE_PREFIX = "prefix";
    private static final String EXISTING_OWNING_ENTITY_NAME = "WayneHolland";
    private static final String EXISTING_OWNING_ENTITY_ID = "d61e6f2d-12fa-4cc2-91df-7c244011d6fc";
    private static final String NOT_EXISTING_OWNING_ENTITY_NAME = "notExistingOwningEntity";

    @Mock
    private AaiService aaiService;

    @Mock
    private HttpServletRequest request;

    @Mock
    private AaiResponse<SubscriberList> subscriberListResponse;

    @Mock
    private RoleValidatorFactory roleValidatorFactory;

    @Mock
    private CategoryParameterService categoryParameterService;

    private RoleProvider roleProvider;


    @BeforeMethod
    public void setUp() {
        initMocks(this);
        roleProvider = new RoleProvider(aaiService, roleValidatorFactory, httpServletRequest -> 5,
            httpServletRequest -> createRoles(),
            categoryParameterService);

        when(categoryParameterService.getCategoryParameters(any()))
            .thenReturn(new CategoryParametersResponse(emptyMap()));
    }

    @Test
    public void shouldSplitRolesWhenDelimiterIsPresent() {
        String roles = "role_a___role_b";

        assertThat(roleProvider.splitRole(roles, "")).isEqualTo(new String[]{"role_a", "role_b"});
    }


    @Test
    public void shouldProperlyCreateRoleFromCorrectArray() throws RoleParsingException {
        setSubscribers();
        String[] roleParts = {SAMPLE_SUBSCRIBER, SAMPLE_SERVICE, SAMPLE_TENANT};

        Role role = roleProvider.createRoleFromStringArr(roleParts, SAMPLE_ROLE_PREFIX, emptyMap());

        assertThat(role.getEcompRole()).isEqualTo(EcompRole.READ);
        assertThat(role.getSubscriberId()).isEqualTo(SAMPLE_SUBSCRIBER_ID);
        assertThat(role.getTenant()).isEqualTo(SAMPLE_TENANT);
        assertThat(role.getServiceType()).isEqualTo(SAMPLE_SERVICE);
    }

    @Test
    public void shouldProperlyCreateRoleWhenTenantIsNotProvided() throws RoleParsingException {
        setSubscribers();

        String[] roleParts = {SAMPLE_SUBSCRIBER, SAMPLE_SERVICE};

        Role role = roleProvider.createRoleFromStringArr(roleParts, SAMPLE_ROLE_PREFIX, emptyMap());

        assertThat(role.getEcompRole()).isEqualTo(EcompRole.READ);
        assertThat(role.getSubscriberId()).isEqualTo(SAMPLE_SUBSCRIBER_ID);
        assertThat(role.getServiceType()).isEqualTo(SAMPLE_SERVICE);
        assertThat(role.getTenant()).isNullOrEmpty();
    }

    @Test(expectedExceptions = RoleParsingException.class)
    public void shouldRaiseExceptionWhenRolePartsAreIncomplete() throws RoleParsingException {
        setSubscribers();

        roleProvider.createRoleFromStringArr(new String[]{SAMPLE_SUBSCRIBER}, SAMPLE_ROLE_PREFIX, emptyMap());
    }

    @Test
    public void shouldProperlyRetrieveUserRolesWhenPermissionIsDifferentThanRead() {
        Role expectedRole = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER_ID, SAMPLE_SERVICE, SAMPLE_TENANT, owningEntityId());
        setSubscribers();

        List<Role> userRoles = roleProvider.getUserRoles(request);


        assertThat(userRoles.size()).isEqualTo(1);
        Role actualRole = userRoles.get(0);

        assertThat(actualRole.getTenant()).isEqualTo(expectedRole.getTenant());
        assertThat(actualRole.getSubscriberId()).isEqualTo(expectedRole.getSubscriberId());
        assertThat(actualRole.getServiceType()).isEqualTo(expectedRole.getServiceType());
    }

    @Test
    public void shouldReturnReadOnlyPermissionWhenRolesAreEmpty() {
        assertThat(roleProvider.userPermissionIsReadOnly(Lists.emptyList())).isTrue();
    }

    @Test
    public void shouldReturnNotReadOnlyPermissionWhenRolesArePresent() {
        assertThat(roleProvider.userPermissionIsReadOnly(Lists.list(new Role(
            EcompRole.READ, SAMPLE_SUBSCRIBER, SAMPLE_SERVICE, SAMPLE_TENANT, owningEntityId())))).isFalse();
    }

    @Test
    public void userShouldHavePermissionToReadLogsWhenServiceAndTenantAreCorrect() {
        Role withoutPermission = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER, SAMPLE_SERVICE, SAMPLE_TENANT, owningEntityId());
        Role withPermission = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER, SERVICE_TYPE_LOGS, TENANT_PERMITTED, owningEntityId());

        assertThat(roleProvider.userPermissionIsReadLogs(Lists.list(withoutPermission, withPermission))).isTrue();
    }

    @Test
    public void getUserRolesValidator_shouldReturnValidatorFromFactory() {
        RoleValidator expectedRoleValidator = new AlwaysValidRoleValidator();
        when(roleValidatorFactory.by(any())).thenReturn(expectedRoleValidator);

        RoleValidator result = roleProvider.getUserRolesValidator(request);

        assertThat(result).isEqualTo(expectedRoleValidator);
    }

    @DataProvider
    public static Object[][] owningEntityNameAndId() {
        return new Object[][] {
            {"owning entity name exist on the response, id is returned ", EXISTING_OWNING_ENTITY_NAME, EXISTING_OWNING_ENTITY_ID},
            {"owning entity name dont exist on the response, name is returned", NOT_EXISTING_OWNING_ENTITY_NAME, NOT_EXISTING_OWNING_ENTITY_NAME},
        };
    }

    @Test(dataProvider = "owningEntityNameAndId")
    public void translateOwningEntityNameToOwningEntityId_shouldTranslateNameToId(String description,
        String owningEntityName, String expectedId) {
        String owningEntityId = roleProvider.translateOwningEntityNameToOwningEntityId(owningEntityName,
            ImmutableMap.of(
                EXISTING_OWNING_ENTITY_NAME, EXISTING_OWNING_ENTITY_ID,
                "anyName", "anyId"
            ));

        Assert.assertEquals(owningEntityId, expectedId);
    }



    private String owningEntityId() {
        return EXISTING_OWNING_ENTITY_ID;
    }

    private void setSubscribers() {
        Subscriber subscriber = new Subscriber();
        subscriber.subscriberName = SAMPLE_SUBSCRIBER;
        subscriber.globalCustomerId = SAMPLE_SUBSCRIBER_ID;
        SubscriberList subscriberList = new SubscriberList(Lists.list(subscriber));
        when(aaiService.getFullSubscriberList()).thenReturn(subscriberListResponse);
        when(subscriberListResponse.getT()).thenReturn(subscriberList);
    }

    private Map<Long, org.onap.portalsdk.core.domain.Role> createRoles() {
        org.onap.portalsdk.core.domain.Role role1 = new org.onap.portalsdk.core.domain.Role();
        role1.setName("read___role2");
        org.onap.portalsdk.core.domain.Role role2 = new org.onap.portalsdk.core.domain.Role();
        role2.setName("sampleSubscriber___sampleService___sampleTenant");
        return ImmutableMap.of(1L, role1, 2L, role2);
    }

    @Test
    public void owningEntityNameToOwningEntityIdMapper_readsOwningEntityCorrectly() throws JsonProcessingException {

        final String categoryParametersResponse = ""
            + "{ "
            + " \"categoryParameters\": { "
            + " \"lineOfBusiness\": [ "
            + "      { \"id\": \"ONAP\", \"name\": \"ONAP\" }, "
            + "      { \"id\": \"zzz1\", \"name\": \"zzz1\" } "
            + "    ], "
            + " \"owningEntity\": [ "
            + "      { \"id\": \"aaa1\", \"name\": \"aaa1\" }, "
            + "      { \"id\": \"" + EXISTING_OWNING_ENTITY_ID + "\", \"name\": \"" + EXISTING_OWNING_ENTITY_NAME + "\" }, "
            + "      { \"id\": \"Melissa\", \"name\": \"Melissa\" }     ], "
            + " \"project\": [ "
            + "      { \"id\": \"WATKINS\", \"name\": \"WATKINS\" }, "
            + "      { \"id\": \"x1\", \"name\": \"x1\" }, "
            + "      { \"id\": \"yyy1\", \"name\": \"yyy1\" } "
            + "    ], "
            + " \"platform\": [ "
            + "      { \"id\": \"platform\", \"name\": \"platform\" }, "
            + "      { \"id\": \"xxx1\", \"name\": \"xxx1\" } "
            + "    ] "
            + "  } "
            + "}";

        CategoryParametersResponse categoryParameterResponse =
            new ObjectMapper().readValue(categoryParametersResponse, CategoryParametersResponse.class);

        when(categoryParameterService.getCategoryParameters(Family.PARAMETER_STANDARDIZATION))
            .thenReturn(categoryParameterResponse);

        org.hamcrest.MatcherAssert.assertThat(roleProvider.owningEntityNameToOwningEntityIdMapper(),
            jsonEquals(ImmutableMap.of(
                "aaa1", "aaa1",
                "Melissa", "Melissa",
                EXISTING_OWNING_ENTITY_NAME, EXISTING_OWNING_ENTITY_ID
            )));
    }
}