f0a4155b42ac629a43a5f40224a172f27fb76695
[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         "oransc.org/nonrtric/capifcore/internal/keycloak"
31
32         "oransc.org/nonrtric/capifcore/internal/common29122"
33         invokerapi "oransc.org/nonrtric/capifcore/internal/invokermanagementapi"
34         "oransc.org/nonrtric/capifcore/internal/publishservice"
35
36         echo "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         keycloak          keycloak.AccessManagement
57         eventChannel      chan<- eventsapi.EventNotification
58         lock              sync.Mutex
59 }
60
61 // Creates a manager that implements both the InvokerRegister and the invokermanagementapi.ServerInterface interfaces.
62 func NewInvokerManager(publishRegister publishservice.PublishRegister, km keycloak.AccessManagement, eventChannel chan<- eventsapi.EventNotification) *InvokerManager {
63         return &InvokerManager{
64                 onboardedInvokers: make(map[string]invokerapi.APIInvokerEnrolmentDetails),
65                 publishRegister:   publishRegister,
66                 nextId:            1000,
67                 keycloak:          km,
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         errMsg := "Unable to onboard invoker due to %s"
106
107         newInvoker, err := getInvokerFromRequest(ctx)
108         if err != nil {
109                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
110         }
111
112         if err = im.isInvokerOnboarded(newInvoker); err != nil {
113                 return sendCoreError(ctx, http.StatusForbidden, fmt.Sprintf(errMsg, err))
114         }
115
116         if err = im.validateInvoker(newInvoker, ctx); err != nil {
117                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
118         }
119
120         im.prepareNewInvoker(&newInvoker)
121
122         go im.sendEvent(*newInvoker.ApiInvokerId, eventsapi.CAPIFEventAPIINVOKERONBOARDED)
123
124         uri := ctx.Request().Host + ctx.Request().URL.String()
125         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newInvoker.ApiInvokerId))
126
127         err = ctx.JSON(http.StatusCreated, newInvoker)
128         if err != nil {
129                 // Something really bad happened, tell Echo that our handler failed
130                 return err
131         }
132
133         return nil
134 }
135
136 func (im *InvokerManager) isInvokerOnboarded(newInvoker invokerapi.APIInvokerEnrolmentDetails) error {
137         for _, invoker := range im.onboardedInvokers {
138                 if err := invoker.ValidateAlreadyOnboarded(newInvoker); err != nil {
139                         return err
140                 }
141         }
142         return nil
143 }
144
145 func (im *InvokerManager) prepareNewInvoker(newInvoker *invokerapi.APIInvokerEnrolmentDetails) {
146         var apiList invokerapi.APIList = im.publishRegister.GetAllPublishedServices()
147         newInvoker.ApiList = &apiList
148
149         im.lock.Lock()
150         defer im.lock.Unlock()
151
152         newInvoker.PrepareNewInvoker()
153
154         im.addClientInKeycloak(newInvoker)
155
156         im.onboardedInvokers[*newInvoker.ApiInvokerId] = *newInvoker
157 }
158
159 func (im *InvokerManager) addClientInKeycloak(newInvoker *invokerapi.APIInvokerEnrolmentDetails) error {
160         if err := im.keycloak.AddClient(*newInvoker.ApiInvokerId, "invokerrealm"); err != nil {
161                 return err
162         }
163
164         if body, err := im.keycloak.GetClientRepresentation(*newInvoker.ApiInvokerId, "invokerrealm"); err != nil {
165                 return err
166         } else {
167                 newInvoker.OnboardingInformation.OnboardingSecret = body.Secret
168         }
169         return nil
170 }
171
172 // Deletes an individual API Invoker.
173 func (im *InvokerManager) DeleteOnboardedInvokersOnboardingId(ctx echo.Context, onboardingId string) error {
174         if _, ok := im.onboardedInvokers[onboardingId]; ok {
175                 im.deleteInvoker(onboardingId)
176         }
177
178         go im.sendEvent(onboardingId, eventsapi.CAPIFEventAPIINVOKEROFFBOARDED)
179
180         return ctx.NoContent(http.StatusNoContent)
181 }
182
183 func (im *InvokerManager) deleteInvoker(onboardingId string) {
184         im.lock.Lock()
185         defer im.lock.Unlock()
186         delete(im.onboardedInvokers, onboardingId)
187 }
188
189 func getInvokerFromRequest(ctx echo.Context) (invokerapi.APIInvokerEnrolmentDetails, error) {
190         var invoker invokerapi.APIInvokerEnrolmentDetails
191         if err := ctx.Bind(&invoker); err != nil {
192                 return invokerapi.APIInvokerEnrolmentDetails{}, fmt.Errorf("invalid format for invoker")
193         }
194         return invoker, nil
195 }
196
197 // Updates an individual API invoker details.
198 func (im *InvokerManager) PutOnboardedInvokersOnboardingId(ctx echo.Context, onboardingId string) error {
199         errMsg := "Unable to update invoker due to %s"
200
201         newInvoker, err := getInvokerFromRequest(ctx)
202         if err != nil {
203                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
204         }
205
206         // Additional validation for PUT
207         if (newInvoker.ApiInvokerId == nil) || (*newInvoker.ApiInvokerId != onboardingId) {
208                 errMismatch := "APIInvokerEnrolmentDetails ApiInvokerId doesn't match path parameter"
209                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, errMismatch))
210         }
211
212         if err := im.validateInvoker(newInvoker, ctx); err != nil {
213                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
214         }
215
216         if _, ok := im.onboardedInvokers[onboardingId]; ok {
217                 im.updateInvoker(newInvoker)
218         } else {
219                 return sendCoreError(ctx, http.StatusNotFound, "The invoker to update has not been onboarded")
220         }
221
222         err = ctx.JSON(http.StatusOK, newInvoker)
223         if err != nil {
224                 // Something really bad happened, tell Echo that our handler failed
225                 return err
226         }
227
228         return nil
229 }
230
231 func (im *InvokerManager) updateInvoker(invoker invokerapi.APIInvokerEnrolmentDetails) {
232         im.lock.Lock()
233         defer im.lock.Unlock()
234         im.onboardedInvokers[*invoker.ApiInvokerId] = invoker
235 }
236
237 func (im *InvokerManager) ModifyIndApiInvokeEnrolment(ctx echo.Context, onboardingId string) error {
238         return ctx.NoContent(http.StatusNotImplemented)
239 }
240
241 func (im *InvokerManager) validateInvoker(invoker invokerapi.APIInvokerEnrolmentDetails, ctx echo.Context) error {
242         if err := invoker.Validate(); err != nil {
243                 return err
244         }
245
246         return nil
247 }
248
249 func (im *InvokerManager) sendEvent(invokerId string, eventType eventsapi.CAPIFEvent) {
250         invokerIds := []string{invokerId}
251         event := eventsapi.EventNotification{
252                 EventDetail: &eventsapi.CAPIFEventDetail{
253                         ApiInvokerIds: &invokerIds,
254                 },
255                 Events: eventType,
256         }
257         im.eventChannel <- event
258 }
259
260 // This function wraps sending of an error in the Error format, and
261 // handling the failure to marshal that.
262 func sendCoreError(ctx echo.Context, code int, message string) error {
263         pd := common29122.ProblemDetails{
264                 Cause:  &message,
265                 Status: &code,
266         }
267         err := ctx.JSON(code, pd)
268         return err
269 }