Skip to content

Commit a0df3c2

Browse files
committed
Refactor key rotation and synchronization logic
- Improved error handling in key rotation and health check functions to return errors from VaultSyncInitDefault. - Cleaned up code by removing unnecessary blank lines and comments. - Enhanced logging to provide better insights into failures during Vault operations. - Updated test cases to ensure proper error handling and response validation. - Consolidated mutex declarations for better readability. - Added SPDX license headers to several files for compliance. - Fixed minor issues in user account handling and subscriber configuration APIs. Signed-off-by: PedroVhGit <pedrovh040110@gmail.com>
1 parent 217150a commit a0df3c2

43 files changed

Lines changed: 297 additions & 340 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

backend/factory/factory.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ func GetConfig() *Config {
3737
// TODO: Support configuration update from REST api
3838
func InitConfigFactory(f string) error {
3939
content, err := os.ReadFile(f)
40-
4140
if err != nil {
4241
return fmt.Errorf("[Configuration] %+v", err)
4342
}

backend/logger/logger.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ var (
1919
WebUILog *zap.SugaredLogger
2020
ContextLog *zap.SugaredLogger
2121
GinLog *zap.SugaredLogger
22+
GrpcLog *zap.SugaredLogger
2223
ConfigLog *zap.SugaredLogger
2324
DbLog *zap.SugaredLogger
2425
AuthLog *zap.SugaredLogger
@@ -57,6 +58,7 @@ func init() {
5758
WebUILog = log.Sugar().With("component", "WebUI", "category", "WebUI")
5859
ContextLog = log.Sugar().With("component", "WebUI", "category", "Context")
5960
GinLog = log.Sugar().With("component", "WebUI", "category", "GIN")
61+
GrpcLog = log.Sugar().With("component", "WebUI", "category", "GRPC")
6062
ConfigLog = log.Sugar().With("component", "WebUI", "category", "CONFIG")
6163
DbLog = log.Sugar().With("component", "WebUI", "category", "DB")
6264
AuthLog = log.Sugar().With("component", "WebUI", "category", "Auth")

backend/metrics/telemetry.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,6 @@ import (
1818
func InitMetrics() {
1919
http.Handle("/metrics", promhttp.Handler())
2020
if err := http.ListenAndServe(":8080", nil); err != nil {
21-
logger.InitLog.Errorf("could not open metrics port: %v", err)
21+
logger.InitLog.Errorf("Could not open metrics port: %v", err)
2222
}
2323
}

backend/ssm/apiclient/login_auth.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@ import (
77
"github.com/omec-project/webconsole/backend/logger"
88
)
99

10-
var AuthContext context.Context = context.Background()
11-
var CurrentJWT string = ""
10+
var (
11+
AuthContext context.Context = context.Background()
12+
CurrentJWT string = ""
13+
)
1214

1315
// SetAuthContext sets the authentication context with the provided JWT token
1416
func SetAuthContext(jwt string) {
@@ -18,14 +20,14 @@ func SetAuthContext(jwt string) {
1820

1921
// LoginSSM performs login to the SSM and returns the authentication token
2022
func LoginSSM(serviceId, password string) (string, error) {
21-
var loginRequest = ssm_models.LoginRequest{
23+
loginRequest := ssm_models.LoginRequest{
2224
ServiceId: serviceId,
2325
Password: password,
2426
}
2527

26-
apiClient := GetSSMAPIClient()
28+
client := GetSSMAPIClient()
2729

28-
resp, r, err := apiClient.AuthenticationAPI.UserLogin(context.Background()).LoginRequest(loginRequest).Execute()
30+
resp, r, err := client.AuthenticationAPI.UserLogin(context.Background()).LoginRequest(loginRequest).Execute()
2931
if err != nil {
3032
logger.WebUILog.Errorf("Error when calling `AuthenticationAPI.UserLogin`: %v", err)
3133
logger.WebUILog.Errorf("Full HTTP response: %v", r)

backend/ssm/apiclient/login_auth_test.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ func TestLoginSSMSuccess(t *testing.T) {
1414
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1515
w.Header().Set("Content-Type", "application/json")
1616
w.WriteHeader(http.StatusOK)
17-
_, _ = w.Write([]byte(`{"token":"jwt123","message":"ok"}`))
17+
if _, err := w.Write([]byte(`{"token":"jwt123","message":"ok"}`)); err != nil {
18+
t.Fatalf("Failed to write response: %v", err)
19+
}
1820
}))
1921
defer server.Close()
2022

@@ -39,7 +41,9 @@ func TestLoginSSMError(t *testing.T) {
3941

4042
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
4143
w.WriteHeader(http.StatusInternalServerError)
42-
_, _ = w.Write([]byte(`{"message":"fail"}`))
44+
if _, err := w.Write([]byte(`{"message":"fail"}`)); err != nil {
45+
t.Fatalf("Failed to write response: %v", err)
46+
}
4347
}))
4448
defer server.Close()
4549

backend/ssm/apiclient/vault_client.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package apiclient
22

33
import (
4+
"errors"
45
"fmt"
56
"os"
67
"sync"
@@ -10,8 +11,10 @@ import (
1011
"github.com/omec-project/webconsole/backend/logger"
1112
)
1213

13-
var vaultClient *vault.Client
14-
var mutexVaultClient sync.Mutex
14+
var (
15+
vaultClient *vault.Client
16+
mutexVaultClient sync.Mutex
17+
)
1518

1619
// GetVaultClient creates and returns a configured Vault API client
1720
func GetVaultClient() (*vault.Client, error) {
@@ -22,6 +25,10 @@ func GetVaultClient() (*vault.Client, error) {
2225
return vaultClient, nil
2326
}
2427

28+
if factory.WebUIConfig == nil || factory.WebUIConfig.Configuration.Vault == nil {
29+
return nil, errors.New("error: Vault Configuration Not Available")
30+
}
31+
2532
logger.AppLog.Infof("Creating new Vault client for URI: %s", factory.WebUIConfig.Configuration.Vault.VaultUri)
2633

2734
config := vault.DefaultConfig()

backend/ssm/apiclient/vault_client_test.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -83,24 +83,24 @@ mbkm0oeQ/kmUoe82o/yXmbkm0oeQ/kmUoe82o/yXmbkm0oeQ/kmUoe82o/yXmbkm
8383
0oeQ/kmUoe82o/yXmbkm0oeQ/kmUoe82o/yXmbkm0oeQ/kmUoe82o/yXmbkm
8484
-----END PRIVATE KEY-----`
8585

86-
if _, err := crt.WriteString(crtContent); err != nil {
86+
if _, err = crt.WriteString(crtContent); err != nil {
8787
t.Fatalf("cannot write to temp crt file: %v", err)
8888
}
89-
if err := crt.Close(); err != nil {
89+
if err = crt.Close(); err != nil {
9090
t.Fatalf("cannot close temp crt file: %v", err)
9191
}
9292

93-
if _, err := key.WriteString(keyContent); err != nil {
93+
if _, err = key.WriteString(keyContent); err != nil {
9494
t.Fatalf("cannot write to temp key file: %v", err)
9595
}
96-
if err := key.Close(); err != nil {
96+
if err = key.Close(); err != nil {
9797
t.Fatalf("cannot close temp key file: %v", err)
9898
}
9999

100-
if _, err := ca.WriteString(crtContent); err != nil {
100+
if _, err = ca.WriteString(crtContent); err != nil {
101101
t.Fatalf("cannot write to temp ca file: %v", err)
102102
}
103-
if err := ca.Close(); err != nil {
103+
if err = ca.Close(); err != nil {
104104
t.Fatalf("cannot close temp ca file: %v", err)
105105
}
106106

backend/ssm/apiclient/vault_login_test.go

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ func TestLoginVaultAppRoleSuccess(t *testing.T) {
1717
t.Fatalf("unexpected path: %s", r.URL.Path)
1818
}
1919
w.WriteHeader(http.StatusOK)
20-
_, _ = w.Write([]byte(`{"auth":{"client_token":"tok-approle","accessor":"acc"}}`))
20+
if _, err := w.Write([]byte(`{"auth":{"client_token":"tok-approle","accessor":"acc"}}`)); err != nil {
21+
t.Fatalf("Failed to write response: %v", err)
22+
}
2123
}))
2224
defer server.Close()
2325

@@ -43,15 +45,20 @@ func TestLoginVaultKubernetesSuccess(t *testing.T) {
4345
t.Fatalf("cannot create temp jwt file: %v", err)
4446
}
4547
defer os.Remove(jwtFile.Name())
46-
_, _ = jwtFile.WriteString("dummy-jwt")
48+
if _, err = jwtFile.WriteString("dummy-jwt"); err != nil {
49+
t.Fatalf("Failed to write JWT file: %v", err)
50+
}
4751
jwtFile.Close()
4852

4953
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
5054
if r.URL.Path != "/v1/auth/kubernetes/login" {
5155
t.Fatalf("unexpected path: %s", r.URL.Path)
5256
}
5357
w.WriteHeader(http.StatusOK)
54-
_, _ = w.Write([]byte(`{"auth":{"client_token":"tok-k8s","accessor":"acc"}}`))
58+
_, err = w.Write([]byte(`{"auth":{"client_token":"tok-k8s","accessor":"acc"}}`))
59+
if err != nil {
60+
t.Fatalf("Failed to write response: %v", err)
61+
}
5562
}))
5663
defer server.Close()
5764

@@ -77,7 +84,10 @@ func TestLoginVaultMTLSSuccess(t *testing.T) {
7784
t.Fatalf("unexpected path: %s", r.URL.Path)
7885
}
7986
w.WriteHeader(http.StatusOK)
80-
_, _ = w.Write([]byte(`{"auth":{"client_token":"tok-mtls","accessor":"acc"}}`))
87+
_, err := w.Write([]byte(`{"auth":{"client_token":"tok-mtls","accessor":"acc"}}`))
88+
if err != nil {
89+
t.Fatalf("Failed to write response: %v", err)
90+
}
8191
}))
8292
defer server.Close()
8393

@@ -104,17 +114,25 @@ func TestLoginVaultPrefersK8s(t *testing.T) {
104114
t.Fatalf("cannot create temp jwt file: %v", err)
105115
}
106116
defer os.Remove(jwtFile.Name())
107-
_, _ = jwtFile.WriteString("dummy-jwt")
117+
if _, err = jwtFile.WriteString("dummy-jwt"); err != nil {
118+
t.Fatalf("Failed to write JWT file: %v", err)
119+
}
108120
jwtFile.Close()
109121

110122
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
111123
switch r.URL.Path {
112124
case "/v1/auth/kubernetes/login":
113125
w.WriteHeader(http.StatusOK)
114-
_, _ = w.Write([]byte(`{"auth":{"client_token":"tok-k8s","accessor":"acc"}}`))
126+
_, err = w.Write([]byte(`{"auth":{"client_token":"tok-k8s","accessor":"acc"}}`))
127+
if err != nil {
128+
t.Fatalf("Failed to write response: %v", err)
129+
}
115130
case "/v1/auth/approle/login":
116131
w.WriteHeader(http.StatusInternalServerError)
117-
_, _ = w.Write([]byte(`{"errors":["should not hit approle"]}`))
132+
_, err = w.Write([]byte(`{"errors":["should not hit approle"]}`))
133+
if err != nil {
134+
t.Fatalf("Failed to write response: %v", err)
135+
}
118136
default:
119137
t.Fatalf("unexpected path: %s", r.URL.Path)
120138
}

backend/ssm/ssm_sync/create_interface.go

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,14 @@ type CreateAES128SSM struct{}
1717
func (c *CreateAES128SSM) CreateNewKeySSM(keyLabel string, id int32) (configmodels.K4, error) {
1818
logger.AppLog.Infof("Creating new AES-128 key in SSM with label %s, id %d", keyLabel, id)
1919

20-
var genAESKeyRequest ssm_models.GenAESKeyRequest = ssm_models.GenAESKeyRequest{
20+
genAESKeyRequest := ssm_models.GenAESKeyRequest{
2121
Id: id,
2222
Bits: 128,
2323
}
2424

2525
apiClient := apiclient.GetSSMAPIClient()
2626

2727
_, r, err := apiClient.KeyManagementAPI.GenerateAESKey(apiclient.AuthContext).GenAESKeyRequest(genAESKeyRequest).Execute()
28-
2928
if err != nil {
3029
logger.AppLog.Errorf("Error when calling `KeyManagementAPI.GenerateAESKey`: %v", err)
3130
logger.AppLog.Errorf("Full HTTP response: %v", r)
@@ -45,15 +44,14 @@ type CreateAES256SSM struct{}
4544
func (c *CreateAES256SSM) CreateNewKeySSM(keyLabel string, id int32) (configmodels.K4, error) {
4645
logger.AppLog.Infof("Creating new AES-256 key in SSM with label %s, id %d", keyLabel, id)
4746

48-
var genAESKeyRequest ssm_models.GenAESKeyRequest = ssm_models.GenAESKeyRequest{
47+
genAESKeyRequest := ssm_models.GenAESKeyRequest{
4948
Id: id,
5049
Bits: 256,
5150
}
5251

5352
apiClient := apiclient.GetSSMAPIClient()
5453

5554
_, r, err := apiClient.KeyManagementAPI.GenerateAESKey(apiclient.AuthContext).GenAESKeyRequest(genAESKeyRequest).Execute()
56-
5755
if err != nil {
5856
logger.AppLog.Errorf("Error when calling `KeyManagementAPI.GenerateAESKey`: %v", err)
5957
logger.AppLog.Errorf("Full HTTP response: %v", r)
@@ -73,13 +71,12 @@ type CreateDes3SSM struct{}
7371
func (c *CreateDes3SSM) CreateNewKeySSM(keyLabel string, id int32) (configmodels.K4, error) {
7472
logger.AppLog.Infof("Creating new DES3 key in SSM with label %s, id %d", keyLabel, id)
7573

76-
var genDES3KeyRequest ssm_models.GenDES3KeyRequest = ssm_models.GenDES3KeyRequest{
74+
genDES3KeyRequest := ssm_models.GenDES3KeyRequest{
7775
Id: id,
7876
}
7977

8078
apiClient := apiclient.GetSSMAPIClient()
8179
_, r, err := apiClient.KeyManagementAPI.GenerateDES3Key(apiclient.AuthContext).GenDES3KeyRequest(genDES3KeyRequest).Execute()
82-
8380
if err != nil {
8481
logger.AppLog.Errorf("Error when calling `KeyManagementAPI.GenerateDES3Key`: %v", err)
8582
logger.AppLog.Errorf("Full HTTP response: %v", r)
@@ -99,13 +96,12 @@ type CreateDesSSM struct{}
9996
func (c *CreateDesSSM) CreateNewKeySSM(keyLabel string, id int32) (configmodels.K4, error) {
10097
logger.AppLog.Infof("Creating new DES key in SSM with label %s, id %d", keyLabel, id)
10198

102-
var genDESKeyRequest ssm_models.GenDESKeyRequest = ssm_models.GenDESKeyRequest{
99+
genDESKeyRequest := ssm_models.GenDESKeyRequest{
103100
Id: id,
104101
}
105102

106103
apiClient := apiclient.GetSSMAPIClient()
107104
_, r, err := apiClient.KeyManagementAPI.GenerateDESKey(apiclient.AuthContext).GenDESKeyRequest(genDESKeyRequest).Execute()
108-
109105
if err != nil {
110106
logger.AppLog.Errorf("Error when calling `KeyManagementAPI.GenerateDESKey`: %v", err)
111107
logger.AppLog.Errorf("Full HTTP response: %v", r)
Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package ssmsync
22

33
// Compile-time checks to ensure creators implement CreateKeySSM.
4-
var _ CreateKeySSM = (*CreateAES128SSM)(nil)
5-
var _ CreateKeySSM = (*CreateAES256SSM)(nil)
6-
var _ CreateKeySSM = (*CreateDes3SSM)(nil)
7-
var _ CreateKeySSM = (*CreateDesSSM)(nil)
4+
var (
5+
_ CreateKeySSM = (*CreateAES128SSM)(nil)
6+
_ CreateKeySSM = (*CreateAES256SSM)(nil)
7+
_ CreateKeySSM = (*CreateDes3SSM)(nil)
8+
_ CreateKeySSM = (*CreateDesSSM)(nil)
9+
)

0 commit comments

Comments
 (0)