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===================================
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"
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"
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
51 func NewSecurity(serviceRegister providermanagement.ServiceRegister, publishRegister publishservice.PublishRegister, invokerRegister invokermanagement.InvokerRegister, km keycloak.AccessManagement) *Security {
53 serviceRegister: serviceRegister,
54 publishRegister: publishRegister,
55 invokerRegister: invokerRegister,
57 trustedInvokers: make(map[string]securityapi.ServiceSecurity),
61 func (s *Security) PostSecuritiesSecurityIdToken(ctx echo.Context, securityId string) error {
62 var accessTokenReq securityapi.AccessTokenReq
63 accessTokenReq.GetAccessTokenReq(ctx)
65 if valid, err := accessTokenReq.Validate(); !valid {
66 return ctx.JSON(http.StatusBadRequest, err)
69 if !s.invokerRegister.IsInvokerRegistered(accessTokenReq.ClientId) {
70 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidClient, "Invoker not registered")
73 if !s.invokerRegister.VerifyInvokerSecret(accessTokenReq.ClientId, *accessTokenReq.ClientSecret) {
74 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, "Invoker secret not valid")
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")
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")
92 jwtToken, err := s.keycloak.GetToken(accessTokenReq.ClientId, *accessTokenReq.ClientSecret, *accessTokenReq.Scope, "invokerrealm")
94 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, err.Error())
97 accessTokenResp := securityapi.AccessTokenRsp{
98 AccessToken: jwtToken.AccessToken,
99 ExpiresIn: common29122.DurationSec(jwtToken.ExpiresIn),
100 Scope: accessTokenReq.Scope,
104 err = ctx.JSON(http.StatusCreated, accessTokenResp)
106 // Something really bad happened, tell Echo that our handler failed
113 func (s *Security) DeleteTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
114 if _, ok := s.trustedInvokers[apiInvokerId]; ok {
115 s.deleteTrustedInvoker(apiInvokerId)
118 return ctx.NoContent(http.StatusNoContent)
121 func (s *Security) deleteTrustedInvoker(apiInvokerId string) {
123 defer s.lock.Unlock()
124 delete(s.trustedInvokers, apiInvokerId)
127 func (s *Security) GetTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string, params securityapi.GetTrustedInvokersApiInvokerIdParams) error {
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)
138 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf("invoker %s not registered as trusted invoker", apiInvokerId))
144 func (s *Security) checkParams(trustedInvoker securityapi.ServiceSecurity, params securityapi.GetTrustedInvokersApiInvokerIdParams) *securityapi.ServiceSecurity {
147 var sendAuthenticationInfo = (params.AuthenticationInfo != nil) && *params.AuthenticationInfo
148 var sendAuthorizationInfo = (params.AuthorizationInfo != nil) && *params.AuthorizationInfo
150 if sendAuthenticationInfo && sendAuthorizationInfo {
151 return &trustedInvoker
154 data, _ := copystructure.Copy(trustedInvoker)
155 updatedInvoker, ok := data.(securityapi.ServiceSecurity)
160 if !sendAuthenticationInfo {
161 for i := range updatedInvoker.SecurityInfo {
162 updatedInvoker.SecurityInfo[i].AuthenticationInfo = &emptyString
165 if !sendAuthorizationInfo {
166 for i := range updatedInvoker.SecurityInfo {
167 updatedInvoker.SecurityInfo[i].AuthorizationInfo = &emptyString
170 return &updatedInvoker
173 func (s *Security) PutTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
174 errMsg := "Unable to update security context due to %s."
176 if !s.invokerRegister.IsInvokerRegistered(apiInvokerId) {
177 return sendCoreError(ctx, http.StatusBadRequest, "Unable to update security context due to Invoker not registered")
179 serviceSecurity, err := getServiceSecurityFromRequest(ctx)
181 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
184 if err := serviceSecurity.Validate(); err != nil {
185 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
188 err = s.prepareNewSecurityContext(&serviceSecurity, apiInvokerId)
190 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
193 uri := ctx.Request().Host + ctx.Request().URL.String()
194 ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, apiInvokerId))
196 err = ctx.JSON(http.StatusCreated, s.trustedInvokers[apiInvokerId])
198 // Something really bad happened, tell Echo that our handler failed
205 func getServiceSecurityFromRequest(ctx echo.Context) (securityapi.ServiceSecurity, error) {
206 var serviceSecurity securityapi.ServiceSecurity
207 err := ctx.Bind(&serviceSecurity)
209 return securityapi.ServiceSecurity{}, fmt.Errorf("invalid format for service security")
211 return serviceSecurity, nil
214 func (s *Security) prepareNewSecurityContext(newContext *securityapi.ServiceSecurity, apiInvokerId string) error {
216 defer s.lock.Unlock()
218 err := newContext.PrepareNewSecurityContext(s.publishRegister.GetAllPublishedServices())
223 s.trustedInvokers[apiInvokerId] = *newContext
227 func (s *Security) PostTrustedInvokersApiInvokerIdDelete(ctx echo.Context, apiInvokerId string) error {
228 var notification securityapi.SecurityNotification
230 errMsg := "Unable to revoke invoker due to %s"
232 if err := ctx.Bind(¬ification); err != nil {
233 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, "invalid format for security notification"))
236 if err := notification.Validate(); err != nil {
237 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
240 if ss, ok := s.trustedInvokers[apiInvokerId]; ok {
241 securityInfoCopy := s.revokeTrustedInvoker(&ss, notification, apiInvokerId)
243 if len(securityInfoCopy) == 0 {
244 s.deleteTrustedInvoker(apiInvokerId)
246 ss.SecurityInfo = securityInfoCopy
247 s.updateTrustedInvoker(ss, apiInvokerId)
251 return sendCoreError(ctx, http.StatusNotFound, "the invoker is not register as a trusted invoker")
254 return ctx.NoContent(http.StatusNoContent)
258 func (s *Security) revokeTrustedInvoker(ss *securityapi.ServiceSecurity, notification securityapi.SecurityNotification, apiInvokerId string) []securityapi.SecurityInformation {
260 data, _ := copystructure.Copy(ss.SecurityInfo)
261 securityInfoCopy, _ := data.([]securityapi.SecurityInformation)
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:]...)
269 return securityInfoCopy
273 func (s *Security) PostTrustedInvokersApiInvokerIdUpdate(ctx echo.Context, apiInvokerId string) error {
274 var serviceSecurity securityapi.ServiceSecurity
276 errMsg := "Unable to update service security context due to %s"
278 if err := ctx.Bind(&serviceSecurity); err != nil {
279 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, "invalid format for service security context"))
282 if err := serviceSecurity.Validate(); err != nil {
283 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
286 if _, ok := s.trustedInvokers[apiInvokerId]; ok {
287 s.updateTrustedInvoker(serviceSecurity, apiInvokerId)
289 return sendCoreError(ctx, http.StatusNotFound, "the invoker is not register as a trusted invoker")
292 uri := ctx.Request().Host + ctx.Request().URL.String()
293 ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, apiInvokerId))
295 err := ctx.JSON(http.StatusOK, s.trustedInvokers[apiInvokerId])
297 // Something really bad happened, tell Echo that our handler failed
304 func (s *Security) updateTrustedInvoker(serviceSecurity securityapi.ServiceSecurity, invokerId string) {
306 defer s.lock.Unlock()
307 s.trustedInvokers[invokerId] = serviceSecurity
310 func sendAccessTokenError(ctx echo.Context, code int, err securityapi.AccessTokenErrError, message string) error {
311 accessTokenErr := securityapi.AccessTokenErr{
313 ErrorDescription: &message,
315 return ctx.JSON(code, accessTokenErr)
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{
325 err := ctx.JSON(code, pd)