7b929729d8ba234d9314db03dbcec749a639f65f
[nonrtric/plt/sme.git] / capifcore / internal / invokermanagement / invokermanagement_test.go
1 // -
2 //
3 //      ========================LICENSE_START=================================
4 //      O-RAN-SC
5 //      %%
6 //      Copyright (C) 2022: Nordix Foundation
7 //      %%
8 //      Licensed under the Apache License, Version 2.0 (the "License");
9 //      you may not use this file except in compliance with the License.
10 //      You may obtain a copy of the License at
11 //
12 //           http://www.apache.org/licenses/LICENSE-2.0
13 //
14 //      Unless required by applicable law or agreed to in writing, software
15 //      distributed under the License is distributed on an "AS IS" BASIS,
16 //      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 //      See the License for the specific language governing permissions and
18 //      limitations under the License.
19 //      ========================LICENSE_END===================================
20 package invokermanagement
21
22 import (
23         "fmt"
24         "net/http"
25         "os"
26         "strings"
27         "testing"
28         "time"
29
30         "oransc.org/nonrtric/capifcore/internal/eventsapi"
31         "oransc.org/nonrtric/capifcore/internal/invokermanagementapi"
32         "oransc.org/nonrtric/capifcore/internal/keycloak"
33
34         "github.com/labstack/echo/v4"
35
36         "oransc.org/nonrtric/capifcore/internal/common29122"
37         "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
38
39         keycloackmocks "oransc.org/nonrtric/capifcore/internal/keycloak/mocks"
40         "oransc.org/nonrtric/capifcore/internal/publishservice"
41         publishmocks "oransc.org/nonrtric/capifcore/internal/publishservice/mocks"
42
43         "github.com/deepmap/oapi-codegen/pkg/middleware"
44         "github.com/deepmap/oapi-codegen/pkg/testutil"
45         echomiddleware "github.com/labstack/echo/v4/middleware"
46         "github.com/stretchr/testify/assert"
47         "github.com/stretchr/testify/mock"
48 )
49
50 func TestOnboardInvoker(t *testing.T) {
51         aefProfiles := []publishserviceapi.AefProfile{
52                 getAefProfile("aefId"),
53         }
54         apiId := "apiId"
55         publishedServices := []publishserviceapi.ServiceAPIDescription{
56                 {
57                         ApiId:       &apiId,
58                         AefProfiles: &aefProfiles,
59                 },
60         }
61
62         invokerInfo := "invoker a"
63         wantedInvokerSecret := "onboarding_secret_" + strings.Replace(invokerInfo, " ", "_", 1)
64         var client keycloak.Client
65         client.Secret = &wantedInvokerSecret
66         publishRegisterMock := publishmocks.PublishRegister{}
67         publishRegisterMock.On("GetAllPublishedServices").Return(publishedServices)
68
69         accessMgmMock := keycloackmocks.AccessManagement{}
70         accessMgmMock.On("AddClient", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(nil)
71         accessMgmMock.On("GetClientRepresentation", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(&client, nil)
72
73         invokerUnderTest, eventChannel, requestHandler := getEcho(&publishRegisterMock, &accessMgmMock)
74
75         newInvoker := getInvoker(invokerInfo)
76
77         // Onboard a valid invoker
78         result := testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(newInvoker).Go(t, requestHandler)
79
80         assert.Equal(t, http.StatusCreated, result.Code())
81         var resultInvoker invokermanagementapi.APIInvokerEnrolmentDetails
82         err := result.UnmarshalBodyToObject(&resultInvoker)
83         assert.NoError(t, err, "error unmarshaling response")
84         wantedInvokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
85         assert.Equal(t, wantedInvokerId, *resultInvoker.ApiInvokerId)
86         assert.Equal(t, newInvoker.NotificationDestination, resultInvoker.NotificationDestination)
87         assert.Equal(t, newInvoker.OnboardingInformation.ApiInvokerPublicKey, resultInvoker.OnboardingInformation.ApiInvokerPublicKey)
88
89         assert.Equal(t, wantedInvokerSecret, *resultInvoker.OnboardingInformation.OnboardingSecret)
90         assert.Equal(t, "http://example.com/onboardedInvokers/"+*resultInvoker.ApiInvokerId, result.Recorder.Header().Get(echo.HeaderLocation))
91         assert.True(t, invokerUnderTest.IsInvokerRegistered(wantedInvokerId))
92         assert.True(t, invokerUnderTest.VerifyInvokerSecret(wantedInvokerId, wantedInvokerSecret))
93         publishRegisterMock.AssertCalled(t, "GetAllPublishedServices")
94         assert.Equal(t, invokermanagementapi.APIList(publishedServices), *resultInvoker.ApiList)
95         if invokerEvent, timeout := waitForEvent(eventChannel, 1*time.Second); timeout {
96                 assert.Fail(t, "No event sent")
97         } else {
98                 assert.Equal(t, *resultInvoker.ApiInvokerId, (*invokerEvent.EventDetail.ApiInvokerIds)[0])
99                 assert.Equal(t, eventsapi.CAPIFEventAPIINVOKERONBOARDED, invokerEvent.Events)
100         }
101
102         // Onboarding the same invoker should result in Forbidden
103         result = testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(newInvoker).Go(t, requestHandler)
104
105         assert.Equal(t, http.StatusForbidden, result.Code())
106         var problemDetails common29122.ProblemDetails
107         err = result.UnmarshalBodyToObject(&problemDetails)
108         assert.NoError(t, err, "error unmarshaling response")
109         assert.Equal(t, http.StatusForbidden, *problemDetails.Status)
110         assert.Contains(t, *problemDetails.Cause, "already onboarded")
111
112         // Onboard an invoker missing required NotificationDestination, should get 400 with problem details
113         invalidInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
114                 OnboardingInformation: invokermanagementapi.OnboardingInformation{
115                         ApiInvokerPublicKey: "newKey",
116                 },
117         }
118         result = testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(invalidInvoker).Go(t, requestHandler)
119
120         assert.Equal(t, http.StatusBadRequest, result.Code())
121         err = result.UnmarshalBodyToObject(&problemDetails)
122         assert.NoError(t, err, "error unmarshaling response")
123         assert.Equal(t, http.StatusBadRequest, *problemDetails.Status)
124         assert.Contains(t, *problemDetails.Cause, "missing")
125         assert.Contains(t, *problemDetails.Cause, "NotificationDestination")
126
127         // Onboard an invoker missing required OnboardingInformation.ApiInvokerPublicKey, should get 400 with problem details
128         invalidInvoker = invokermanagementapi.APIInvokerEnrolmentDetails{
129                 NotificationDestination: "http://golang.cafe/",
130         }
131
132         result = testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(invalidInvoker).Go(t, requestHandler)
133
134         assert.Equal(t, http.StatusBadRequest, result.Code())
135         err = result.UnmarshalBodyToObject(&problemDetails)
136         assert.NoError(t, err, "error unmarshaling response")
137         assert.Equal(t, http.StatusBadRequest, *problemDetails.Status)
138         assert.Contains(t, *problemDetails.Cause, "missing")
139         assert.Contains(t, *problemDetails.Cause, "OnboardingInformation.ApiInvokerPublicKey")
140 }
141
142 func TestDeleteInvoker(t *testing.T) {
143         invokerUnderTest, eventChannel, requestHandler := getEcho(nil, nil)
144
145         invokerId := "invokerId"
146         newInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
147                 ApiInvokerId:            &invokerId,
148                 NotificationDestination: "url",
149                 OnboardingInformation: invokermanagementapi.OnboardingInformation{
150                         ApiInvokerPublicKey: "key",
151                 },
152         }
153         invokerUnderTest.onboardedInvokers[invokerId] = newInvoker
154         assert.True(t, invokerUnderTest.IsInvokerRegistered(invokerId))
155
156         // Delete the invoker
157         result := testutil.NewRequest().Delete("/onboardedInvokers/"+invokerId).Go(t, requestHandler)
158
159         assert.Equal(t, http.StatusNoContent, result.Code())
160         assert.False(t, invokerUnderTest.IsInvokerRegistered(invokerId))
161         if invokerEvent, timeout := waitForEvent(eventChannel, 1*time.Second); timeout {
162                 assert.Fail(t, "No event sent")
163         } else {
164                 assert.Equal(t, invokerId, (*invokerEvent.EventDetail.ApiInvokerIds)[0])
165                 assert.Equal(t, eventsapi.CAPIFEventAPIINVOKEROFFBOARDED, invokerEvent.Events)
166         }
167 }
168
169 func TestUpdateInvoker(t *testing.T) {
170         publishRegisterMock := publishmocks.PublishRegister{}
171         publishRegisterMock.On("GetAllPublishedServices").Return([]publishserviceapi.ServiceAPIDescription{})
172         serviceUnderTest, _, requestHandler := getEcho(&publishRegisterMock, nil)
173
174         invokerId := "invokerId"
175         invoker := invokermanagementapi.APIInvokerEnrolmentDetails{
176                 ApiInvokerId:            &invokerId,
177                 NotificationDestination: "http://golang.cafe/",
178                 OnboardingInformation: invokermanagementapi.OnboardingInformation{
179                         ApiInvokerPublicKey: "key",
180                 },
181         }
182         serviceUnderTest.onboardedInvokers[invokerId] = invoker
183
184         // Update the invoker with valid invoker, should return 200 with updated invoker details
185         newNotifURL := "http://golang.org/"
186         invoker.NotificationDestination = common29122.Uri(newNotifURL)
187         newPublicKey := "newPublicKey"
188         invoker.OnboardingInformation.ApiInvokerPublicKey = newPublicKey
189         result := testutil.NewRequest().Put("/onboardedInvokers/"+invokerId).WithJsonBody(invoker).Go(t, requestHandler)
190
191         var resultInvoker invokermanagementapi.APIInvokerEnrolmentDetails
192         assert.Equal(t, http.StatusOK, result.Code())
193         err := result.UnmarshalBodyToObject(&resultInvoker)
194         assert.NoError(t, err, "error unmarshaling response")
195         assert.Equal(t, invokerId, *resultInvoker.ApiInvokerId)
196         assert.Equal(t, newNotifURL, string(resultInvoker.NotificationDestination))
197         assert.Equal(t, newPublicKey, resultInvoker.OnboardingInformation.ApiInvokerPublicKey)
198
199         // Update with an invoker missing required NotificationDestination, should get 400 with problem details
200         validOnboardingInfo := invokermanagementapi.OnboardingInformation{
201                 ApiInvokerPublicKey: "key",
202         }
203         invalidInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
204                 ApiInvokerId:          &invokerId,
205                 OnboardingInformation: validOnboardingInfo,
206         }
207         result = testutil.NewRequest().Put("/onboardedInvokers/"+invokerId).WithJsonBody(invalidInvoker).Go(t, requestHandler)
208
209         assert.Equal(t, http.StatusBadRequest, result.Code())
210         var problemDetails common29122.ProblemDetails
211         err = result.UnmarshalBodyToObject(&problemDetails)
212         assert.NoError(t, err, "error unmarshaling response")
213         assert.Equal(t, http.StatusBadRequest, *problemDetails.Status)
214         assert.Contains(t, *problemDetails.Cause, "missing")
215         assert.Contains(t, *problemDetails.Cause, "NotificationDestination")
216
217         // Update with an invoker missing required OnboardingInformation.ApiInvokerPublicKey, should get 400 with problem details
218         invalidInvoker.NotificationDestination = "http://golang.org/"
219         invalidInvoker.OnboardingInformation = invokermanagementapi.OnboardingInformation{}
220         result = testutil.NewRequest().Put("/onboardedInvokers/"+invokerId).WithJsonBody(invalidInvoker).Go(t, requestHandler)
221
222         assert.Equal(t, http.StatusBadRequest, result.Code())
223         err = result.UnmarshalBodyToObject(&problemDetails)
224         assert.NoError(t, err, "error unmarshaling response")
225         assert.Equal(t, http.StatusBadRequest, *problemDetails.Status)
226         assert.Contains(t, *problemDetails.Cause, "missing")
227         assert.Contains(t, *problemDetails.Cause, "OnboardingInformation.ApiInvokerPublicKey")
228
229         // Update with an invoker with other ApiInvokerId than the one provided in the URL, should get 400 with problem details
230         invalidId := "1"
231         invalidInvoker.ApiInvokerId = &invalidId
232         invalidInvoker.OnboardingInformation = validOnboardingInfo
233         result = testutil.NewRequest().Put("/onboardedInvokers/"+invokerId).WithJsonBody(invalidInvoker).Go(t, requestHandler)
234
235         assert.Equal(t, http.StatusBadRequest, result.Code())
236         err = result.UnmarshalBodyToObject(&problemDetails)
237         assert.NoError(t, err, "error unmarshaling response")
238         assert.Equal(t, http.StatusBadRequest, *problemDetails.Status)
239         assert.Contains(t, *problemDetails.Cause, "not matching")
240         assert.Contains(t, *problemDetails.Cause, "ApiInvokerId")
241
242         // Update an invoker that has not been onboarded, should get 404 with problem details
243         missingId := "1"
244         invoker.ApiInvokerId = &missingId
245         result = testutil.NewRequest().Put("/onboardedInvokers/"+missingId).WithJsonBody(invoker).Go(t, requestHandler)
246
247         assert.Equal(t, http.StatusNotFound, result.Code())
248         err = result.UnmarshalBodyToObject(&problemDetails)
249         assert.NoError(t, err, "error unmarshaling response")
250         assert.Equal(t, http.StatusNotFound, *problemDetails.Status)
251         assert.Contains(t, *problemDetails.Cause, "not been onboarded")
252         assert.Contains(t, *problemDetails.Cause, "invoker")
253 }
254
255 func TestGetInvokerApiList(t *testing.T) {
256         aefProfiles1 := []publishserviceapi.AefProfile{
257                 getAefProfile("aefId"),
258         }
259         apiId := "apiId"
260         apiList := []publishserviceapi.ServiceAPIDescription{
261                 {
262                         ApiId:       &apiId,
263                         AefProfiles: &aefProfiles1,
264                 },
265         }
266         aefProfiles2 := []publishserviceapi.AefProfile{
267                 getAefProfile("aefId2"),
268         }
269         apiId2 := "apiId2"
270         apiList = append(apiList, publishserviceapi.ServiceAPIDescription{
271                 ApiId:       &apiId2,
272                 AefProfiles: &aefProfiles2,
273         })
274         publishRegisterMock := publishmocks.PublishRegister{}
275         publishRegisterMock.On("GetAllPublishedServices").Return(apiList)
276         invokerUnderTest, _, _ := getEcho(&publishRegisterMock, nil)
277
278         invokerInfo := "invoker a"
279         newInvoker := getInvoker(invokerInfo)
280         invokerAId := "api_invoker_id_" + strings.ReplaceAll(invokerInfo, " ", "_")
281         newInvoker.ApiInvokerId = &invokerAId
282         invokerUnderTest.onboardedInvokers[invokerAId] = newInvoker
283         invokerInfo = "invoker b"
284         newInvoker = getInvoker(invokerInfo)
285         invokerId := "api_invoker_id_" + strings.ReplaceAll(invokerInfo, " ", "_")
286         newInvoker.ApiInvokerId = &invokerId
287         invokerUnderTest.onboardedInvokers[invokerId] = newInvoker
288
289         wantedApiList := invokerUnderTest.GetInvokerApiList(invokerAId)
290         assert.NotNil(t, wantedApiList)
291         assert.Len(t, *wantedApiList, 2)
292         assert.Equal(t, apiId, *(*wantedApiList)[0].ApiId)
293 }
294
295 func getEcho(publishRegister publishservice.PublishRegister, keycloakMgm keycloak.AccessManagement) (*InvokerManager, chan eventsapi.EventNotification, *echo.Echo) {
296         swagger, err := invokermanagementapi.GetSwagger()
297         if err != nil {
298                 fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err)
299                 os.Exit(1)
300         }
301
302         swagger.Servers = nil
303
304         eventChannel := make(chan eventsapi.EventNotification)
305         im := NewInvokerManager(publishRegister, keycloakMgm, eventChannel)
306
307         e := echo.New()
308         e.Use(echomiddleware.Logger())
309         e.Use(middleware.OapiRequestValidator(swagger))
310
311         invokermanagementapi.RegisterHandlers(e, im)
312         return im, eventChannel, e
313 }
314
315 func getAefProfile(aefId string) publishserviceapi.AefProfile {
316         return publishserviceapi.AefProfile{
317                 AefId: aefId,
318                 Versions: []publishserviceapi.Version{
319                         {
320                                 Resources: &[]publishserviceapi.Resource{
321                                         {
322                                                 CommType: "REQUEST_RESPONSE",
323                                         },
324                                 },
325                         },
326                 },
327         }
328 }
329
330 func getInvoker(invokerInfo string) invokermanagementapi.APIInvokerEnrolmentDetails {
331         newInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
332                 ApiInvokerInformation:   &invokerInfo,
333                 NotificationDestination: "http://golang.cafe/",
334                 OnboardingInformation: invokermanagementapi.OnboardingInformation{
335                         ApiInvokerPublicKey: "key",
336                 },
337                 ApiList: nil,
338         }
339         return newInvoker
340 }
341
342 // waitForEvent waits for the channel to receive an event for the specified max timeout.
343 // Returns true if waiting timed out.
344 func waitForEvent(ch chan eventsapi.EventNotification, timeout time.Duration) (*eventsapi.EventNotification, bool) {
345         select {
346         case event := <-ch:
347                 return &event, false // completed normally
348         case <-time.After(timeout):
349                 return nil, true // timed out
350         }
351 }