...

Source file src/edge-infra.dev/pkg/sds/emergencyaccess/emulator/workspace.go

Documentation: edge-infra.dev/pkg/sds/emergencyaccess/emulator

     1  package emulator
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"io/fs"
     8  	"os"
     9  
    10  	"github.com/go-logr/logr"
    11  )
    12  
    13  const (
    14  	envFilePathDir = "RCLI_WORKSPACE_DIR"
    15  	defaultDir     = "./"
    16  )
    17  
    18  func GetWorkspaceDir(logger logr.Logger) (string, error) {
    19  	dir := os.Getenv(envFilePathDir)
    20  	// If env var is empty or doesn't exist, use default
    21  	if dir == "" {
    22  		logger.Info("Environment variable was not set. Using default value", "envvar", envFilePathDir)
    23  		dir = defaultDir
    24  	}
    25  
    26  	if dir != defaultDir {
    27  		// If directory does not exist, return error
    28  		// Need read, write, and execute permissions
    29  		fi, err := os.Stat(dir)
    30  		if errors.Is(err, fs.ErrNotExist) {
    31  			return "", fmt.Errorf("workspace directory could not be found: %v", err)
    32  		}
    33  		if err != nil {
    34  			return "", err
    35  		}
    36  
    37  		perms := fi.Mode()
    38  		// Check for specific permissions: user rwx
    39  		if perms&0b111000000 != 0b111000000 {
    40  			return "", fmt.Errorf("workspace directory perms aren't accessible by remotecli")
    41  		}
    42  	}
    43  
    44  	logger.Info("Workspace directory successfully set", "workspace", dir)
    45  	return dir, nil
    46  }
    47  
    48  type workspace struct {
    49  	ProjectID string `json:"project_ID"`
    50  	BannerID  string `json:"banner_ID"`
    51  	StoreID   string `json:"store_ID"`
    52  
    53  	DisablePerSessionSubscription bool `json:"disable_per_session_subscription"`
    54  }
    55  
    56  func newWorkspace(path string) (*workspace, error) {
    57  	var ws workspace
    58  
    59  	data, err := os.ReadFile(path)
    60  	if err != nil {
    61  		return &ws, err
    62  	}
    63  	err = json.Unmarshal(data, &ws)
    64  	if err != nil {
    65  		return &ws, err
    66  	}
    67  	return &ws, nil
    68  }
    69  
    70  func (ws workspace) save(path string) error {
    71  	data, err := json.Marshal(ws)
    72  	if err != nil {
    73  		return err
    74  	}
    75  
    76  	err = os.WriteFile(path, data, 0644)
    77  	if err != nil {
    78  		return err
    79  	}
    80  	return nil
    81  }
    82  
    83  func (ws workspace) string() string {
    84  	strings := []string{ws.BannerID, ws.StoreID}
    85  
    86  	for enum, item := range strings {
    87  		if item == "" {
    88  			strings[enum] = UNSET
    89  		}
    90  	}
    91  
    92  	return fmt.Sprintf("BannerID: %s, StoreID: %s\n", strings[0], strings[1])
    93  }
    94  

View as plain text