2 // ========================LICENSE_START=================================
5 // Copyright (C) 2022: Nordix Foundation
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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===================================
31 "github.com/labstack/echo/v4"
32 copystructure "github.com/mitchellh/copystructure"
33 "k8s.io/utils/strings/slices"
34 "oransc.org/nonrtric/capifcore/internal/common29122"
35 securityapi "oransc.org/nonrtric/capifcore/internal/securityapi"
37 "oransc.org/nonrtric/capifcore/internal/invokermanagement"
38 "oransc.org/nonrtric/capifcore/internal/keycloak"
39 "oransc.org/nonrtric/capifcore/internal/providermanagement"
40 "oransc.org/nonrtric/capifcore/internal/publishservice"
43 type Security struct {
44 serviceRegister providermanagement.ServiceRegister
45 publishRegister publishservice.PublishRegister
46 invokerRegister invokermanagement.InvokerRegister
47 keycloak keycloak.AccessManagement
48 trustedInvokers map[string]securityapi.ServiceSecurity
52 func NewSecurity(serviceRegister providermanagement.ServiceRegister, publishRegister publishservice.PublishRegister, invokerRegister invokermanagement.InvokerRegister, km keycloak.AccessManagement) *Security {
54 serviceRegister: serviceRegister,
55 publishRegister: publishRegister,
56 invokerRegister: invokerRegister,
58 trustedInvokers: make(map[string]securityapi.ServiceSecurity),
62 func (s *Security) PostSecuritiesSecurityIdToken(ctx echo.Context, securityId string) error {
63 var accessTokenReq securityapi.AccessTokenReq
64 accessTokenReq.GetAccessTokenReq(ctx)
66 if valid, err := accessTokenReq.Validate(); !valid {
67 return ctx.JSON(http.StatusBadRequest, err)
70 if !s.invokerRegister.IsInvokerRegistered(accessTokenReq.ClientId) {
71 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidClient, "Invoker not registered")
74 if !s.invokerRegister.VerifyInvokerSecret(accessTokenReq.ClientId, *accessTokenReq.ClientSecret) {
75 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, "Invoker secret not valid")
78 if accessTokenReq.Scope != nil && *accessTokenReq.Scope != "" {
79 scope := strings.Split(*accessTokenReq.Scope, "#")
80 aefList := strings.Split(scope[1], ";")
81 for _, aef := range aefList {
82 apiList := strings.Split(aef, ":")
83 if !s.serviceRegister.IsFunctionRegistered(apiList[0]) {
84 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidScope, "AEF Function not registered")
86 for _, api := range strings.Split(apiList[1], ",") {
87 if !s.publishRegister.IsAPIPublished(apiList[0], api) {
88 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidScope, "API not published")
93 data := url.Values{"grant_type": {"client_credentials"}, "client_id": {accessTokenReq.ClientId}, "client_secret": {*accessTokenReq.ClientSecret}}
94 jwtToken, err := s.keycloak.GetToken("invokerrealm", data)
96 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, err.Error())
99 accessTokenResp := securityapi.AccessTokenRsp{
100 AccessToken: jwtToken.AccessToken,
101 ExpiresIn: common29122.DurationSec(jwtToken.ExpiresIn),
102 Scope: accessTokenReq.Scope,
106 err = ctx.JSON(http.StatusCreated, accessTokenResp)
108 // Something really bad happened, tell Echo that our handler failed
115 func (s *Security) DeleteTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
116 if _, ok := s.trustedInvokers[apiInvokerId]; ok {
117 s.deleteTrustedInvoker(apiInvokerId)
120 return ctx.NoContent(http.StatusNoContent)
123 func (s *Security) deleteTrustedInvoker(apiInvokerId string) {
125 defer s.lock.Unlock()
126 delete(s.trustedInvokers, apiInvokerId)
129 func (s *Security) GetTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string, params securityapi.GetTrustedInvokersApiInvokerIdParams) error {
131 if trustedInvoker, ok := s.trustedInvokers[apiInvokerId]; ok {
132 updatedInvoker := s.checkParams(trustedInvoker, params)
133 if updatedInvoker != nil {
134 err := ctx.JSON(http.StatusOK, updatedInvoker)
140 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf("invoker %s not registered as trusted invoker", apiInvokerId))
146 func (s *Security) checkParams(trustedInvoker securityapi.ServiceSecurity, params securityapi.GetTrustedInvokersApiInvokerIdParams) *securityapi.ServiceSecurity {
149 var sendAuthenticationInfo = (params.AuthenticationInfo != nil) && *params.AuthenticationInfo
150 var sendAuthorizationInfo = (params.AuthorizationInfo != nil) && *params.AuthorizationInfo
152 if sendAuthenticationInfo && sendAuthorizationInfo {
153 return &trustedInvoker
156 data, _ := copystructure.Copy(trustedInvoker)
157 updatedInvoker, ok := data.(securityapi.ServiceSecurity)
162 if !sendAuthenticationInfo {
163 for i := range updatedInvoker.SecurityInfo {
164 updatedInvoker.SecurityInfo[i].AuthenticationInfo = &emptyString
167 if !sendAuthorizationInfo {
168 for i := range updatedInvoker.SecurityInfo {
169 updatedInvoker.SecurityInfo[i].AuthorizationInfo = &emptyString
172 return &updatedInvoker
175 func (s *Security) PutTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
176 errMsg := "Unable to update security context due to %s."
178 if !s.invokerRegister.IsInvokerRegistered(apiInvokerId) {
179 return sendCoreError(ctx, http.StatusBadRequest, "Unable to update security context due to Invoker not registered")
181 serviceSecurity, err := getServiceSecurityFromRequest(ctx)
183 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
186 if err := serviceSecurity.Validate(); err != nil {
187 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
190 err = s.prepareNewSecurityContext(&serviceSecurity, apiInvokerId)
192 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
195 uri := ctx.Request().Host + ctx.Request().URL.String()
196 ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, apiInvokerId))
198 err = ctx.JSON(http.StatusCreated, s.trustedInvokers[apiInvokerId])
200 // Something really bad happened, tell Echo that our handler failed
207 func getServiceSecurityFromRequest(ctx echo.Context) (securityapi.ServiceSecurity, error) {
208 var serviceSecurity securityapi.ServiceSecurity
209 err := ctx.Bind(&serviceSecurity)
211 return securityapi.ServiceSecurity{}, fmt.Errorf("invalid format for service security")
213 return serviceSecurity, nil
216 func (s *Security) prepareNewSecurityContext(newContext *securityapi.ServiceSecurity, apiInvokerId string) error {
218 defer s.lock.Unlock()
220 err := newContext.PrepareNewSecurityContext(s.publishRegister.GetAllPublishedServices())
225 s.trustedInvokers[apiInvokerId] = *newContext
229 func (s *Security) PostTrustedInvokersApiInvokerIdDelete(ctx echo.Context, apiInvokerId string) error {
230 var notification securityapi.SecurityNotification
232 errMsg := "Unable to revoke invoker due to %s"
234 if err := ctx.Bind(¬ification); err != nil {
235 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, "invalid format for security notification"))
238 if err := notification.Validate(); err != nil {
239 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
242 if ss, ok := s.trustedInvokers[apiInvokerId]; ok {
243 securityInfoCopy := s.revokeTrustedInvoker(&ss, notification, apiInvokerId)
245 if len(securityInfoCopy) == 0 {
246 s.deleteTrustedInvoker(apiInvokerId)
248 ss.SecurityInfo = securityInfoCopy
249 s.updateTrustedInvoker(ss, apiInvokerId)
253 return sendCoreError(ctx, http.StatusNotFound, "the invoker is not register as a trusted invoker")
256 return ctx.NoContent(http.StatusNoContent)
260 func (s *Security) revokeTrustedInvoker(ss *securityapi.ServiceSecurity, notification securityapi.SecurityNotification, apiInvokerId string) []securityapi.SecurityInformation {
262 data, _ := copystructure.Copy(ss.SecurityInfo)
263 securityInfoCopy, _ := data.([]securityapi.SecurityInformation)
265 for i, context := range ss.SecurityInfo {
266 if notification.AefId == context.AefId || slices.Contains(notification.ApiIds, *context.ApiId) {
267 securityInfoCopy = append(securityInfoCopy[:i], securityInfoCopy[i+1:]...)
271 return securityInfoCopy
275 func (s *Security) PostTrustedInvokersApiInvokerIdUpdate(ctx echo.Context, apiInvokerId string) error {
276 var serviceSecurity securityapi.ServiceSecurity
278 errMsg := "Unable to update service security context due to %s"
280 if err := ctx.Bind(&serviceSecurity); err != nil {
281 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, "invalid format for service security context"))
284 if err := serviceSecurity.Validate(); err != nil {
285 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
288 if _, ok := s.trustedInvokers[apiInvokerId]; ok {
289 s.updateTrustedInvoker(serviceSecurity, apiInvokerId)
291 return sendCoreError(ctx, http.StatusNotFound, "the invoker is not register as a trusted invoker")
294 uri := ctx.Request().Host + ctx.Request().URL.String()
295 ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, apiInvokerId))
297 err := ctx.JSON(http.StatusOK, s.trustedInvokers[apiInvokerId])
299 // Something really bad happened, tell Echo that our handler failed
306 func (s *Security) updateTrustedInvoker(serviceSecurity securityapi.ServiceSecurity, invokerId string) {
308 defer s.lock.Unlock()
309 s.trustedInvokers[invokerId] = serviceSecurity
312 func sendAccessTokenError(ctx echo.Context, code int, err securityapi.AccessTokenErrError, message string) error {
313 accessTokenErr := securityapi.AccessTokenErr{
315 ErrorDescription: &message,
317 return ctx.JSON(code, accessTokenErr)
320 // This function wraps sending of an error in the Error format, and
321 // handling the failure to marshal that.
322 func sendCoreError(ctx echo.Context, code int, message string) error {
323 pd := common29122.ProblemDetails{
327 err := ctx.JSON(code, pd)