Skip to content
Open
54 changes: 54 additions & 0 deletions pkg/certificate/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ package certificate
import (
"context"
"fmt"
"os"
"path/filepath"
"sync"
"time"

Expand All @@ -26,6 +28,7 @@ import (
"github.com/AthenZ/k8s-athenz-sia/v3/third_party/log"
"github.com/AthenZ/k8s-athenz-sia/v3/third_party/util"
"github.com/cenkalti/backoff"
"golang.org/x/sys/unix"
)

type certService struct {
Expand Down Expand Up @@ -71,6 +74,52 @@ func New(ctx context.Context, idCfg *config.IdentityConfig) (daemon.Daemon, erro
var localFileKeyPEM []byte
var localFileIdentity *InstanceIdentity

// validate file
isValidFile := func(file_path string) error {
dir_path := filepath.Dir(file_path)
var target_path string
_, file_err := os.Stat(file_path)
_, dir_err := os.Stat(dir_path)

if file_err == nil {
// validate file path
target_path = file_path
} else if os.IsNotExist(file_err) && dir_err == nil {
// validate dir path
target_path = dir_path
} else {
return fmt.Errorf("file path not exist: %w, %w", file_err, dir_err)
}

err := unix.Access(target_path, unix.W_OK)
if err != nil {
return fmt.Errorf("file permission error: %w", err)
}

return nil
}

// validate files
isValidFiles := func() error {
for _, certFile := range idCfg.ServiceCert.CopperArgos.Cert.Paths {
err := isValidFile(certFile)
if err != nil {
return err
}
}
for _, keyFile := range idCfg.ServiceCert.CopperArgos.Key.Paths {
err := isValidFile(keyFile)
if err != nil {
return err
}
}
err := isValidFile(idCfg.CaCertFile)
if err != nil {
return err
}
return nil
}

// Write files to local file system
writeFiles := func() error {
w := util.NewWriter()
Expand Down Expand Up @@ -209,6 +258,11 @@ func New(ctx context.Context, idCfg *config.IdentityConfig) (daemon.Daemon, erro
}

run := func() error {
err := isValidFiles()
if err != nil {
return err
}

if idCfg.ServiceCert.CopperArgos.Use {
log.Infof("Attempting to request x509 certificate to identity provider[%s]...", idCfg.ServiceCert.CopperArgos.Provider)

Expand Down