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 "oransc.org/nonrtric/capifcore/internal/common29122"
33 securityapi "oransc.org/nonrtric/capifcore/internal/securityapi"
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"
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
50 func NewSecurity(serviceRegister providermanagement.ServiceRegister, publishRegister publishservice.PublishRegister, invokerRegister invokermanagement.InvokerRegister, km keycloak.AccessManagement) *Security {
52 serviceRegister: serviceRegister,
53 publishRegister: publishRegister,
54 invokerRegister: invokerRegister,
56 trustedInvokers: make(map[string]securityapi.ServiceSecurity),
60 func (s *Security) PostSecuritiesSecurityIdToken(ctx echo.Context, securityId string) error {
61 var accessTokenReq securityapi.AccessTokenReq
62 accessTokenReq.GetAccessTokenReq(ctx)
64 if valid, err := accessTokenReq.Validate(); !valid {
65 return ctx.JSON(http.StatusBadRequest, err)
68 if !s.invokerRegister.IsInvokerRegistered(accessTokenReq.ClientId) {
69 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidClient, "Invoker not registered")
72 if !s.invokerRegister.VerifyInvokerSecret(accessTokenReq.ClientId, *accessTokenReq.ClientSecret) {
73 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, "Invoker secret not valid")
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")
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")
91 jwtToken, err := s.keycloak.GetToken(accessTokenReq.ClientId, *accessTokenReq.ClientSecret, *accessTokenReq.Scope, "invokerrealm")
93 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, err.Error())
96 accessTokenResp := securityapi.AccessTokenRsp{
97 AccessToken: jwtToken.AccessToken,
98 ExpiresIn: common29122.DurationSec(jwtToken.ExpiresIn),
99 Scope: accessTokenReq.Scope,
103 err = ctx.JSON(http.StatusCreated, accessTokenResp)
105 // Something really bad happened, tell Echo that our handler failed
112 func (s *Security) DeleteTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
113 if _, ok := s.trustedInvokers[apiInvokerId]; ok {
114 s.deleteTrustedInvoker(apiInvokerId)
117 return ctx.NoContent(http.StatusNoContent)
120 func (s *Security) deleteTrustedInvoker(apiInvokerId string) {
122 defer s.lock.Unlock()
123 delete(s.trustedInvokers, apiInvokerId)
126 func (s *Security) GetTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string, params securityapi.GetTrustedInvokersApiInvokerIdParams) error {
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)
137 return sendCoreError(ctx, http.StatusNotFound, fmt.Sprintf("invoker %s not registered as trusted invoker", apiInvokerId))
143 func (s *Security) checkParams(trustedInvoker securityapi.ServiceSecurity, params securityapi.GetTrustedInvokersApiInvokerIdParams) *securityapi.ServiceSecurity {
146 var sendAuthenticationInfo = (params.AuthenticationInfo != nil) && *params.AuthenticationInfo
147 var sendAuthorizationInfo = (params.AuthorizationInfo != nil) && *params.AuthorizationInfo
149 if sendAuthenticationInfo && sendAuthorizationInfo {
150 return &trustedInvoker
153 data, _ := copystructure.Copy(trustedInvoker)
154 updatedInvoker, ok := data.(securityapi.ServiceSecurity)
159 if !sendAuthenticationInfo {
160 for i := range updatedInvoker.SecurityInfo {
161 updatedInvoker.SecurityInfo[i].AuthenticationInfo = &emptyString
164 if !sendAuthorizationInfo {
165 for i := range updatedInvoker.SecurityInfo {
166 updatedInvoker.SecurityInfo[i].AuthorizationInfo = &emptyString
169 return &updatedInvoker
172 func (s *Security) PutTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
173 errMsg := "Unable to update security context due to %s."
175 if !s.invokerRegister.IsInvokerRegistered(apiInvokerId) {
176 return sendCoreError(ctx, http.StatusBadRequest, "Unable to update security context due to Invoker not registered")
178 serviceSecurity, err := getServiceSecurityFromRequest(ctx)
180 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
183 if err := serviceSecurity.Validate(); err != nil {
184 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
187 err = s.prepareNewSecurityContext(&serviceSecurity, apiInvokerId)
189 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
192 uri := ctx.Request().Host + ctx.Request().URL.String()
193 ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, apiInvokerId))
195 err = ctx.JSON(http.StatusCreated, s.trustedInvokers[apiInvokerId])
197 // Something really bad happened, tell Echo that our handler failed
204 func getServiceSecurityFromRequest(ctx echo.Context) (securityapi.ServiceSecurity, error) {
205 var serviceSecurity securityapi.ServiceSecurity
206 err := ctx.Bind(&serviceSecurity)
208 return securityapi.ServiceSecurity{}, fmt.Errorf("invalid format for service security")
210 return serviceSecurity, nil
213 func (s *Security) prepareNewSecurityContext(newContext *securityapi.ServiceSecurity, apiInvokerId string) error {
215 defer s.lock.Unlock()
217 err := newContext.PrepareNewSecurityContext(s.publishRegister.GetAllPublishedServices())
222 s.trustedInvokers[apiInvokerId] = *newContext
226 func (s *Security) PostTrustedInvokersApiInvokerIdDelete(ctx echo.Context, apiInvokerId string) error {
227 return ctx.NoContent(http.StatusNotImplemented)
230 func (s *Security) PostTrustedInvokersApiInvokerIdUpdate(ctx echo.Context, apiInvokerId string) error {
231 return ctx.NoContent(http.StatusNotImplemented)
234 func sendAccessTokenError(ctx echo.Context, code int, err securityapi.AccessTokenErrError, message string) error {
235 accessTokenErr := securityapi.AccessTokenErr{
237 ErrorDescription: &message,
239 return ctx.JSON(code, accessTokenErr)
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{
249 err := ctx.JSON(code, pd)