Implementation for Update and revoke trustedInvokers endpoint
[nonrtric/plt/sme.git] / capifcore / internal / securityservice / security.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 security
22
23 import (
24         "fmt"
25         "net/http"
26         "path"
27         "strings"
28         "sync"
29
30         "github.com/labstack/echo/v4"
31         copystructure "github.com/mitchellh/copystructure"
32         "k8s.io/utils/strings/slices"
33         "oransc.org/nonrtric/capifcore/internal/common29122"
34         securityapi "oransc.org/nonrtric/capifcore/internal/securityapi"
35
36         "oransc.org/nonrtric/capifcore/internal/invokermanagement"
37         "oransc.org/nonrtric/capifcore/internal/keycloak"
38         "oransc.org/nonrtric/capifcore/internal/providermanagement"
39         "oransc.org/nonrtric/capifcore/internal/publishservice"
40 )
41
42 type Security struct {
43         serviceRegister providermanagement.ServiceRegister
44         publishRegister publishservice.PublishRegister
45         invokerRegister invokermanagement.InvokerRegister
46         keycloak        keycloak.AccessManagement
47         trustedInvokers map[string]securityapi.ServiceSecurity
48         lock            sync.Mutex
49 }
50
51 func NewSecurity(serviceRegister providermanagement.ServiceRegister, publishRegister publishservice.PublishRegister, invokerRegister invokermanagement.InvokerRegister, km keycloak.AccessManagement) *Security {
52         return &Security{
53                 serviceRegister: serviceRegister,
54                 publishRegister: publishRegister,
55                 invokerRegister: invokerRegister,
56                 keycloak:        km,
57                 trustedInvokers: make(map[string]securityapi.ServiceSecurity),
58         }
59 }
60
61 func (s *Security) PostSecuritiesSecurityIdToken(ctx echo.Context, securityId string) error {
62         var accessTokenReq securityapi.AccessTokenReq
63         accessTokenReq.GetAccessTokenReq(ctx)
64
65         if valid, err := accessTokenReq.Validate(); !valid {
66                 return ctx.JSON(http.StatusBadRequest, err)
67         }
68
69         if !s.invokerRegister.IsInvokerRegistered(accessTokenReq.ClientId) {
70                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidClient, "Invoker not registered")
71         }
72
73         if !s.invokerRegister.VerifyInvokerSecret(accessTokenReq.ClientId, *accessTokenReq.ClientSecret) {
74                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, "Invoker secret not valid")
75         }
76
77         if accessTokenReq.Scope != nil && *accessTokenReq.Scope != "" {
78                 scope := strings.Split(*accessTokenReq.Scope, "#")
79                 aefList := strings.Split(scope[1], ";")
80                 for _, aef := range aefList {
81                         apiList := strings.Split(aef, ":")
82                         if !s.serviceRegister.IsFunctionRegistered(apiList[0]) {
83                                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidScope, "AEF Function not registered")
84                         }
85                         for _, api := range strings.Split(apiList[1], ",") {
86                                 if !s.publishRegister.IsAPIPublished(apiList[0], api) {
87                                         return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidScope, "API not published")
88                                 }
89                         }
90                 }
91         }
92         jwtToken, err := s.keycloak.GetToken(accessTokenReq.ClientId, *accessTokenReq.ClientSecret, *accessTokenReq.Scope, "invokerrealm")
93         if err != nil {
94                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, err.Error())
95         }
96
97         accessTokenResp := securityapi.AccessTokenRsp{
98                 AccessToken: jwtToken.AccessToken,
99                 ExpiresIn:   common29122.DurationSec(jwtToken.ExpiresIn),
100                 Scope:       accessTokenReq.Scope,
101                 TokenType:   "Bearer",
102         }
103
104         err = ctx.JSON(http.StatusCreated, accessTokenResp)
105         if err != nil {
106                 // Something really bad happened, tell Echo that our handler failed
107                 return err
108         }
109
110         return nil
111 }
112
113 func (s *Security) DeleteTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
114         if _, ok := s.trustedInvokers[apiInvokerId]; ok {
115                 s.deleteTrustedInvoker(apiInvokerId)
116         }
117
118         return ctx.NoContent(http.StatusNoContent)
119 }
120
121 func (s *Security) deleteTrustedInvoker(apiInvokerId string) {
122         s.lock.Lock()
123         defer s.lock.Unlock()
124         delete(s.trustedInvokers, apiInvokerId)
125 }
126
127 func (s *Security) GetTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string, params securityapi.GetTrustedInvokersApiInvokerIdParams) error {
128
129         if trustedInvoker, ok := s.trustedInvokers[apiInvokerId]; ok {
130                 updatedInvoker := s.checkParams(trustedInvoker, params)
131                 if updatedInvoker != nil {
132                         err := ctx.JSON(http.StatusOK, updatedInvoker)
133                         if err != nil {
134                                 return err
135                         }
136                 }
137         } else {
138                 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf("invoker %s not registered as trusted invoker", apiInvokerId))
139         }
140
141         return nil
142 }
143
144 func (s *Security) checkParams(trustedInvoker securityapi.ServiceSecurity, params securityapi.GetTrustedInvokersApiInvokerIdParams) *securityapi.ServiceSecurity {
145         emptyString := ""
146
147         var sendAuthenticationInfo = (params.AuthenticationInfo != nil) && *params.AuthenticationInfo
148         var sendAuthorizationInfo = (params.AuthorizationInfo != nil) && *params.AuthorizationInfo
149
150         if sendAuthenticationInfo && sendAuthorizationInfo {
151                 return &trustedInvoker
152         }
153
154         data, _ := copystructure.Copy(trustedInvoker)
155         updatedInvoker, ok := data.(securityapi.ServiceSecurity)
156         if !ok {
157                 return nil
158         }
159
160         if !sendAuthenticationInfo {
161                 for i := range updatedInvoker.SecurityInfo {
162                         updatedInvoker.SecurityInfo[i].AuthenticationInfo = &emptyString
163                 }
164         }
165         if !sendAuthorizationInfo {
166                 for i := range updatedInvoker.SecurityInfo {
167                         updatedInvoker.SecurityInfo[i].AuthorizationInfo = &emptyString
168                 }
169         }
170         return &updatedInvoker
171 }
172
173 func (s *Security) PutTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
174         errMsg := "Unable to update security context due to %s."
175
176         if !s.invokerRegister.IsInvokerRegistered(apiInvokerId) {
177                 return sendCoreError(ctx, http.StatusBadRequest, "Unable to update security context due to Invoker not registered")
178         }
179         serviceSecurity, err := getServiceSecurityFromRequest(ctx)
180         if err != nil {
181                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
182         }
183
184         if err := serviceSecurity.Validate(); err != nil {
185                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
186         }
187
188         err = s.prepareNewSecurityContext(&serviceSecurity, apiInvokerId)
189         if err != nil {
190                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
191         }
192
193         uri := ctx.Request().Host + ctx.Request().URL.String()
194         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, apiInvokerId))
195
196         err = ctx.JSON(http.StatusCreated, s.trustedInvokers[apiInvokerId])
197         if err != nil {
198                 // Something really bad happened, tell Echo that our handler failed
199                 return err
200         }
201
202         return nil
203 }
204
205 func getServiceSecurityFromRequest(ctx echo.Context) (securityapi.ServiceSecurity, error) {
206         var serviceSecurity securityapi.ServiceSecurity
207         err := ctx.Bind(&serviceSecurity)
208         if err != nil {
209                 return securityapi.ServiceSecurity{}, fmt.Errorf("invalid format for service security")
210         }
211         return serviceSecurity, nil
212 }
213
214 func (s *Security) prepareNewSecurityContext(newContext *securityapi.ServiceSecurity, apiInvokerId string) error {
215         s.lock.Lock()
216         defer s.lock.Unlock()
217
218         err := newContext.PrepareNewSecurityContext(s.publishRegister.GetAllPublishedServices())
219         if err != nil {
220                 return err
221         }
222
223         s.trustedInvokers[apiInvokerId] = *newContext
224         return nil
225 }
226
227 func (s *Security) PostTrustedInvokersApiInvokerIdDelete(ctx echo.Context, apiInvokerId string) error {
228         var notification securityapi.SecurityNotification
229
230         errMsg := "Unable to revoke invoker due to %s"
231
232         if err := ctx.Bind(&notification); err != nil {
233                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, "invalid format for security notification"))
234         }
235
236         if err := notification.Validate(); err != nil {
237                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
238         }
239
240         if ss, ok := s.trustedInvokers[apiInvokerId]; ok {
241                 securityInfoCopy := s.revokeTrustedInvoker(&ss, notification, apiInvokerId)
242
243                 if len(securityInfoCopy) == 0 {
244                         s.deleteTrustedInvoker(apiInvokerId)
245                 } else {
246                         ss.SecurityInfo = securityInfoCopy
247                         s.updateTrustedInvoker(ss, apiInvokerId)
248                 }
249
250         } else {
251                 return sendCoreError(ctx, http.StatusNotFound, "the invoker is not register as a trusted invoker")
252         }
253
254         return ctx.NoContent(http.StatusNoContent)
255
256 }
257
258 func (s *Security) revokeTrustedInvoker(ss *securityapi.ServiceSecurity, notification securityapi.SecurityNotification, apiInvokerId string) []securityapi.SecurityInformation {
259
260         data, _ := copystructure.Copy(ss.SecurityInfo)
261         securityInfoCopy, _ := data.([]securityapi.SecurityInformation)
262
263         for i, context := range ss.SecurityInfo {
264                 if notification.AefId == context.AefId || slices.Contains(notification.ApiIds, *context.ApiId) {
265                         securityInfoCopy = append(securityInfoCopy[:i], securityInfoCopy[i+1:]...)
266                 }
267         }
268
269         return securityInfoCopy
270
271 }
272
273 func (s *Security) PostTrustedInvokersApiInvokerIdUpdate(ctx echo.Context, apiInvokerId string) error {
274         var serviceSecurity securityapi.ServiceSecurity
275
276         errMsg := "Unable to update service security context due to %s"
277
278         if err := ctx.Bind(&serviceSecurity); err != nil {
279                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, "invalid format for service security context"))
280         }
281
282         if err := serviceSecurity.Validate(); err != nil {
283                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
284         }
285
286         if _, ok := s.trustedInvokers[apiInvokerId]; ok {
287                 s.updateTrustedInvoker(serviceSecurity, apiInvokerId)
288         } else {
289                 return sendCoreError(ctx, http.StatusNotFound, "the invoker is not register as a trusted invoker")
290         }
291
292         uri := ctx.Request().Host + ctx.Request().URL.String()
293         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, apiInvokerId))
294
295         err := ctx.JSON(http.StatusOK, s.trustedInvokers[apiInvokerId])
296         if err != nil {
297                 // Something really bad happened, tell Echo that our handler failed
298                 return err
299         }
300
301         return nil
302 }
303
304 func (s *Security) updateTrustedInvoker(serviceSecurity securityapi.ServiceSecurity, invokerId string) {
305         s.lock.Lock()
306         defer s.lock.Unlock()
307         s.trustedInvokers[invokerId] = serviceSecurity
308 }
309
310 func sendAccessTokenError(ctx echo.Context, code int, err securityapi.AccessTokenErrError, message string) error {
311         accessTokenErr := securityapi.AccessTokenErr{
312                 Error:            err,
313                 ErrorDescription: &message,
314         }
315         return ctx.JSON(code, accessTokenErr)
316 }
317
318 // This function wraps sending of an error in the Error format, and
319 // handling the failure to marshal that.
320 func sendCoreError(ctx echo.Context, code int, message string) error {
321         pd := common29122.ProblemDetails{
322                 Cause:  &message,
323                 Status: &code,
324         }
325         err := ctx.JSON(code, pd)
326         return err
327 }