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