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