d71ff0defd1700eb64e74195d96fd2e50d02235c
[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         "net/http"
25         "strings"
26         "time"
27
28         "github.com/golang-jwt/jwt"
29         "github.com/labstack/echo/v4"
30
31         "oransc.org/nonrtric/capifcore/internal/common29122"
32         securityapi "oransc.org/nonrtric/capifcore/internal/securityapi"
33
34         "oransc.org/nonrtric/capifcore/internal/invokermanagement"
35         "oransc.org/nonrtric/capifcore/internal/providermanagement"
36         "oransc.org/nonrtric/capifcore/internal/publishservice"
37 )
38
39 var jwtKey = "my-secret-key"
40
41 type Security struct {
42         serviceRegister providermanagement.ServiceRegister
43         publishRegister publishservice.PublishRegister
44         invokerRegister invokermanagement.InvokerRegister
45 }
46
47 func NewSecurity(serviceRegister providermanagement.ServiceRegister, publishRegister publishservice.PublishRegister, invokerRegister invokermanagement.InvokerRegister) *Security {
48         return &Security{
49                 serviceRegister: serviceRegister,
50                 publishRegister: publishRegister,
51                 invokerRegister: invokerRegister,
52         }
53 }
54
55 func (s *Security) PostSecuritiesSecurityIdToken(ctx echo.Context, securityId string) error {
56         var accessTokenReq securityapi.AccessTokenReq
57         accessTokenReq.GetAccessTokenReq(ctx)
58
59         if valid, err := accessTokenReq.Validate(); !valid {
60                 return ctx.JSON(http.StatusBadRequest, err)
61         }
62
63         if !s.invokerRegister.IsInvokerRegistered(accessTokenReq.ClientId) {
64                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidClient, "Invoker not registered")
65         }
66
67         if !s.invokerRegister.VerifyInvokerSecret(accessTokenReq.ClientId, *accessTokenReq.ClientSecret) {
68                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorUnauthorizedClient, "Invoker secret not valid")
69         }
70
71         if accessTokenReq.Scope != nil {
72                 scope := strings.Split(*accessTokenReq.Scope, "#")
73                 aefList := strings.Split(scope[1], ";")
74                 for _, aef := range aefList {
75                         apiList := strings.Split(aef, ":")
76                         if !s.serviceRegister.IsFunctionRegistered(apiList[0]) {
77                                 return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidScope, "AEF Function not registered")
78                         }
79                         for _, api := range strings.Split(apiList[1], ",") {
80                                 if !s.publishRegister.IsAPIPublished(apiList[0], api) {
81                                         return sendAccessTokenError(ctx, http.StatusBadRequest, securityapi.AccessTokenErrErrorInvalidScope, "API not published")
82                                 }
83                         }
84                 }
85         }
86
87         expirationTime := time.Now().Add(time.Hour).Unix()
88
89         claims := &jwt.MapClaims{
90                 "iss": accessTokenReq.ClientId,
91                 "exp": expirationTime,
92                 "data": map[string]interface{}{
93                         "scope": accessTokenReq.Scope,
94                 },
95         }
96
97         token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
98         tokenString, err := token.SignedString([]byte(jwtKey))
99         if err != nil {
100                 // If there is an error in creating the JWT return an internal server error
101                 return err
102         }
103
104         accessTokenResp := securityapi.AccessTokenRsp{
105                 AccessToken: tokenString,
106                 ExpiresIn:   common29122.DurationSec(expirationTime),
107                 Scope:       accessTokenReq.Scope,
108                 TokenType:   "Bearer",
109         }
110
111         err = ctx.JSON(http.StatusCreated, accessTokenResp)
112         if err != nil {
113                 // Something really bad happened, tell Echo that our handler failed
114                 return err
115         }
116
117         return nil
118 }
119
120 func (s *Security) DeleteTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
121         return ctx.NoContent(http.StatusNotImplemented)
122 }
123
124 func (s *Security) GetTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string, params securityapi.GetTrustedInvokersApiInvokerIdParams) error {
125         return ctx.NoContent(http.StatusNotImplemented)
126 }
127
128 func (s *Security) PutTrustedInvokersApiInvokerId(ctx echo.Context, apiInvokerId string) error {
129         return ctx.NoContent(http.StatusNotImplemented)
130 }
131
132 func (s *Security) PostTrustedInvokersApiInvokerIdDelete(ctx echo.Context, apiInvokerId string) error {
133         return ctx.NoContent(http.StatusNotImplemented)
134 }
135
136 func (s *Security) PostTrustedInvokersApiInvokerIdUpdate(ctx echo.Context, apiInvokerId string) error {
137         return ctx.NoContent(http.StatusNotImplemented)
138 }
139
140 func sendAccessTokenError(ctx echo.Context, code int, err securityapi.AccessTokenErrError, message string) error {
141         accessTokenErr := securityapi.AccessTokenErr{
142                 Error:            err,
143                 ErrorDescription: &message,
144         }
145         return ctx.JSON(code, accessTokenErr)
146 }