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"
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 return ctx.NoContent(http.StatusNotImplemented)
116 func (s *Security) GetTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string, params securityapi.GetTrustedInvokersApiInvokerIdParams) error {
117 return ctx.NoContent(http.StatusNotImplemented)
120 func (s *Security) PutTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
121 errMsg := "Unable to update security context due to %s."
123 if !s.invokerRegister.IsInvokerRegistered(apiInvokerId) {
124 return sendCoreError(ctx, http.StatusBadRequest, "Unable to update security context due to Invoker not registered")
126 serviceSecurity, err := getServiceSecurityFromRequest(ctx)
128 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
131 if err := serviceSecurity.Validate(); err != nil {
132 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
135 err = s.prepareNewSecurityContext(&serviceSecurity, apiInvokerId)
137 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
140 uri := ctx.Request().Host + ctx.Request().URL.String()
141 ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, apiInvokerId))
143 err = ctx.JSON(http.StatusCreated, s.trustedInvokers[apiInvokerId])
145 // Something really bad happened, tell Echo that our handler failed
152 func getServiceSecurityFromRequest(ctx echo.Context) (securityapi.ServiceSecurity, error) {
153 var serviceSecurity securityapi.ServiceSecurity
154 err := ctx.Bind(&serviceSecurity)
156 return securityapi.ServiceSecurity{}, fmt.Errorf("invalid format for service security")
158 return serviceSecurity, nil
161 func (s *Security) prepareNewSecurityContext(newContext *securityapi.ServiceSecurity, apiInvokerId string) error {
163 defer s.lock.Unlock()
165 err := newContext.PrepareNewSecurityContext(s.publishRegister.GetAllPublishedServices())
170 s.trustedInvokers[apiInvokerId] = *newContext
174 func (s *Security) PostTrustedInvokersApiInvokerIdDelete(ctx echo.Context, apiInvokerId string) error {
175 return ctx.NoContent(http.StatusNotImplemented)
178 func (s *Security) PostTrustedInvokersApiInvokerIdUpdate(ctx echo.Context, apiInvokerId string) error {
179 return ctx.NoContent(http.StatusNotImplemented)
182 func sendAccessTokenError(ctx echo.Context, code int, err securityapi.AccessTokenErrError, message string) error {
183 accessTokenErr := securityapi.AccessTokenErr{
185 ErrorDescription: &message,
187 return ctx.JSON(code, accessTokenErr)
190 // This function wraps sending of an error in the Error format, and
191 // handling the failure to marshal that.
192 func sendCoreError(ctx echo.Context, code int, message string) error {
193 pd := common29122.ProblemDetails{
197 err := ctx.JSON(code, pd)