3 // ========================LICENSE_START=================================
6 // Copyright (C) 2022: Nordix Foundation
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
12 // http://www.apache.org/licenses/LICENSE-2.0
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
30 "oransc.org/nonrtric/capifcore/internal/eventsapi"
31 "oransc.org/nonrtric/capifcore/internal/invokermanagementapi"
32 "oransc.org/nonrtric/capifcore/internal/keycloak"
34 "github.com/labstack/echo/v4"
36 "oransc.org/nonrtric/capifcore/internal/common29122"
37 "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
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"
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"
50 func TestOnboardInvoker(t *testing.T) {
51 aefProfiles := []publishserviceapi.AefProfile{
52 getAefProfile("aefId"),
55 publishedServices := []publishserviceapi.ServiceAPIDescription{
58 AefProfiles: &aefProfiles,
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)
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)
73 invokerUnderTest, eventChannel, requestHandler := getEcho(&publishRegisterMock, &accessMgmMock)
75 newInvoker := getInvoker(invokerInfo)
77 // Onboard a valid invoker
78 result := testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(newInvoker).Go(t, requestHandler)
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)
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")
98 assert.Equal(t, *resultInvoker.ApiInvokerId, (*invokerEvent.EventDetail.ApiInvokerIds)[0])
99 assert.Equal(t, eventsapi.CAPIFEventAPIINVOKERONBOARDED, invokerEvent.Events)
102 // Onboarding the same invoker should result in Forbidden
103 result = testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(newInvoker).Go(t, requestHandler)
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")
112 // Onboard an invoker missing required NotificationDestination, should get 400 with problem details
113 invalidInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
114 OnboardingInformation: invokermanagementapi.OnboardingInformation{
115 ApiInvokerPublicKey: "newKey",
118 result = testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(invalidInvoker).Go(t, requestHandler)
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")
127 // Onboard an invoker missing required OnboardingInformation.ApiInvokerPublicKey, should get 400 with problem details
128 invalidInvoker = invokermanagementapi.APIInvokerEnrolmentDetails{
129 NotificationDestination: "http://golang.cafe/",
132 result = testutil.NewRequest().Post("/onboardedInvokers").WithJsonBody(invalidInvoker).Go(t, requestHandler)
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")
142 func TestDeleteInvoker(t *testing.T) {
143 invokerUnderTest, eventChannel, requestHandler := getEcho(nil, nil)
145 invokerId := "invokerId"
146 newInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
147 ApiInvokerId: &invokerId,
148 NotificationDestination: "url",
149 OnboardingInformation: invokermanagementapi.OnboardingInformation{
150 ApiInvokerPublicKey: "key",
153 invokerUnderTest.onboardedInvokers[invokerId] = newInvoker
154 assert.True(t, invokerUnderTest.IsInvokerRegistered(invokerId))
156 // Delete the invoker
157 result := testutil.NewRequest().Delete("/onboardedInvokers/"+invokerId).Go(t, requestHandler)
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")
164 assert.Equal(t, invokerId, (*invokerEvent.EventDetail.ApiInvokerIds)[0])
165 assert.Equal(t, eventsapi.CAPIFEventAPIINVOKEROFFBOARDED, invokerEvent.Events)
169 func TestUpdateInvoker(t *testing.T) {
170 publishRegisterMock := publishmocks.PublishRegister{}
171 publishRegisterMock.On("GetAllPublishedServices").Return([]publishserviceapi.ServiceAPIDescription{})
172 serviceUnderTest, _, requestHandler := getEcho(&publishRegisterMock, nil)
174 invokerId := "invokerId"
175 invoker := invokermanagementapi.APIInvokerEnrolmentDetails{
176 ApiInvokerId: &invokerId,
177 NotificationDestination: "http://golang.cafe/",
178 OnboardingInformation: invokermanagementapi.OnboardingInformation{
179 ApiInvokerPublicKey: "key",
182 serviceUnderTest.onboardedInvokers[invokerId] = invoker
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)
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)
199 // Update with an invoker missing required NotificationDestination, should get 400 with problem details
200 validOnboardingInfo := invokermanagementapi.OnboardingInformation{
201 ApiInvokerPublicKey: "key",
203 invalidInvoker := invokermanagementapi.APIInvokerEnrolmentDetails{
204 ApiInvokerId: &invokerId,
205 OnboardingInformation: validOnboardingInfo,
207 result = testutil.NewRequest().Put("/onboardedInvokers/"+invokerId).WithJsonBody(invalidInvoker).Go(t, requestHandler)
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")
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)
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")
229 // Update with an invoker with other ApiInvokerId than the one provided in the URL, should get 400 with problem details
231 invalidInvoker.ApiInvokerId = &invalidId
232 invalidInvoker.OnboardingInformation = validOnboardingInfo
233 result = testutil.NewRequest().Put("/onboardedInvokers/"+invokerId).WithJsonBody(invalidInvoker).Go(t, requestHandler)
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")
242 // Update an invoker that has not been onboarded, should get 404 with problem details
244 invoker.ApiInvokerId = &missingId
245 result = testutil.NewRequest().Put("/onboardedInvokers/"+missingId).WithJsonBody(invoker).Go(t, requestHandler)
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")
255 func TestGetInvokerApiList(t *testing.T) {
256 aefProfiles1 := []publishserviceapi.AefProfile{
257 getAefProfile("aefId"),
260 apiList := []publishserviceapi.ServiceAPIDescription{
263 AefProfiles: &aefProfiles1,
266 aefProfiles2 := []publishserviceapi.AefProfile{
267 getAefProfile("aefId2"),
270 apiList = append(apiList, publishserviceapi.ServiceAPIDescription{
272 AefProfiles: &aefProfiles2,
274 publishRegisterMock := publishmocks.PublishRegister{}
275 publishRegisterMock.On("GetAllPublishedServices").Return(apiList)
276 invokerUnderTest, _, _ := getEcho(&publishRegisterMock, nil)
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
289 wantedApiList := invokerUnderTest.GetInvokerApiList(invokerAId)
290 assert.NotNil(t, wantedApiList)
291 assert.Len(t, *wantedApiList, 2)
292 assert.Equal(t, apiId, *(*wantedApiList)[0].ApiId)
295 func getEcho(publishRegister publishservice.PublishRegister, keycloakMgm keycloak.AccessManagement) (*InvokerManager, chan eventsapi.EventNotification, *echo.Echo) {
296 swagger, err := invokermanagementapi.GetSwagger()
298 fmt.Fprintf(os.Stderr, "Error loading swagger spec\n: %s", err)
302 swagger.Servers = nil
304 eventChannel := make(chan eventsapi.EventNotification)
305 im := NewInvokerManager(publishRegister, keycloakMgm, eventChannel)
308 e.Use(echomiddleware.Logger())
309 e.Use(middleware.OapiRequestValidator(swagger))
311 invokermanagementapi.RegisterHandlers(e, im)
312 return im, eventChannel, e
315 func getAefProfile(aefId string) publishserviceapi.AefProfile {
316 return publishserviceapi.AefProfile{
318 Versions: []publishserviceapi.Version{
320 Resources: &[]publishserviceapi.Resource{
322 CommType: "REQUEST_RESPONSE",
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",
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) {
347 return &event, false // completed normally
348 case <-time.After(timeout):
349 return nil, true // timed out