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