Add event sending to publishservice
[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         publishapi "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
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         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) *InvokerManager {
62         return &InvokerManager{
63                 onboardedInvokers: make(map[string]invokerapi.APIInvokerEnrolmentDetails),
64                 publishRegister:   publishRegister,
65                 nextId:            1000,
66         }
67 }
68
69 func (im *InvokerManager) IsInvokerRegistered(invokerId string) bool {
70         im.lock.Lock()
71         defer im.lock.Unlock()
72
73         _, registered := im.onboardedInvokers[invokerId]
74         return registered
75 }
76
77 func (im *InvokerManager) VerifyInvokerSecret(invokerId, secret string) bool {
78         im.lock.Lock()
79         defer im.lock.Unlock()
80
81         verified := false
82         if invoker, registered := im.onboardedInvokers[invokerId]; registered {
83                 verified = *invoker.OnboardingInformation.OnboardingSecret == secret
84         }
85         return verified
86 }
87
88 func (im *InvokerManager) GetInvokerApiList(invokerId string) *invokerapi.APIList {
89         invoker, ok := im.onboardedInvokers[invokerId]
90         if ok {
91                 var apiList invokerapi.APIList = im.publishRegister.GetAllPublishedServices()
92                 im.lock.Lock()
93                 defer im.lock.Unlock()
94                 invoker.ApiList = &apiList
95                 return &apiList
96         }
97         return nil
98 }
99
100 // Creates a new individual API Invoker profile.
101 func (im *InvokerManager) PostOnboardedInvokers(ctx echo.Context) error {
102         var newInvoker invokerapi.APIInvokerEnrolmentDetails
103         err := ctx.Bind(&newInvoker)
104         if err != nil {
105                 return sendCoreError(ctx, http.StatusBadRequest, "Invalid format for invoker")
106         }
107
108         shouldReturn, coreError := im.validateInvoker(newInvoker, ctx)
109         if shouldReturn {
110                 return coreError
111         }
112
113         im.lock.Lock()
114         defer im.lock.Unlock()
115
116         newInvoker.ApiInvokerId = im.getId(newInvoker.ApiInvokerInformation)
117         onboardingSecret := "onboarding_secret_"
118         if newInvoker.ApiInvokerInformation != nil {
119                 onboardingSecret = onboardingSecret + strings.ReplaceAll(*newInvoker.ApiInvokerInformation, " ", "_")
120         } else {
121                 onboardingSecret = onboardingSecret + *newInvoker.ApiInvokerId
122         }
123         newInvoker.OnboardingInformation.OnboardingSecret = &onboardingSecret
124
125         var apiList invokerapi.APIList = im.publishRegister.GetAllPublishedServices()
126         newInvoker.ApiList = &apiList
127
128         im.onboardedInvokers[*newInvoker.ApiInvokerId] = newInvoker
129
130         uri := ctx.Request().Host + ctx.Request().URL.String()
131         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, *newInvoker.ApiInvokerId))
132         err = ctx.JSON(http.StatusCreated, newInvoker)
133         if err != nil {
134                 // Something really bad happened, tell Echo that our handler failed
135                 return err
136         }
137
138         return nil
139 }
140
141 // Deletes an individual API Invoker.
142 func (im *InvokerManager) DeleteOnboardedInvokersOnboardingId(ctx echo.Context, onboardingId string) error {
143         im.lock.Lock()
144         defer im.lock.Unlock()
145
146         delete(im.onboardedInvokers, onboardingId)
147
148         return ctx.NoContent(http.StatusNoContent)
149 }
150
151 // Updates an individual API invoker details.
152 func (im *InvokerManager) PutOnboardedInvokersOnboardingId(ctx echo.Context, onboardingId string) error {
153         var invoker invokerapi.APIInvokerEnrolmentDetails
154         err := ctx.Bind(&invoker)
155         if err != nil {
156                 return sendCoreError(ctx, http.StatusBadRequest, "Invalid format for invoker")
157         }
158
159         if onboardingId != *invoker.ApiInvokerId {
160                 return sendCoreError(ctx, http.StatusBadRequest, "Invoker ApiInvokerId not matching")
161         }
162
163         shouldReturn, coreError := im.validateInvoker(invoker, ctx)
164         if shouldReturn {
165                 return coreError
166         }
167
168         im.lock.Lock()
169         defer im.lock.Unlock()
170
171         if _, ok := im.onboardedInvokers[onboardingId]; ok {
172                 im.onboardedInvokers[*invoker.ApiInvokerId] = invoker
173         } else {
174                 return sendCoreError(ctx, http.StatusNotFound, "The invoker to update has not been onboarded")
175         }
176
177         err = ctx.JSON(http.StatusOK, invoker)
178         if err != nil {
179                 // Something really bad happened, tell Echo that our handler failed
180                 return err
181         }
182
183         return nil
184 }
185
186 func (im *InvokerManager) ModifyIndApiInvokeEnrolment(ctx echo.Context, onboardingId string) error {
187         return ctx.NoContent(http.StatusNotImplemented)
188 }
189
190 func (im *InvokerManager) validateInvoker(invoker invokerapi.APIInvokerEnrolmentDetails, ctx echo.Context) (bool, error) {
191         if invoker.NotificationDestination == "" {
192                 return true, sendCoreError(ctx, http.StatusBadRequest, "Invoker missing required NotificationDestination")
193         }
194
195         if invoker.OnboardingInformation.ApiInvokerPublicKey == "" {
196                 return true, sendCoreError(ctx, http.StatusBadRequest, "Invoker missing required OnboardingInformation.ApiInvokerPublicKey")
197         }
198
199         if !im.areAPIsPublished(invoker.ApiList) {
200                 return true, sendCoreError(ctx, http.StatusBadRequest, "Some APIs needed by invoker are not registered")
201         }
202
203         return false, nil
204 }
205
206 func (im *InvokerManager) areAPIsPublished(apis *invokerapi.APIList) bool {
207         if apis == nil {
208                 return true
209         }
210         return im.publishRegister.AreAPIsPublished((*[]publishapi.ServiceAPIDescription)(apis))
211 }
212
213 func (im *InvokerManager) getId(invokerInfo *string) *string {
214         idAsString := "api_invoker_id_"
215         if invokerInfo != nil {
216                 idAsString = idAsString + strings.ReplaceAll(*invokerInfo, " ", "_")
217         } else {
218                 idAsString = idAsString + strconv.FormatInt(im.nextId, 10)
219                 im.nextId = im.nextId + 1
220         }
221         return &idAsString
222 }
223
224 // This function wraps sending of an error in the Error format, and
225 // handling the failure to marshal that.
226 func sendCoreError(ctx echo.Context, code int, message string) error {
227         pd := common29122.ProblemDetails{
228                 Cause:  &message,
229                 Status: &code,
230         }
231         err := ctx.JSON(code, pd)
232         return err
233 }