Implementation for GET/DELETE 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         "oransc.org/nonrtric/capifcore/internal/common29122"
33         securityapi "oransc.org/nonrtric/capifcore/internal/securityapi"
34
35         "oransc.org/nonrtric/capifcore/internal/invokermanagement"
36         "oransc.org/nonrtric/capifcore/internal/keycloak"
37         "oransc.org/nonrtric/capifcore/internal/providermanagement"
38         "oransc.org/nonrtric/capifcore/internal/publishservice"
39 )
40
41 type Security struct {
42         serviceRegister providermanagement.ServiceRegister
43         publishRegister publishservice.PublishRegister
44         invokerRegister invokermanagement.InvokerRegister
45         keycloak        keycloak.AccessManagement
46         trustedInvokers map[string]securityapi.ServiceSecurity
47         lock            sync.Mutex
48 }
49
50 func NewSecurity(serviceRegister providermanagement.ServiceRegister, publishRegister publishservice.PublishRegister, invokerRegister invokermanagement.InvokerRegister, km keycloak.AccessManagement) *Security {
51         return &Security{
52                 serviceRegister: serviceRegister,
53                 publishRegister: publishRegister,
54                 invokerRegister: invokerRegister,
55                 keycloak:        km,
56                 trustedInvokers: make(map[string]securityapi.ServiceSecurity),
57         }
58 }
59
60 func (s *Security) PostSecuritiesSecurityIdToken(ctx echo.Context, securityId string) error {
61         var accessTokenReq securityapi.AccessTokenReq
62         accessTokenReq.GetAccessTokenReq(ctx)
63
64         if valid, err := accessTokenReq.Validate(); !valid {
65                 return ctx.JSON(http.StatusBadRequest, err)
66         }
67
68         if !s.invokerRegister.IsInvokerRegistered(accessTokenReq.ClientId) {
69                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidClient, "Invoker not registered")
70         }
71
72         if !s.invokerRegister.VerifyInvokerSecret(accessTokenReq.ClientId, *accessTokenReq.ClientSecret) {
73                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, "Invoker secret not valid")
74         }
75
76         if accessTokenReq.Scope != nil && *accessTokenReq.Scope != "" {
77                 scope := strings.Split(*accessTokenReq.Scope, "#")
78                 aefList := strings.Split(scope[1], ";")
79                 for _, aef := range aefList {
80                         apiList := strings.Split(aef, ":")
81                         if !s.serviceRegister.IsFunctionRegistered(apiList[0]) {
82                                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidScope, "AEF Function not registered")
83                         }
84                         for _, api := range strings.Split(apiList[1], ",") {
85                                 if !s.publishRegister.IsAPIPublished(apiList[0], api) {
86                                         return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidScope, "API not published")
87                                 }
88                         }
89                 }
90         }
91         jwtToken, err := s.keycloak.GetToken(accessTokenReq.ClientId, *accessTokenReq.ClientSecret, *accessTokenReq.Scope, "invokerrealm")
92         if err != nil {
93                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, err.Error())
94         }
95
96         accessTokenResp := securityapi.AccessTokenRsp{
97                 AccessToken: jwtToken.AccessToken,
98                 ExpiresIn:   common29122.DurationSec(jwtToken.ExpiresIn),
99                 Scope:       accessTokenReq.Scope,
100                 TokenType:   "Bearer",
101         }
102
103         err = ctx.JSON(http.StatusCreated, accessTokenResp)
104         if err != nil {
105                 // Something really bad happened, tell Echo that our handler failed
106                 return err
107         }
108
109         return nil
110 }
111
112 func (s *Security) DeleteTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
113         if _, ok := s.trustedInvokers[apiInvokerId]; ok {
114                 s.deleteTrustedInvoker(apiInvokerId)
115         }
116
117         return ctx.NoContent(http.StatusNoContent)
118 }
119
120 func (s *Security) deleteTrustedInvoker(apiInvokerId string) {
121         s.lock.Lock()
122         defer s.lock.Unlock()
123         delete(s.trustedInvokers, apiInvokerId)
124 }
125
126 func (s *Security) GetTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string, params securityapi.GetTrustedInvokersApiInvokerIdParams) error {
127
128         if trustedInvoker, ok := s.trustedInvokers[apiInvokerId]; ok {
129                 updatedInvoker := s.checkParams(trustedInvoker, params)
130                 if updatedInvoker != nil {
131                         err := ctx.JSON(http.StatusOK, updatedInvoker)
132                         if err != nil {
133                                 return err
134                         }
135                 }
136         } else {
137                 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf("invoker %s not registered as trusted invoker", apiInvokerId))
138         }
139
140         return nil
141 }
142
143 func (s *Security) checkParams(trustedInvoker securityapi.ServiceSecurity, params securityapi.GetTrustedInvokersApiInvokerIdParams) *securityapi.ServiceSecurity {
144         emptyString := ""
145
146         var sendAuthenticationInfo = (params.AuthenticationInfo != nil) && *params.AuthenticationInfo
147         var sendAuthorizationInfo = (params.AuthorizationInfo != nil) && *params.AuthorizationInfo
148
149         if sendAuthenticationInfo && sendAuthorizationInfo {
150                 return &trustedInvoker
151         }
152
153         data, _ := copystructure.Copy(trustedInvoker)
154         updatedInvoker, ok := data.(securityapi.ServiceSecurity)
155         if !ok {
156                 return nil
157         }
158
159         if !sendAuthenticationInfo {
160                 for i := range updatedInvoker.SecurityInfo {
161                         updatedInvoker.SecurityInfo[i].AuthenticationInfo = &emptyString
162                 }
163         }
164         if !sendAuthorizationInfo {
165                 for i := range updatedInvoker.SecurityInfo {
166                         updatedInvoker.SecurityInfo[i].AuthorizationInfo = &emptyString
167                 }
168         }
169         return &updatedInvoker
170 }
171
172 func (s *Security) PutTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
173         errMsg := "Unable to update security context due to %s."
174
175         if !s.invokerRegister.IsInvokerRegistered(apiInvokerId) {
176                 return sendCoreError(ctx, http.StatusBadRequest, "Unable to update security context due to Invoker not registered")
177         }
178         serviceSecurity, err := getServiceSecurityFromRequest(ctx)
179         if err != nil {
180                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
181         }
182
183         if err := serviceSecurity.Validate(); err != nil {
184                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
185         }
186
187         err = s.prepareNewSecurityContext(&serviceSecurity, apiInvokerId)
188         if err != nil {
189                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
190         }
191
192         uri := ctx.Request().Host + ctx.Request().URL.String()
193         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, apiInvokerId))
194
195         err = ctx.JSON(http.StatusCreated, s.trustedInvokers[apiInvokerId])
196         if err != nil {
197                 // Something really bad happened, tell Echo that our handler failed
198                 return err
199         }
200
201         return nil
202 }
203
204 func getServiceSecurityFromRequest(ctx echo.Context) (securityapi.ServiceSecurity, error) {
205         var serviceSecurity securityapi.ServiceSecurity
206         err := ctx.Bind(&serviceSecurity)
207         if err != nil {
208                 return securityapi.ServiceSecurity{}, fmt.Errorf("invalid format for service security")
209         }
210         return serviceSecurity, nil
211 }
212
213 func (s *Security) prepareNewSecurityContext(newContext *securityapi.ServiceSecurity, apiInvokerId string) error {
214         s.lock.Lock()
215         defer s.lock.Unlock()
216
217         err := newContext.PrepareNewSecurityContext(s.publishRegister.GetAllPublishedServices())
218         if err != nil {
219                 return err
220         }
221
222         s.trustedInvokers[apiInvokerId] = *newContext
223         return nil
224 }
225
226 func (s *Security) PostTrustedInvokersApiInvokerIdDelete(ctx echo.Context, apiInvokerId string) error {
227         return ctx.NoContent(http.StatusNotImplemented)
228 }
229
230 func (s *Security) PostTrustedInvokersApiInvokerIdUpdate(ctx echo.Context, apiInvokerId string) error {
231         return ctx.NoContent(http.StatusNotImplemented)
232 }
233
234 func sendAccessTokenError(ctx echo.Context, code int, err securityapi.AccessTokenErrError, message string) error {
235         accessTokenErr := securityapi.AccessTokenErr{
236                 Error:            err,
237                 ErrorDescription: &message,
238         }
239         return ctx.JSON(code, accessTokenErr)
240 }
241
242 // This function wraps sending of an error in the Error format, and
243 // handling the failure to marshal that.
244 func sendCoreError(ctx echo.Context, code int, message string) error {
245         pd := common29122.ProblemDetails{
246                 Cause:  &message,
247                 Status: &code,
248         }
249         err := ctx.JSON(code, pd)
250         return err
251 }