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