Implementation for PUT 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
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         return ctx.NoContent(http.StatusNotImplemented)
114 }
115
116 func (s *Security) GetTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string, params securityapi.GetTrustedInvokersApiInvokerIdParams) error {
117         return ctx.NoContent(http.StatusNotImplemented)
118 }
119
120 func (s *Security) PutTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
121         errMsg := "Unable to update security context due to %s."
122
123         if !s.invokerRegister.IsInvokerRegistered(apiInvokerId) {
124                 return sendCoreError(ctx, http.StatusBadRequest, "Unable to update security context due to Invoker not registered")
125         }
126         serviceSecurity, err := getServiceSecurityFromRequest(ctx)
127         if err != nil {
128                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
129         }
130
131         if err := serviceSecurity.Validate(); err != nil {
132                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
133         }
134
135         err = s.prepareNewSecurityContext(&serviceSecurity, apiInvokerId)
136         if err != nil {
137                 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
138         }
139
140         uri := ctx.Request().Host + ctx.Request().URL.String()
141         ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, apiInvokerId))
142
143         err = ctx.JSON(http.StatusCreated, s.trustedInvokers[apiInvokerId])
144         if err != nil {
145                 // Something really bad happened, tell Echo that our handler failed
146                 return err
147         }
148
149         return nil
150 }
151
152 func getServiceSecurityFromRequest(ctx echo.Context) (securityapi.ServiceSecurity, error) {
153         var serviceSecurity securityapi.ServiceSecurity
154         err := ctx.Bind(&serviceSecurity)
155         if err != nil {
156                 return securityapi.ServiceSecurity{}, fmt.Errorf("invalid format for service security")
157         }
158         return serviceSecurity, nil
159 }
160
161 func (s *Security) prepareNewSecurityContext(newContext *securityapi.ServiceSecurity, apiInvokerId string) error {
162         s.lock.Lock()
163         defer s.lock.Unlock()
164
165         err := newContext.PrepareNewSecurityContext(s.publishRegister.GetAllPublishedServices())
166         if err != nil {
167                 return err
168         }
169
170         s.trustedInvokers[apiInvokerId] = *newContext
171         return nil
172 }
173
174 func (s *Security) PostTrustedInvokersApiInvokerIdDelete(ctx echo.Context, apiInvokerId string) error {
175         return ctx.NoContent(http.StatusNotImplemented)
176 }
177
178 func (s *Security) PostTrustedInvokersApiInvokerIdUpdate(ctx echo.Context, apiInvokerId string) error {
179         return ctx.NoContent(http.StatusNotImplemented)
180 }
181
182 func sendAccessTokenError(ctx echo.Context, code int, err securityapi.AccessTokenErrError, message string) error {
183         accessTokenErr := securityapi.AccessTokenErr{
184                 Error:            err,
185                 ErrorDescription: &message,
186         }
187         return ctx.JSON(code, accessTokenErr)
188 }
189
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{
194                 Cause:  &message,
195                 Status: &code,
196         }
197         err := ctx.JSON(code, pd)
198         return err
199 }