Skip to content

Commit

Permalink
config package resolve comments
Browse files Browse the repository at this point in the history
Signed-off-by: Junjie Gao <43160897+JeyJeyGao@users.noreply.github.com>
  • Loading branch information
JeyJeyGao committed Jul 28, 2022
1 parent d683a4c commit d8e4a67
Show file tree
Hide file tree
Showing 9 changed files with 118 additions and 60 deletions.
52 changes: 41 additions & 11 deletions config/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ var (
SigningKeysPath string

// configInfo is the information of config.json
configInfo *ConfigFile
configOnce sync.Once
configInfo *Config
configInfoOnce sync.Once

// signingKeysInfo is the information of signingkeys.json
signingKeysInfo *SigningKeys
Expand All @@ -27,16 +27,46 @@ var (
func init() {
ConfigPath = dir.Path.Config()
SigningKeysPath = dir.Path.SigningKeyConfig()
}

// Configuration is the main config struct of notation-go
type Configuration struct {
*Config
*SigningKeys
}

// Configuration is a interface to manage notation config
type Configuration interface {
Save() error
// Save stores sub-configurations to files
func (c *Configuration) Save() error {
if err := c.Config.Save(); err != nil {
return err
}
if err := c.SigningKeys.Save(); err != nil {
return err
}
return nil
}

// LoadOnce returns the previously read config file.
// If previous config file does not exist, it reads the config from file
// or return a default config if not found.
// The returned config is only suitable for read only scenarios for short-lived processes.
func LoadOnce() (*Configuration, error) {
configInfo, err := loadConfigOnce()
if err != nil {
return nil, err
}
signingKeysInfo, err := loadSigningKeysOnce()
if err != nil {
return nil, err
}
return &Configuration{
Config: configInfo,
SigningKeys: signingKeysInfo,
}, nil
}

// Save stores the config to file
func Save(filePath string, config interface{}) error {
// Save stores the cfg struct to file
func Save(filePath string, cfg interface{}) error {
dir := filepath.Dir(filePath)
if err := os.MkdirAll(dir, 0700); err != nil {
return err
Expand All @@ -48,15 +78,15 @@ func Save(filePath string, config interface{}) error {
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
return encoder.Encode(config)
return encoder.Encode(cfg)
}

// Load reads the config from file
func Load(filePath string, config interface{}) error {
// Load reads file, parses json and stores in cfg struct
func Load(filePath string, cfg interface{}) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
return json.NewDecoder(file).Decode(config)
return json.NewDecoder(file).Decode(cfg)
}
30 changes: 16 additions & 14 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ func (c CertificateReference) Is(name string) bool {
return c.Name == name
}

// ConfigFile reflects the config file.
// Config reflects the config file.
// Specification: https://github.com/notaryproject/notation/pull/76
type ConfigFile struct {
type Config struct {
VerificationCertificates VerificationCertificates `json:"verificationCerts"`
InsecureRegistries []string `json:"insecureRegistries"`
CredentialsStore string `json:"credsStore,omitempty"`
CredentialHelpers map[string]string `json:"credHelpers,omitempty"`
}

// VerificationCertificates is a collection of public certs used for verification.
Expand All @@ -29,20 +31,20 @@ type VerificationCertificates struct {
}

// NewConfig creates a new config file
func NewConfig() *ConfigFile {
return &ConfigFile{
func NewConfig() *Config {
return &Config{
InsecureRegistries: []string{},
}
}

// Save stores the config to file
func (f *ConfigFile) Save() error {
return Save(ConfigPath, f)
func (c *Config) Save() error {
return Save(ConfigPath, c)
}

// LoadConfig reads the config from file or return a default config if not found.
func LoadConfig() (*ConfigFile, error) {
var config ConfigFile
// loadConfig reads the config from file or return a default config if not found.
func loadConfig() (*Config, error) {
var config Config
err := Load(ConfigPath, &config)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
Expand All @@ -53,14 +55,14 @@ func LoadConfig() (*ConfigFile, error) {
return &config, nil
}

// LoadConfigOnce returns the previously read config file.
// If previous config file does not exists, it reads the config from file
// loadConfigOnce returns the previously read config file.
// If previous config file does not exist, it reads the config from file
// or return a default config if not found.
// The returned config is only suitable for read only scenarios for short-lived processes.
func LoadConfigOnce() (*ConfigFile, error) {
func loadConfigOnce() (*Config, error) {
var err error
configOnce.Do(func() {
configInfo, err = LoadConfig()
configInfoOnce.Do(func() {
configInfo, err = loadConfig()
})
return configInfo, err
}
16 changes: 8 additions & 8 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const (
nonexistentPath = "./testdata/nonexistent.json"
)

var sampleConfig = &ConfigFile{
var sampleConfig = &Config{
VerificationCertificates: VerificationCertificates{
Certificates: []CertificateReference{
{
Expand All @@ -31,7 +31,7 @@ var sampleConfig = &ConfigFile{
},
}

func TestLoadConfig(t *testing.T) {
func TestLoadFile(t *testing.T) {
t.Cleanup(func() {
// restore path
ConfigPath = dir.Path.Config()
Expand All @@ -42,7 +42,7 @@ func TestLoadConfig(t *testing.T) {
tests := []struct {
name string
args args
want *ConfigFile
want *Config
wantErr bool
}{
{
Expand All @@ -61,27 +61,27 @@ func TestLoadConfig(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ConfigPath = tt.args.filePath
got, err := LoadConfig()
got, err := loadConfig()
if (err != nil) != tt.wantErr {
t.Errorf("LoadConfig() error = %v, wantErr %v", err, tt.wantErr)
t.Errorf("loadFile() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("LoadConfig() = %v, want %v", got, tt.want)
t.Errorf("loadFile() = %v, want %v", got, tt.want)
}
})
}
}

func TestSaveConfigFile(t *testing.T) {
func TestSaveFile(t *testing.T) {
t.Cleanup(func() {
// restore path
ConfigPath = dir.Path.Config()
})
root := t.TempDir()
ConfigPath = filepath.Join(root, "config.json")
sampleConfig.Save()
config, err := LoadConfig()
config, err := loadConfig()
if err != nil {
t.Fatal("Load config file from temp dir failed")
}
Expand Down
12 changes: 6 additions & 6 deletions config/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ func NewSigningKeys() *SigningKeys {
return &SigningKeys{Keys: []KeySuite{}}
}

// LoadSigningKeys reads the config from file
// loadSigningKeys reads the config from file
// or return a default config if not found.
func LoadSigningKeys() (*SigningKeys, error) {
func loadSigningKeys() (*SigningKeys, error) {
var config SigningKeys
err := Load(SigningKeysPath, &config)
if err != nil {
Expand All @@ -62,14 +62,14 @@ func LoadSigningKeys() (*SigningKeys, error) {
return &config, nil
}

// LoadSigningKeysOnce returns the previously read config file.
// If previous config file does not exists, it reads the config from file
// loadSigningKeysOnce returns the previously read config file.
// If previous config file does not exist, it reads the config from file
// or return a default config if not found.
// The returned config is only suitable for read only scenarios for short-lived processes.
func LoadSigningKeysOnce() (*SigningKeys, error) {
func loadSigningKeysOnce() (*SigningKeys, error) {
var err error
signingKeysInfoOnce.Do(func() {
signingKeysInfo, err = LoadSigningKeys()
signingKeysInfo, err = loadSigningKeys()
})
return signingKeysInfo, err
}
4 changes: 2 additions & 2 deletions config/keys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func TestLoadSigningKeysInfo(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
SigningKeysPath = tt.args.filePath
got, err := LoadSigningKeys()
got, err := loadSigningKeys()
if err != nil {
t.Errorf("LoadSigningKeysInfo() error = %v", err)
return
Expand All @@ -90,7 +90,7 @@ func TestSaveSigningKeys(t *testing.T) {
root := t.TempDir()
SigningKeysPath = filepath.Join(root, "signingkeys.json")
sampleSigningKeysInfo.Save()
info, err := LoadSigningKeys()
info, err := loadSigningKeys()
if err != nil {
t.Fatal("Load signingkeys.json from temp dir failed.")
}
Expand Down
4 changes: 2 additions & 2 deletions config/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ var (

// IsRegistryInsecure checks whether the registry is in the list of insecure registries.
func IsRegistryInsecure(target string) bool {
config, err := LoadConfigOnce()
config, err := loadConfigOnce()
if err != nil {
return false
}
Expand All @@ -27,7 +27,7 @@ func IsRegistryInsecure(target string) bool {
// ResolveKey resolves the key by name.
// The default key is attempted if name is empty.
func ResolveKey(name string) (KeySuite, error) {
config, err := LoadSigningKeysOnce()
config, err := loadSigningKeysOnce()
if err != nil {
return KeySuite{}, err
}
Expand Down
8 changes: 6 additions & 2 deletions dir/fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,14 @@ func (u unionDirFS) ReadDir(name string) ([]fs.DirEntry, error) {
}

// PluginFS returns the UnionDirFS for notation plugins
// if dirs is set, use dirs as the directories for plugins
// if dirs is not set, use build-in directory structure for plugins
func PluginFS(dirs ...string) UnionDirFS {
var rootedFsys []RootedFS
dirs = append(dirs, filepath.Join(userLibexec, "plugins"))
dirs = append(dirs, filepath.Join(systemLibexec, "plugins"))
if len(dirs) == 0 {
dirs = append(dirs, filepath.Join(userLibexec, "plugins"))
dirs = append(dirs, filepath.Join(systemLibexec, "plugins"))
}
for _, dir := range dirs {
rootedFsys = append(rootedFsys, NewRootedFS(dir, nil))
}
Expand Down
34 changes: 28 additions & 6 deletions dir/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,37 @@ package dir

import (
"errors"
"fmt"
"io/fs"

"github.com/opencontainers/go-digest"
)

const (
// SignatureExtension defines the extension of the signature files
SignatureExtension = ".sig"
// CertificateExtension defines the extension of the certificate files
CertificateExtension = ".crt"

// ConfigFile is the name of config file
ConfigFile = "config.json"

// KeyExtension defines the extension of the key files
KeyExtension = ".key"

// LocalKeysDir is the directory name for local key store
LocalKeysDir = "localkeys"

// SignatureExtension defines the extension of the signature files
SignatureExtension = ".sig"

// SignatureStoreDirName is the name of the signature store directory
SignatureStoreDirName = "signatures"

// SigningKeysFile is the file name of signing key info
SigningKeysFile = "signingkeys.json"

// TrustPolicyFile is the file name of trust policy info
TrustPolicyFile = "trustpolicy.json"

// TrustStoreDir is the directory name of trust store
TrustStoreDir = "truststore"
)
Expand Down Expand Up @@ -46,8 +61,11 @@ func (p *PathManager) Config() string {

// LocalKey returns path of the local private keys or certificate
// in the localkeys directory
func (p *PathManager) Localkey(keyName string) string {
return errorHandler(p.UserConfigFS.GetPath(LocalKeysDir, keyName))
func (p *PathManager) Localkey(name string, extension string) string {
if extension != KeyExtension && extension != CertificateExtension {
panic(fmt.Sprintf("doesn't support the extension `%s`", extension))
}
return errorHandler(p.UserConfigFS.GetPath(LocalKeysDir, name+extension))
}

// SigningKeyConfig return the path of signingkeys.json files
Expand All @@ -68,7 +86,7 @@ func (p *PathManager) X509TrustStore(prefix, namedStore string) string {
// CachedSignature returns the cached signature file path
func (p *PathManager) CachedSignature(manifestDigest, signatureDigest digest.Digest) string {
return errorHandler(p.CacheFS.GetPath(
"signatures",
SignatureStoreDirName,
manifestDigest.Algorithm().String(),
manifestDigest.Encoded(),
signatureDigest.Algorithm().String(),
Expand All @@ -79,8 +97,12 @@ func (p *PathManager) CachedSignature(manifestDigest, signatureDigest digest.Dig
// CachedSignatureRoot returns the cached signature root path
func (p *PathManager) CachedSignatureRoot(manifestDigest digest.Digest) string {
return errorHandler(p.CacheFS.GetPath(
"signatures",
SignatureStoreDirName,
manifestDigest.Algorithm().String(),
manifestDigest.Encoded(),
))
}

func (p *PathManager) CachedSignatureStoreDirPath() string {
return errorHandler(p.CacheFS.GetPath(SignatureStoreDirName))
}
18 changes: 9 additions & 9 deletions plugin/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,12 @@ type DescribeKeyResponse struct {

// GenerateSignatureRequest contains the parameters passed in a generate-signature request.
type GenerateSignatureRequest struct {
ContractVersion string `json:"contractVersion"`
KeyID string `json:"keyId"`
KeySpec signer.KeySpec `json:"keySpec"`
Hash string `json:"hashAlgorithm"`
Payload []byte `json:"payload"`
PluginConfig map[string]string `json:"pluginConfig,omitempty"`
ContractVersion string `json:"contractVersion"`
KeyID string `json:"keyId"`
KeySpec signer.KeySpec `json:"keySpec"`
Hash string `json:"hashAlgorithm"`
Payload []byte `json:"payload"`
PluginConfig map[string]string `json:"pluginConfig,omitempty"`
}

func (GenerateSignatureRequest) Command() Command {
Expand All @@ -136,9 +136,9 @@ func (GenerateSignatureRequest) Command() Command {

// GenerateSignatureResponse is the response of a generate-signature request.
type GenerateSignatureResponse struct {
KeyID string `json:"keyId"`
Signature []byte `json:"signature"`
SigningAlgorithm signer.SignatureAlgorithm `json:"signingAlgorithm"`
KeyID string `json:"keyId"`
Signature []byte `json:"signature"`
SigningAlgorithm signer.SignatureAlgorithm `json:"signingAlgorithm"`

// Ordered list of certificates starting with leaf certificate
// and ending with root certificate.
Expand Down

0 comments on commit d8e4a67

Please sign in to comment.