NONRTRIC-946: Add support for Kong routes
[nonrtric/plt/sme.git] / servicemanager / internal / providermanagement / providermanagement_test.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2024: OpenInfra Foundation Europe
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package providermanagement
22
23 import (
24         "fmt"
25         "net/http"
26         "os"
27         "strings"
28         "testing"
29
30         echo "github.com/labstack/echo/v4"
31
32         "oransc.org/nonrtric/servicemanager/internal/common29122"
33         "oransc.org/nonrtric/servicemanager/internal/envreader"
34         "oransc.org/nonrtric/servicemanager/internal/kongclear"
35         provapi "oransc.org/nonrtric/servicemanager/internal/providermanagementapi"
36         "oransc.org/nonrtric/servicemanager/internal/publishservice"
37         publishapi "oransc.org/nonrtric/servicemanager/internal/publishserviceapi"
38
39         "github.com/deepmap/oapi-codegen/pkg/middleware"
40         "github.com/deepmap/oapi-codegen/pkg/testutil"
41         echomiddleware "github.com/labstack/echo/v4/middleware"
42         log "github.com/sirupsen/logrus"
43         "github.com/stretchr/testify/assert"
44 )
45
46 var (
47         domainID = "domain_id_Kong"
48         domainInfo  = "Kong"
49         funcInfoAPF = "rApp Kong as APF"
50         funcIdAPF   = "APF_id_rApp_Kong_as_APF"
51         funcInfoAEF = "rApp Kong as AEF"
52         funcIdAEF   = "AEF_id_rApp_Kong_as_AEF"
53 )
54
55 var requestHandler *echo.Echo
56
57 func TestMain(m *testing.M) {
58         err := setupTest()
59         if err != nil {
60                 return
61         }
62
63         ret := m.Run()
64         if ret == 0 {
65                 teardown()
66         }
67         os.Exit(ret)
68 }
69
70 func setupTest() error {
71         myEnv, myPorts, err := envreader.ReadDotEnv()
72         if err != nil {
73                 log.Fatal("error loading environment file on setupTest")
74                 return err
75         }
76
77         requestHandler, err = getEcho(myEnv, myPorts)
78         if err != nil {
79                 log.Fatal("getEcho fatal error on setupTest")
80                 return err
81         }
82         return err
83 }
84
85 func teardown() error {
86         log.Trace("entering teardown")
87
88         t := new(testing.T) // Create a new testing.T instance for teardown
89
90         // Delete the invoker
91         invokerInfo := "invoker a"
92         invokerId := "api_invoker_id_" + strings.Replace(invokerInfo, " ", "_", 1)
93
94         result := testutil.NewRequest().Delete("/api-invoker-management/v1/onboardedInvokers/"+invokerId).Go(t, requestHandler)
95         assert.Equal(t, http.StatusNoContent, result.Code())
96
97         // Delete the original published service
98         apfId := "APF_id_rApp_Kong_as_APF"
99         apiName := "apiName"
100         apiId := "api_id_" + apiName
101
102         result = testutil.NewRequest().Delete("/published-apis/v1/"+apfId+"/service-apis/"+apiId).Go(t, requestHandler)
103         assert.Equal(t, http.StatusNoContent, result.Code())
104
105         // Delete the first published service
106         apfId = "APF_id_rApp_Kong_as_APF"
107         apiName = "apiName1"
108         apiId = "api_id_" + apiName
109
110         result = testutil.NewRequest().Delete("/published-apis/v1/"+apfId+"/service-apis/"+apiId).Go(t, requestHandler)
111         assert.Equal(t, http.StatusNoContent, result.Code())
112
113         // Delete the second published service
114         apiName = "apiName2"
115         apiId = "api_id_" + apiName
116
117         result = testutil.NewRequest().Delete("/published-apis/v1/"+apfId+"/service-apis/"+apiId).Go(t, requestHandler)
118         assert.Equal(t, http.StatusNoContent, result.Code())
119
120         // Delete the provider
121         result = testutil.NewRequest().Delete("/api-provider-management/v1/registrations/"+domainID).Go(t, requestHandler)
122         assert.Equal(t, http.StatusNoContent, result.Code())
123
124         myEnv, myPorts, err := envreader.ReadDotEnv()
125         if err != nil {
126                 log.Fatal("error loading environment file")
127                 return err
128         }
129
130         err = kongclear.KongClear(myEnv, myPorts)
131         if err != nil {
132                 log.Fatal("error clearing Kong on teardown")
133         }
134         return err
135 }
136
137 func TestRegisterValidProvider(t *testing.T) {
138         teardown()
139
140         // Register a valid provider
141         newProvider := getProvider()
142         result := testutil.NewRequest().Post("/api-provider-management/v1/registrations").WithJsonBody(newProvider).Go(t, requestHandler)
143         assert.Equal(t, http.StatusCreated, result.Code())
144
145         var resultProvider provapi.APIProviderEnrolmentDetails
146         err := result.UnmarshalBodyToObject(&resultProvider)
147         assert.NoError(t, err, "error unmarshaling response")
148
149         assert.NotNil(t, resultProvider.ApiProvDomId, "error reading resultProvider")
150
151         if resultProvider.ApiProvDomId != nil {
152                 assert.Equal(t, *resultProvider.ApiProvDomId, domainID)
153
154                 apiProvFuncAPF := (*resultProvider.ApiProvFuncs)[0]
155                 apiProvFuncIdAPF := *apiProvFuncAPF.ApiProvFuncId
156                 assert.Equal(t, apiProvFuncIdAPF, funcIdAPF)
157
158                 // We don't handle AMF
159                 apiProvFuncAEF := (*resultProvider.ApiProvFuncs)[1]
160                 apiProvFuncIdAEF := *apiProvFuncAEF.ApiProvFuncId
161                 assert.Equal(t, apiProvFuncIdAEF, funcIdAEF)
162
163                 assert.Empty(t, resultProvider.FailReason)
164                 assert.Equal(t, "http://example.com/api-provider-management/v1/registrations/"+*resultProvider.ApiProvDomId, result.Recorder.Header().Get(echo.HeaderLocation))
165
166                 // Register same provider again should result in Forbidden
167                 result = testutil.NewRequest().Post("/api-provider-management/v1/registrations").WithJsonBody(newProvider).Go(t, requestHandler)
168
169                 var errorObj common29122.ProblemDetails
170                 assert.Equal(t, http.StatusForbidden, result.Code())
171
172                 err = result.UnmarshalBodyToObject(&errorObj)
173                 assert.NoError(t, err, "error unmarshaling response")
174                 assert.Equal(t, http.StatusForbidden, *errorObj.Status)
175                 assert.Contains(t, *errorObj.Cause, "already registered")
176         }
177 }
178
179 func TestUpdateValidProviderWithNewFunction(t *testing.T) {
180         // Modify the provider
181         updatedProvider := getProvider()
182         updatedProvider.ApiProvDomId = &domainID
183
184         newDomainInfo := "New domain info"
185         updatedProvider.ApiProvDomInfo = &newDomainInfo
186         newFunctionInfo := "New function info"
187         (*updatedProvider.ApiProvFuncs)[0].ApiProvFuncInfo = &newFunctionInfo
188         newFuncInfoAEF := "new func as AEF"
189
190         testFuncs := append(*updatedProvider.ApiProvFuncs, provapi.APIProviderFunctionDetails{
191                 ApiProvFuncInfo: &newFuncInfoAEF,
192                 ApiProvFuncRole: provapi.ApiProviderFuncRoleAEF,
193                 RegInfo: provapi.RegistrationInformation{
194                         ApiProvPubKey: "key",
195                 },
196         })
197         updatedProvider.ApiProvFuncs = &testFuncs
198
199         result := testutil.NewRequest().Put("/api-provider-management/v1/registrations/"+domainID).WithJsonBody(updatedProvider).Go(t, requestHandler)
200
201         var resultProvider provapi.APIProviderEnrolmentDetails
202         assert.Equal(t, http.StatusOK, result.Code())
203
204         err := result.UnmarshalBodyToObject(&resultProvider)
205         assert.NoError(t, err, "error unmarshaling response")
206
207         assert.Equal(t, newDomainInfo, *resultProvider.ApiProvDomInfo)
208         assert.Equal(t, newFunctionInfo, *(*resultProvider.ApiProvFuncs)[0].ApiProvFuncInfo)
209         assert.Equal(t, *(*resultProvider.ApiProvFuncs)[2].ApiProvFuncId, "AEF_id_new_func_as_AEF")
210         assert.Empty(t, resultProvider.FailReason)
211 }
212
213 func TestDeleteProvider(t *testing.T) {
214         provider := getProvider()
215         provider.ApiProvDomId = &domainID
216         (*provider.ApiProvFuncs)[0].ApiProvFuncId = &funcIdAPF
217         result := testutil.NewRequest().Delete("/api-provider-management/v1/registrations/"+domainID).Go(t, requestHandler)
218         assert.Equal(t, http.StatusNoContent, result.Code())
219         teardown()
220 }
221
222 func getProvider() provapi.APIProviderEnrolmentDetails {
223         testFuncs := []provapi.APIProviderFunctionDetails{
224                 {
225                         ApiProvFuncInfo: &funcInfoAPF,
226                         ApiProvFuncRole: provapi.ApiProviderFuncRoleAPF,
227                         RegInfo: provapi.RegistrationInformation{
228                                 ApiProvPubKey: "APF-PublicKey",
229                         },
230                 },
231                 {
232                         ApiProvFuncInfo: &funcInfoAEF,
233                         ApiProvFuncRole: provapi.ApiProviderFuncRoleAEF,
234                         RegInfo: provapi.RegistrationInformation{
235                                 ApiProvPubKey: "AEF-PublicKey",
236                         },
237                 },
238         }
239         return provapi.APIProviderEnrolmentDetails{
240                 RegSec:         "sec",
241                 ApiProvDomInfo: &domainInfo,
242                 ApiProvFuncs:   &testFuncs,
243         }
244 }
245
246 func getEcho(myEnv map[string]string, myPorts map[string]int) (*echo.Echo, error) {
247         capifProtocol := myEnv["CAPIF_PROTOCOL"]
248         capifIPv4 := common29122.Ipv4Addr(myEnv["CAPIF_IPV4"])
249         capifPort := common29122.Port(myPorts["CAPIF_PORT"])
250         kongDomain := myEnv["KONG_DOMAIN"]
251         kongProtocol := myEnv["KONG_PROTOCOL"]
252         kongIPv4 := common29122.Ipv4Addr(myEnv["KONG_IPV4"])
253         kongDataPlanePort := common29122.Port(myPorts["KONG_DATA_PLANE_PORT"])
254         kongControlPlanePort := common29122.Port(myPorts["KONG_CONTROL_PLANE_PORT"])
255
256         e := echo.New()
257
258         // Register ProviderManagement
259         providerManagerSwagger, err := provapi.GetSwagger()
260         if err != nil {
261                 log.Fatalf("Error loading ProviderManagement swagger spec\n: %s", err)
262                 return nil, err
263         }
264         providerManagerSwagger.Servers = nil
265         providerManager := NewProviderManager(capifProtocol, capifIPv4, capifPort)
266
267         var group *echo.Group
268
269         group = e.Group("/api-provider-management/v1")
270         group.Use(middleware.OapiRequestValidator(providerManagerSwagger))
271         provapi.RegisterHandlersWithBaseURL(e, providerManager, "/api-provider-management/v1")
272
273         publishServiceSwagger, err := publishapi.GetSwagger()
274         if err != nil {
275                 fmt.Fprintf(os.Stderr, "Error loading PublishService swagger spec\n: %s", err)
276                 return nil, err
277         }
278
279         publishServiceSwagger.Servers = nil
280
281         ps := publishservice.NewPublishService(kongDomain, kongProtocol, kongIPv4, kongDataPlanePort, kongControlPlanePort, capifProtocol, capifIPv4, capifPort)
282
283         group = e.Group("/published-apis/v1")
284         group.Use(echomiddleware.Logger())
285         group.Use(middleware.OapiRequestValidator(publishServiceSwagger))
286         publishapi.RegisterHandlersWithBaseURL(e, ps, "/published-apis/v1")
287
288         // return ps, eventChannel, e
289         return e, err
290 }