-
Notifications
You must be signed in to change notification settings - Fork 16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Keymanager 'disk' implementation #167
Merged
maxlambrecht
merged 11 commits into
HewlettPackard:main
from
maxlambrecht:keymanager-disk-implementation
May 21, 2023
+267
−43
Merged
Changes from 10 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
8f8ba9d
KeyManager 'disk' implementation
maxlambrecht a4e153b
Add missing blank line
maxlambrecht bd92bc6
Amend comment
maxlambrecht 8f5dd04
Fix locks
maxlambrecht 5941f7a
Remove comment
maxlambrecht 2db4cb4
Amend error messages
maxlambrecht 38ead29
Fix lint error
maxlambrecht 104ab40
Refactor perm into a constant
maxlambrecht 5dcf342
Unexport base keymanager
maxlambrecht d30c5eb
Minor amendment
maxlambrecht 99c71c3
Amend comments
maxlambrecht File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
package keymanager | ||
|
||
import ( | ||
"context" | ||
"crypto" | ||
"crypto/ecdsa" | ||
"crypto/rsa" | ||
"crypto/x509" | ||
"encoding/json" | ||
"encoding/pem" | ||
"errors" | ||
"fmt" | ||
"os" | ||
|
||
"github.com/HewlettPackard/galadriel/pkg/common/cryptoutil" | ||
) | ||
|
||
const keyFilePerm = 0600 | ||
|
||
// Disk extends the base KeyManager to store keys in disk. | ||
type Disk struct { | ||
base | ||
|
||
keysFilePath string | ||
} | ||
|
||
// NewDiskKeyManager creates a new Disk that stores keys in disk. | ||
func NewDiskKeyManager(generator Generator, keysFilePath string) (*Disk, error) { | ||
c := &Config{ | ||
Generator: generator, | ||
} | ||
base := newBase(c) | ||
|
||
diskKeyManager := &Disk{ | ||
base: *base, | ||
keysFilePath: keysFilePath, | ||
} | ||
|
||
err := diskKeyManager.loadKeysFromDisk() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return diskKeyManager, nil | ||
} | ||
|
||
// GenerateKey generates a new key and stores it in disk. | ||
func (d *Disk) GenerateKey(ctx context.Context, keyID string, keyType cryptoutil.KeyType) (Key, error) { | ||
key, err := d.base.GenerateKey(ctx, keyID, keyType) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
err = d.saveKeysToDisk() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return key, nil | ||
} | ||
|
||
func (d *Disk) loadKeysFromDisk() error { | ||
data, err := os.ReadFile(d.keysFilePath) | ||
if err != nil { | ||
return nil // No keys file exists, no error | ||
} | ||
|
||
keys := make(map[string]string) | ||
if err := json.Unmarshal(data, &keys); err != nil { | ||
return fmt.Errorf("failed to unmarshal keys from disk: %w", err) | ||
} | ||
|
||
d.mu.RLock() | ||
defer d.mu.RUnlock() | ||
|
||
for id, keyBytes := range keys { | ||
signer, err := convertToSigner([]byte(keyBytes)) | ||
if err != nil { | ||
return fmt.Errorf("failed to create key entry: %w", err) | ||
} | ||
|
||
d.entries[id] = &KeyEntry{ | ||
PrivateKey: signer, | ||
PublicKey: signer.Public(), | ||
id: id, | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// SaveKeysToDisk saves the keys in the key manager to disk. | ||
func (d *Disk) saveKeysToDisk() error { | ||
d.mu.Lock() | ||
defer d.mu.Unlock() | ||
|
||
keys := make(map[string]string) | ||
for id, entry := range d.entries { | ||
keyBytes, err := x509.MarshalPKCS8PrivateKey(entry.PrivateKey) | ||
if err != nil { | ||
return fmt.Errorf("failed to marshal private key: %w", err) | ||
} | ||
|
||
// Encode PEM block as string | ||
keyPEM := pem.EncodeToMemory(&pem.Block{ | ||
Type: "PRIVATE KEY", | ||
Bytes: keyBytes, | ||
}) | ||
keys[id] = string(keyPEM) | ||
} | ||
|
||
data, err := json.Marshal(keys) | ||
if err != nil { | ||
return fmt.Errorf("failed to serialize keys: %w", err) | ||
} | ||
|
||
if err := os.WriteFile(d.keysFilePath, data, keyFilePerm); err != nil { | ||
return fmt.Errorf("failed to write keys to disk: %w", err) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func convertToSigner(keyBytes []byte) (crypto.Signer, error) { | ||
block, _ := pem.Decode(keyBytes) | ||
if block == nil { | ||
return nil, errors.New("failed to decode PEM block containing private key") | ||
} | ||
|
||
key, err := x509.ParsePKCS8PrivateKey(block.Bytes) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to parse private key: %w", err) | ||
} | ||
|
||
switch key := key.(type) { | ||
case *rsa.PrivateKey: | ||
return key, nil | ||
case *ecdsa.PrivateKey: | ||
return key, nil | ||
default: | ||
return nil, errors.New("unsupported private key type") | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package keymanager | ||
|
||
import ( | ||
"context" | ||
"os" | ||
"path/filepath" | ||
"testing" | ||
|
||
"github.com/HewlettPackard/galadriel/pkg/common/cryptoutil" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestDiskKeyManager(t *testing.T) { | ||
tempDir, err := os.MkdirTemp("", "keymanager_test") | ||
require.NoError(t, err) | ||
defer os.RemoveAll(tempDir) | ||
|
||
dataDir := filepath.Join(tempDir, "keys-test.json") | ||
|
||
// Create a new Disk key manager | ||
keyManager, err := NewDiskKeyManager(nil, dataDir) | ||
require.NoError(t, err) | ||
|
||
// Generate a new key pair | ||
keyID := "key1" | ||
keyType := cryptoutil.RSA2048 | ||
key, err := keyManager.GenerateKey(context.Background(), keyID, keyType) | ||
require.NoError(t, err) | ||
require.NotNil(t, key) | ||
|
||
// Get the generated key | ||
gotKey, err := keyManager.GetKey(context.Background(), keyID) | ||
require.NoError(t, err) | ||
require.NotNil(t, gotKey) | ||
|
||
// Verify the generated key's ID and type | ||
assert.Equal(t, keyID, gotKey.ID()) | ||
|
||
// Verify the generated key's | ||
assert.NotNil(t, gotKey.Signer()) | ||
|
||
// Load the Disk key manager from disk | ||
loadedKeyManager, err := NewDiskKeyManager(nil, dataDir) | ||
require.NoError(t, err) | ||
|
||
// Get the loaded key | ||
loadedKey, err := loadedKeyManager.GetKey(context.Background(), keyID) | ||
require.NoError(t, err) | ||
require.NotNil(t, loadedKey) | ||
|
||
// Verify the loaded key's ID and type | ||
assert.Equal(t, keyID, loadedKey.ID()) | ||
|
||
// Verify the loaded key's | ||
assert.NotNil(t, loadedKey.Signer()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,7 +8,7 @@ import ( | |
"github.com/HewlettPackard/galadriel/pkg/common/cryptoutil" | ||
) | ||
|
||
// KeyManager provides a common interface for managing keys. | ||
// Memory provides a common interface for managing keys. | ||
type KeyManager interface { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Change interface name to match the new comment ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No, the comment is wrong. |
||
// GenerateKey generates a new key with the given ID and key type. | ||
// If a key with that ID already exists, it is overwritten. | ||
|
@@ -18,7 +18,7 @@ type KeyManager interface { | |
// an error is returned. | ||
GetKey(ctx context.Context, id string) (Key, error) | ||
|
||
// GetKeys returns all keys managed by the KeyManager. | ||
// GetKeys returns all keys managed by the Memory. | ||
GetKeys(ctx context.Context) ([]Key, error) | ||
} | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
package keymanager | ||
|
||
// Memory is a key manager that keeps keys in memory. | ||
type Memory struct { | ||
*base | ||
} | ||
|
||
func NewMemoryKeyManager(generator Generator) *Memory { | ||
return &Memory{ | ||
base: newBase(&Config{ | ||
Generator: generator, | ||
}), | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.