Refactor invoker management
[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
33         "github.com/labstack/echo/v4"
34
35         "oransc.org/nonrtric/capifcore/internal/common29122"
36         "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
37
38         "oransc.org/nonrtric/capifcore/internal/publishservice"
39         publishmocks "oransc.org/nonrtric/capifcore/internal/publishservice/mocks"
40
41         "github.com/deepmap/oapi-codegen/pkg/middleware"
42         "github.com/deepmap/oapi-codegen/pkg/testutil"
43         echomiddleware "github.com/labstack/echo/v4/middleware"
44         "github.com/stretchr/testify/assert"
45 )
46
47 func TestOnboardInvoker(t *testing.T) {
48         aefProfiles := []publishserviceapi.AefProfile{
49                 getAefProfile("aefId"),
50         }
51         apiId := "apiId"
52         publishedServices := []publishserviceapi.ServiceAPIDescription{
53                 {
54                         ApiId:       &apiId,
55                         AefProfiles: &aefProfiles,
56                 },
57         }
58         publishRegisterMock := publishmocks.PublishRegister{}
59         publishRegisterMock.On("GetAllPublishedServices").Return(publishedServices)
60         invokerUnderTest, eventChannel, requestHandler := getEcho(&publishRegisterMock)
61
62         invokerInfo := "invoker a"
63         newInvoker := getInvoker(invokerInfo)
64
65         // Onboard a valid invoker
66         result := testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(newInvoker).Go(t, requestHandler)
67
68         assert.Equal(t, http.StatusCreated, result.Code())
69         var resultInvoker invokermanagementapi.APIInvokerEnrolmentDetails
70         err := result.UnmarshalBodyToObject(&resultInvoker)
71         assert.NoError(t, err, "error unmarshaling response")
72         wantedInvokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
73         assert.Equal(t, wantedInvokerId, *resultInvoker.ApiInvokerId)
74         assert.Equal(t, newInvoker.NotificationDestination, resultInvoker.NotificationDestination)
75         assert.Equal(t, newInvoker.OnboardingInformation.ApiInvokerPublicKey, resultInvoker.OnboardingInformation.ApiInvokerPublicKey)
76         wantedInvokerSecret := "onboarding_secret_" + strings.Replace(invokerInfo, " ", "_", 1)
77         assert.Equal(t, wantedInvokerSecret, *resultInvoker.OnboardingInformation.OnboardingSecret)
78         assert.Equal(t, "http://example.com/onboardedInvokers/"+*resultInvoker.ApiInvokerId, result.Recorder.Header().Get(echo.HeaderLocation))
79         assert.True(t, invokerUnderTest.IsInvokerRegistered(wantedInvokerId))
80         assert.True(t, invokerUnderTest.VerifyInvokerSecret(wantedInvokerId, wantedInvokerSecret))
81         publishRegisterMock.AssertCalled(t, "GetAllPublishedServices")
82         assert.Equal(t, invokermanagementapi.APIList(publishedServices), *resultInvoker.ApiList)
83         if invokerEvent, timeout := waitForEvent(eventChannel, 1*time.Second); timeout {
84                 assert.Fail(t, "No event sent")
85         } else {
86                 assert.Equal(t, *resultInvoker.ApiInvokerId, (*invokerEvent.EventDetail.ApiInvokerIds)[0])
87                 assert.Equal(t, eventsapi.CAPIFEventAPIINVOKERONBOARDED, invokerEvent.Events)
88         }
89
90         // Onboard an invoker missing required NotificationDestination, should get 400 with problem details
91         invalidInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
92                 OnboardingInformation: invokermanagementapi.OnboardingInformation{
93                         ApiInvokerPublicKey: "key",
94                 },
95         }
96         result = testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(invalidInvoker).Go(t, requestHandler)
97
98         assert.Equal(t, http.StatusBadRequest, result.Code())
99         var problemDetails common29122.ProblemDetails
100         err = result.UnmarshalBodyToObject(&problemDetails)
101         assert.NoError(t, err, "error unmarshaling response")
102         badRequest := http.StatusBadRequest
103         assert.Equal(t, &badRequest, problemDetails.Status)
104         assert.Contains(t, *problemDetails.Cause, "missing")
105         assert.Contains(t, *problemDetails.Cause, "NotificationDestination")
106
107         // Onboard an invoker missing required OnboardingInformation.ApiInvokerPublicKey, should get 400 with problem details
108         invalidInvoker = invokermanagementapi.APIInvokerEnrolmentDetails{
109                 NotificationDestination: "url",
110         }
111
112         result = testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(invalidInvoker).Go(t, requestHandler)
113
114         assert.Equal(t, http.StatusBadRequest, result.Code())
115         err = result.UnmarshalBodyToObject(&problemDetails)
116         assert.NoError(t, err, "error unmarshaling response")
117         assert.Equal(t, &badRequest, problemDetails.Status)
118         assert.Contains(t, *problemDetails.Cause, "missing")
119         assert.Contains(t, *problemDetails.Cause, "OnboardingInformation.ApiInvokerPublicKey")
120 }
121
122 func TestDeleteInvoker(t *testing.T) {
123         invokerUnderTest, eventChannel, requestHandler := getEcho(nil)
124
125         invokerId := "invokerId"
126         newInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
127                 ApiInvokerId:            &invokerId,
128                 NotificationDestination: "url",
129                 OnboardingInformation: invokermanagementapi.OnboardingInformation{
130                         ApiInvokerPublicKey: "key",
131                 },
132         }
133         invokerUnderTest.onboardedInvokers[invokerId] = newInvoker
134         assert.True(t, invokerUnderTest.IsInvokerRegistered(invokerId))
135
136         // Delete the invoker
137         result := testutil.NewRequest().Delete("/onboardedInvokers/"+invokerId).Go(t, requestHandler)
138
139         assert.Equal(t, http.StatusNoContent, result.Code())
140         assert.False(t, invokerUnderTest.IsInvokerRegistered(invokerId))
141         if invokerEvent, timeout := waitForEvent(eventChannel, 1*time.Second); timeout {
142                 assert.Fail(t, "No event sent")
143         } else {
144                 assert.Equal(t, invokerId, (*invokerEvent.EventDetail.ApiInvokerIds)[0])
145                 assert.Equal(t, eventsapi.CAPIFEventAPIINVOKEROFFBOARDED, invokerEvent.Events)
146         }
147 }
148
149 func TestUpdateInvoker(t *testing.T) {
150         publishRegisterMock := publishmocks.PublishRegister{}
151         publishRegisterMock.On("GetAllPublishedServices").Return([]publishserviceapi.ServiceAPIDescription{})
152         serviceUnderTest, _, requestHandler := getEcho(&publishRegisterMock)
153
154         invokerId := "invokerId"
155         invoker := invokermanagementapi.APIInvokerEnrolmentDetails{
156                 ApiInvokerId:            &invokerId,
157                 NotificationDestination: "url",
158                 OnboardingInformation: invokermanagementapi.OnboardingInformation{
159                         ApiInvokerPublicKey: "key",
160                 },
161         }
162         serviceUnderTest.onboardedInvokers[invokerId] = invoker
163
164         // Update the invoker with valid invoker, should return 200 with updated invoker details
165         newNotifURL := "newUrl"
166         invoker.NotificationDestination = common29122.Uri(newNotifURL)
167         newPublicKey := "newPublicKey"
168         invoker.OnboardingInformation.ApiInvokerPublicKey = newPublicKey
169         result := testutil.NewRequest().Put("/onboardedInvokers/"+invokerId).WithJsonBody(invoker).Go(t, requestHandler)
170
171         var resultInvoker invokermanagementapi.APIInvokerEnrolmentDetails
172         assert.Equal(t, http.StatusOK, result.Code())
173         err := result.UnmarshalBodyToObject(&resultInvoker)
174         assert.NoError(t, err, "error unmarshaling response")
175         assert.Equal(t, invokerId, *resultInvoker.ApiInvokerId)
176         assert.Equal(t, newNotifURL, string(resultInvoker.NotificationDestination))
177         assert.Equal(t, newPublicKey, resultInvoker.OnboardingInformation.ApiInvokerPublicKey)
178
179         // Update with an invoker missing required NotificationDestination, should get 400 with problem details
180         validOnboardingInfo := invokermanagementapi.OnboardingInformation{
181                 ApiInvokerPublicKey: "key",
182         }
183         invalidInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
184                 ApiInvokerId:          &invokerId,
185                 OnboardingInformation: validOnboardingInfo,
186         }
187         result = testutil.NewRequest().Put("/onboardedInvokers/"+invokerId).WithJsonBody(invalidInvoker).Go(t, requestHandler)
188
189         assert.Equal(t, http.StatusBadRequest, result.Code())
190         var problemDetails common29122.ProblemDetails
191         err = result.UnmarshalBodyToObject(&problemDetails)
192         assert.NoError(t, err, "error unmarshaling response")
193         badRequest := http.StatusBadRequest
194         assert.Equal(t, &badRequest, problemDetails.Status)
195         assert.Contains(t, *problemDetails.Cause, "missing")
196         assert.Contains(t, *problemDetails.Cause, "NotificationDestination")
197
198         // Update with an invoker missing required OnboardingInformation.ApiInvokerPublicKey, should get 400 with problem details
199         invalidInvoker.NotificationDestination = "url"
200         invalidInvoker.OnboardingInformation = invokermanagementapi.OnboardingInformation{}
201         result = testutil.NewRequest().Put("/onboardedInvokers/"+invokerId).WithJsonBody(invalidInvoker).Go(t, requestHandler)
202
203         assert.Equal(t, http.StatusBadRequest, result.Code())
204         err = result.UnmarshalBodyToObject(&problemDetails)
205         assert.NoError(t, err, "error unmarshaling response")
206         assert.Equal(t, &badRequest, problemDetails.Status)
207         assert.Contains(t, *problemDetails.Cause, "missing")
208         assert.Contains(t, *problemDetails.Cause, "OnboardingInformation.ApiInvokerPublicKey")
209
210         // Update with an invoker with other ApiInvokerId than the one provided in the URL, should get 400 with problem details
211         invalidId := "1"
212         invalidInvoker.ApiInvokerId = &invalidId
213         invalidInvoker.OnboardingInformation = validOnboardingInfo
214         result = testutil.NewRequest().Put("/onboardedInvokers/"+invokerId).WithJsonBody(invalidInvoker).Go(t, requestHandler)
215
216         assert.Equal(t, http.StatusBadRequest, result.Code())
217         err = result.UnmarshalBodyToObject(&problemDetails)
218         assert.NoError(t, err, "error unmarshaling response")
219         assert.Equal(t, &badRequest, problemDetails.Status)
220         assert.Contains(t, *problemDetails.Cause, "not matching")
221         assert.Contains(t, *problemDetails.Cause, "ApiInvokerId")
222
223         // Update an invoker that has not been onboarded, should get 404 with problem details
224         missingId := "1"
225         invoker.ApiInvokerId = &missingId
226         result = testutil.NewRequest().Put("/onboardedInvokers/"+missingId).WithJsonBody(invoker).Go(t, requestHandler)
227
228         assert.Equal(t, http.StatusNotFound, result.Code())
229         err = result.UnmarshalBodyToObject(&problemDetails)
230         assert.NoError(t, err, "error unmarshaling response")
231         notFound := http.StatusNotFound
232         assert.Equal(t, &notFound, problemDetails.Status)
233         assert.Contains(t, *problemDetails.Cause, "not been onboarded")
234         assert.Contains(t, *problemDetails.Cause, "invoker")
235 }
236
237 func TestGetInvokerApiList(t *testing.T) {
238         aefProfiles1 := []publishserviceapi.AefProfile{
239                 getAefProfile("aefId"),
240         }
241         apiId := "apiId"
242         apiList := []publishserviceapi.ServiceAPIDescription{
243                 {
244                         ApiId:       &apiId,
245                         AefProfiles: &aefProfiles1,
246                 },
247         }
248         aefProfiles2 := []publishserviceapi.AefProfile{
249                 getAefProfile("aefId2"),
250         }
251         apiId2 := "apiId2"
252         apiList = append(apiList, publishserviceapi.ServiceAPIDescription{
253                 ApiId:       &apiId2,
254                 AefProfiles: &aefProfiles2,
255         })
256         publishRegisterMock := publishmocks.PublishRegister{}
257         publishRegisterMock.On("GetAllPublishedServices").Return(apiList)
258         invokerUnderTest, _, _ := getEcho(&publishRegisterMock)
259
260         invokerInfo := "invoker a"
261         newInvoker := getInvoker(invokerInfo)
262         invokerAId := "api_invoker_id_" + strings.ReplaceAll(invokerInfo, " ", "_")
263         newInvoker.ApiInvokerId = &invokerAId
264         invokerUnderTest.onboardedInvokers[invokerAId] = newInvoker
265         invokerInfo = "invoker b"
266         newInvoker = getInvoker(invokerInfo)
267         invokerId := "api_invoker_id_" + strings.ReplaceAll(invokerInfo, " ", "_")
268         newInvoker.ApiInvokerId = &invokerId
269         invokerUnderTest.onboardedInvokers[invokerId] = newInvoker
270
271         wantedApiList := invokerUnderTest.GetInvokerApiList(invokerAId)
272         assert.NotNil(t, wantedApiList)
273         assert.Len(t, *wantedApiList, 2)
274         assert.Equal(t, apiId, *(*wantedApiList)[0].ApiId)
275 }
276
277 func getEcho(publishRegister publishservice.PublishRegister) (*InvokerManager, chan eventsapi.EventNotification, *echo.Echo) {
278         swagger, err := invokermanagementapi.GetSwagger()
279         if err != nil {
280                 fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err)
281                 os.Exit(1)
282         }
283
284         swagger.Servers = nil
285
286         eventChannel := make(chan eventsapi.EventNotification)
287         im := NewInvokerManager(publishRegister, eventChannel)
288
289         e := echo.New()
290         e.Use(echomiddleware.Logger())
291         e.Use(middleware.OapiRequestValidator(swagger))
292
293         invokermanagementapi.RegisterHandlers(e, im)
294         return im, eventChannel, e
295 }
296
297 func getAefProfile(aefId string) publishserviceapi.AefProfile {
298         return publishserviceapi.AefProfile{
299                 AefId: aefId,
300                 Versions: []publishserviceapi.Version{
301                         {
302                                 Resources: &[]publishserviceapi.Resource{
303                                         {
304                                                 CommType: "REQUEST_RESPONSE",
305                                         },
306                                 },
307                         },
308                 },
309         }
310 }
311
312 func getInvoker(invokerInfo string) invokermanagementapi.APIInvokerEnrolmentDetails {
313         newInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
314                 ApiInvokerInformation:   &invokerInfo,
315                 NotificationDestination: "url",
316                 OnboardingInformation: invokermanagementapi.OnboardingInformation{
317                         ApiInvokerPublicKey: "key",
318                 },
319                 ApiList: nil,
320         }
321         return newInvoker
322 }
323
324 // waitForEvent waits for the channel to receive an event for the specified max timeout.
325 // Returns true if waiting timed out.
326 func waitForEvent(ch chan eventsapi.EventNotification, timeout time.Duration) (*eventsapi.EventNotification, bool) {
327         select {
328         case event := <-ch:
329                 return &event, false // completed normally
330         case <-time.After(timeout):
331                 return nil, true // timed out
332         }
333 }