9025f83e602bec08b7b945af4de3a8e4b8effdbe
[nonrtric/plt/sme.git] / capifcore / internal / invokermanagement / invokermanagement.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: Nordix Foundation
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 invokermanagement
22
23 import (
24         "net/http"
25         "path"
26         "strconv"
27         "strings"
28         "sync"
29
30         "oransc.org/nonrtric/capifcore/internal/eventsapi"
31         publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
32
33         "oransc.org/nonrtric/capifcore/internal/common29122"
34         invokerapi "oransc.org/nonrtric/capifcore/internal/invokermanagementapi"
35
36         "oransc.org/nonrtric/capifcore/internal/publishservice"
37
38         "github.com/labstack/echo/v4"
39 )
40
41 //go:generate mockery --name InvokerRegister
42 type InvokerRegister interface {
43         // Checks if the invoker is registered.
44         // Returns true of the provided invoker is registered, false otherwise.
45         IsInvokerRegistered(invokerId string) bool
46         // Verifies that the provided secret is the invoker's registered secret.
47         // Returns true if the provided secret is the registered invoker's secret, false otherwise.
48         VerifyInvokerSecret(invokerId, secret string) bool
49         // Gets the provided invoker's registered APIs.
50         // Returns a list of all the invoker's registered APIs.
51         GetInvokerApiList(invokerId string) *invokerapi.APIList
52 }
53
54 type InvokerManager struct {
55         onboardedInvokers map[string]invokerapi.APIInvokerEnrolmentDetails
56         publishRegister   publishservice.PublishRegister
57         nextId            int64
58         eventChannel      chan<- eventsapi.EventNotification
59         lock              sync.Mutex
60 }
61
62 // Creates a manager that implements both the InvokerRegister and the invokermanagementapi.ServerInterface interfaces.
63 func NewInvokerManager(publishRegister publishservice.PublishRegister, eventChannel chan<- eventsapi.EventNotification) *InvokerManager {
64         return &InvokerManager{
65                 onboardedInvokers: make(map[string]invokerapi.APIInvokerEnrolmentDetails),
66                 publishRegister:   publishRegister,
67                 nextId:            1000,
68                 eventChannel:      eventChannel,
69         }
70 }
71
72 func (im *InvokerManager) IsInvokerRegistered(invokerId string) bool {
73         im.lock.Lock()
74         defer im.lock.Unlock()
75
76         _, registered := im.onboardedInvokers[invokerId]
77         return registered
78 }
79
80 func (im *InvokerManager) VerifyInvokerSecret(invokerId, secret string) bool {
81         im.lock.Lock()
82         defer im.lock.Unlock()
83
84         verified := false
85         if invoker, registered := im.onboardedInvokers[invokerId]; registered {
86                 verified = *invoker.OnboardingInformation.OnboardingSecret == secret
87         }
88         return verified
89 }
90
91 func (im *InvokerManager) GetInvokerApiList(invokerId string) *invokerapi.APIList {
92         var apiList invokerapi.APIList = im.publishRegister.GetAllPublishedServices()
93         im.lock.Lock()
94         defer im.lock.Unlock()
95         invoker, ok := im.onboardedInvokers[invokerId]
96         if ok {
97                 invoker.ApiList = &apiList
98                 return &apiList
99         }
100         return nil
101 }
102
103 // Creates a new individual API Invoker profile.
104 func (im *InvokerManager) PostOnboardedInvokers(ctx echo.Context) error {
105         var newInvoker invokerapi.APIInvokerEnrolmentDetails
106         err := ctx.Bind(&newInvoker)
107         if err != nil {
108                 return sendCoreError(ctx, http.StatusBadRequest, "Invalid format for invoker")
109         }
110
111         shouldReturn, coreError := im.validateInvoker(newInvoker, ctx)
112         if shouldReturn {
113                 return coreError
114         }
115
116         im.prepareNewInvoker(&newInvoker)
117
118         go im.sendEvent(*newInvoker.ApiInvokerId, eventsapi.CAPIFEventAPIINVOKERONBOARDED)
119
120         uri := ctx.Request().Host + ctx.Request().URL.String()
121         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newInvoker.ApiInvokerId))
122         err = ctx.JSON(http.StatusCreated, newInvoker)
123         if err != nil {
124                 // Something really bad happened, tell Echo that our handler failed
125                 return err
126         }
127
128         return nil
129 }
130
131 func (im *InvokerManager) prepareNewInvoker(newInvoker *invokerapi.APIInvokerEnrolmentDetails) {
132         im.lock.Lock()
133         defer im.lock.Unlock()
134
135         newInvoker.ApiInvokerId = im.getId(newInvoker.ApiInvokerInformation)
136         newInvoker.OnboardingInformation.OnboardingSecret = getOnboardingSecret(*newInvoker)
137
138         var apiList invokerapi.APIList = im.publishRegister.GetAllPublishedServices()
139         newInvoker.ApiList = &apiList
140
141         im.onboardedInvokers[*newInvoker.ApiInvokerId] = *newInvoker
142 }
143
144 func getOnboardingSecret(newInvoker invokerapi.APIInvokerEnrolmentDetails) *string {
145         onboardingSecret := "onboarding_secret_"
146         if newInvoker.ApiInvokerInformation != nil {
147                 onboardingSecret = onboardingSecret + strings.ReplaceAll(*newInvoker.ApiInvokerInformation, " ", "_")
148         } else {
149                 onboardingSecret = onboardingSecret + *newInvoker.ApiInvokerId
150         }
151         return &onboardingSecret
152 }
153
154 // Deletes an individual API Invoker.
155 func (im *InvokerManager) DeleteOnboardedInvokersOnboardingId(ctx echo.Context, onboardingId string) error {
156         if _, ok := im.onboardedInvokers[onboardingId]; ok {
157                 im.deleteInvoker(onboardingId)
158         }
159
160         go im.sendEvent(onboardingId, eventsapi.CAPIFEventAPIINVOKEROFFBOARDED)
161
162         return ctx.NoContent(http.StatusNoContent)
163 }
164
165 func (im *InvokerManager) deleteInvoker(onboardingId string) {
166         im.lock.Lock()
167         defer im.lock.Unlock()
168         delete(im.onboardedInvokers, onboardingId)
169 }
170
171 // Updates an individual API invoker details.
172 func (im *InvokerManager) PutOnboardedInvokersOnboardingId(ctx echo.Context, onboardingId string) error {
173         var invoker invokerapi.APIInvokerEnrolmentDetails
174         err := ctx.Bind(&invoker)
175         if err != nil {
176                 return sendCoreError(ctx, http.StatusBadRequest, "Invalid format for invoker")
177         }
178
179         if onboardingId != *invoker.ApiInvokerId {
180                 return sendCoreError(ctx, http.StatusBadRequest, "Invoker ApiInvokerId not matching")
181         }
182
183         shouldReturn, coreError := im.validateInvoker(invoker, ctx)
184         if shouldReturn {
185                 return coreError
186         }
187
188         if _, ok := im.onboardedInvokers[onboardingId]; ok {
189                 im.updateInvoker(invoker)
190         } else {
191                 return sendCoreError(ctx, http.StatusNotFound, "The invoker to update has not been onboarded")
192         }
193
194         err = ctx.JSON(http.StatusOK, invoker)
195         if err != nil {
196                 // Something really bad happened, tell Echo that our handler failed
197                 return err
198         }
199
200         return nil
201 }
202
203 func (im *InvokerManager) updateInvoker(invoker invokerapi.APIInvokerEnrolmentDetails) {
204         im.lock.Lock()
205         defer im.lock.Unlock()
206         im.onboardedInvokers[*invoker.ApiInvokerId] = invoker
207 }
208
209 func (im *InvokerManager) ModifyIndApiInvokeEnrolment(ctx echo.Context, onboardingId string) error {
210         return ctx.NoContent(http.StatusNotImplemented)
211 }
212
213 func (im *InvokerManager) validateInvoker(invoker invokerapi.APIInvokerEnrolmentDetails, ctx echo.Context) (bool, error) {
214         if invoker.NotificationDestination == "" {
215                 return true, sendCoreError(ctx, http.StatusBadRequest, "Invoker missing required NotificationDestination")
216         }
217
218         if invoker.OnboardingInformation.ApiInvokerPublicKey == "" {
219                 return true, sendCoreError(ctx, http.StatusBadRequest, "Invoker missing required OnboardingInformation.ApiInvokerPublicKey")
220         }
221
222         if !im.areAPIsPublished(invoker.ApiList) {
223                 return true, sendCoreError(ctx, http.StatusBadRequest, "Some APIs needed by invoker are not registered")
224         }
225
226         return false, nil
227 }
228
229 func (im *InvokerManager) areAPIsPublished(apis *invokerapi.APIList) bool {
230         if apis == nil {
231                 return true
232         }
233         return im.publishRegister.AreAPIsPublished((*[]publishapi.ServiceAPIDescription)(apis))
234 }
235
236 func (im *InvokerManager) getId(invokerInfo *string) *string {
237         idAsString := "api_invoker_id_"
238         if invokerInfo != nil {
239                 idAsString = idAsString + strings.ReplaceAll(*invokerInfo, " ", "_")
240         } else {
241                 idAsString = idAsString + strconv.FormatInt(im.nextId, 10)
242                 im.nextId = im.nextId + 1
243         }
244         return &idAsString
245 }
246
247 func (im *InvokerManager) sendEvent(invokerId string, eventType eventsapi.CAPIFEvent) {
248         invokerIds := []string{invokerId}
249         event := eventsapi.EventNotification{
250                 EventDetail: &eventsapi.CAPIFEventDetail{
251                         ApiInvokerIds: &invokerIds,
252                 },
253                 Events: eventType,
254         }
255         im.eventChannel <- event
256 }
257
258 // This function wraps sending of an error in the Error format, and
259 // handling the failure to marshal that.
260 func sendCoreError(ctx echo.Context, code int, message string) error {
261         pd := common29122.ProblemDetails{
262                 Cause:  &message,
263                 Status: &code,
264         }
265         err := ctx.JSON(code, pd)
266         return err
267 }