generate identity
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const privateKeyPEMType = "PRIVATE KEY"
|
||||
|
||||
// Identity est l'identité racine du cluster. La clé privée ne doit jamais
|
||||
// être persistée en base ni journalisée.
|
||||
type Identity struct {
|
||||
PrivateKey ed25519.PrivateKey
|
||||
PublicKey ed25519.PublicKey
|
||||
Path string
|
||||
}
|
||||
|
||||
// LoadOrCreate charge la clé privée PKCS#8 PEM présente dans path. Si elle
|
||||
// n'existe pas et que allowCreate est vrai, une nouvelle paire Ed25519 est
|
||||
// générée et écrite avec les permissions 0600.
|
||||
func LoadOrCreate(path string, allowCreate bool) (Identity, error) {
|
||||
if path == "" {
|
||||
return Identity{}, errors.New("cluster : chemin de clé vide")
|
||||
}
|
||||
|
||||
identity, err := load(path)
|
||||
if err == nil {
|
||||
return identity, nil
|
||||
}
|
||||
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return Identity{}, err
|
||||
}
|
||||
|
||||
if !allowCreate {
|
||||
return Identity{}, fmt.Errorf("cluster : clé absente (%s) et création désactivée", path)
|
||||
}
|
||||
|
||||
return create(path)
|
||||
}
|
||||
|
||||
func load(path string) (Identity, error) {
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return Identity{}, err
|
||||
}
|
||||
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
return Identity{}, fmt.Errorf("cluster : %s est un lien symbolique, refusé", path)
|
||||
}
|
||||
|
||||
if !info.Mode().IsRegular() {
|
||||
return Identity{}, fmt.Errorf("cluster : %s n'est pas un fichier régulier", path)
|
||||
}
|
||||
|
||||
if info.Mode().Perm()&0o077 != 0 {
|
||||
return Identity{}, fmt.Errorf(
|
||||
"cluster : permissions trop larges sur %s (%04o), attendu 0600",
|
||||
path,
|
||||
info.Mode().Perm(),
|
||||
)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return Identity{}, err
|
||||
}
|
||||
|
||||
block, _ := pem.Decode(data)
|
||||
if block == nil {
|
||||
return Identity{}, fmt.Errorf("cluster : %s ne contient pas de PEM valide", path)
|
||||
}
|
||||
|
||||
if block.Type != privateKeyPEMType {
|
||||
return Identity{}, fmt.Errorf("cluster : type PEM %q inattendu", block.Type)
|
||||
}
|
||||
|
||||
parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return Identity{}, fmt.Errorf("cluster : clé PKCS#8 invalide : %w", err)
|
||||
}
|
||||
|
||||
privateKey, ok := parsed.(ed25519.PrivateKey)
|
||||
if !ok {
|
||||
return Identity{}, fmt.Errorf("cluster : clé de type %T, attendu ed25519.PrivateKey", parsed)
|
||||
}
|
||||
|
||||
publicKey, ok := privateKey.Public().(ed25519.PublicKey)
|
||||
if !ok {
|
||||
return Identity{}, errors.New("cluster : clé publique Ed25519 invalide")
|
||||
}
|
||||
|
||||
return Identity{
|
||||
PrivateKey: privateKey,
|
||||
PublicKey: publicKey,
|
||||
Path: path,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func create(path string) (Identity, error) {
|
||||
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return Identity{}, fmt.Errorf("cluster : génération de clé : %w", err)
|
||||
}
|
||||
|
||||
der, err := x509.MarshalPKCS8PrivateKey(privateKey)
|
||||
if err != nil {
|
||||
return Identity{}, fmt.Errorf("cluster : encodage PKCS#8 : %w", err)
|
||||
}
|
||||
|
||||
data := pem.EncodeToMemory(&pem.Block{Type: privateKeyPEMType, Bytes: der})
|
||||
if data == nil {
|
||||
return Identity{}, errors.New("cluster : encodage PEM")
|
||||
}
|
||||
|
||||
dir := filepath.Dir(path)
|
||||
if dir == "" {
|
||||
dir = "."
|
||||
}
|
||||
if dir != "." {
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return Identity{}, fmt.Errorf("cluster : création du répertoire %s : %w", dir, err)
|
||||
}
|
||||
}
|
||||
|
||||
temp, err := os.CreateTemp(dir, ".cluster-key-*")
|
||||
if err != nil {
|
||||
return Identity{}, fmt.Errorf("cluster : création du fichier temporaire : %w", err)
|
||||
}
|
||||
|
||||
tempPath := temp.Name()
|
||||
cleanup := func() {
|
||||
_ = temp.Close()
|
||||
_ = os.Remove(tempPath)
|
||||
}
|
||||
|
||||
if err := temp.Chmod(0o600); err != nil {
|
||||
cleanup()
|
||||
return Identity{}, fmt.Errorf("cluster : permissions du fichier temporaire : %w", err)
|
||||
}
|
||||
|
||||
written, writeErr := temp.Write(data)
|
||||
if writeErr != nil || written != len(data) {
|
||||
cleanup()
|
||||
|
||||
if writeErr != nil {
|
||||
return Identity{}, fmt.Errorf("cluster : écriture de %s : %w", tempPath, writeErr)
|
||||
}
|
||||
|
||||
return Identity{}, fmt.Errorf("cluster : écriture partielle de %s", tempPath)
|
||||
}
|
||||
|
||||
if err := temp.Sync(); err != nil {
|
||||
cleanup()
|
||||
return Identity{}, fmt.Errorf("cluster : synchronisation de %s : %w", tempPath, err)
|
||||
}
|
||||
|
||||
if err := temp.Close(); err != nil {
|
||||
_ = os.Remove(tempPath)
|
||||
return Identity{}, fmt.Errorf("cluster : fermeture de %s : %w", tempPath, err)
|
||||
}
|
||||
|
||||
// Link est atomique et échoue si path existe déjà : on ne peut pas écraser
|
||||
// une clé créée par un autre processus.
|
||||
if err := os.Link(tempPath, path); err != nil {
|
||||
_ = os.Remove(tempPath)
|
||||
|
||||
if errors.Is(err, os.ErrExist) {
|
||||
return load(path)
|
||||
}
|
||||
|
||||
return Identity{}, fmt.Errorf("cluster : installation de %s : %w", path, err)
|
||||
}
|
||||
|
||||
_ = os.Remove(tempPath)
|
||||
|
||||
return Identity{
|
||||
PrivateKey: privateKey,
|
||||
PublicKey: publicKey,
|
||||
Path: path,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (i Identity) PublicKeyBytes() []byte {
|
||||
return append([]byte(nil), i.PublicKey...)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadOrCreateGeneratesAndReloads(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "cluster.key")
|
||||
|
||||
first, err := LoadOrCreate(path, true)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOrCreate (création) : %v", err)
|
||||
}
|
||||
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Stat : %v", err)
|
||||
}
|
||||
if got := info.Mode().Perm(); got != 0o600 {
|
||||
t.Fatalf("permissions = %04o, attendu 0600", got)
|
||||
}
|
||||
|
||||
second, err := LoadOrCreate(path, true)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadOrCreate (relecture) : %v", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(first.PublicKey, second.PublicKey) {
|
||||
t.Fatal("clés publiques différentes après relecture")
|
||||
}
|
||||
if !bytes.Equal(first.PrivateKey, second.PrivateKey) {
|
||||
t.Fatal("clés privées différentes après relecture")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOrCreateNoCreate(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "missing.key")
|
||||
|
||||
if _, err := LoadOrCreate(path, false); err == nil {
|
||||
t.Fatal("LoadOrCreate aurait dû échouer sans création autorisée")
|
||||
}
|
||||
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatalf("le fichier ne devrait pas exister : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOrCreateCorrupt(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "cluster.key")
|
||||
if err := os.WriteFile(path, []byte("pas une clé"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := LoadOrCreate(path, true); err == nil {
|
||||
t.Fatal("LoadOrCreate aurait dû refuser un fichier corrompu")
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(data) != "pas une clé" {
|
||||
t.Fatal("le fichier corrompu a été modifié")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOrCreateRejectsLoosePermissions(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "cluster.key")
|
||||
|
||||
if _, err := LoadOrCreate(path, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := LoadOrCreate(path, true); err == nil {
|
||||
t.Fatal("LoadOrCreate aurait dû refuser des permissions 0644")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOrCreateRejectsSymlink(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "target.key")
|
||||
link := filepath.Join(dir, "cluster.key")
|
||||
|
||||
if _, err := LoadOrCreate(target, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(target, link); err != nil {
|
||||
t.Skipf("symlink non supporté : %v", err)
|
||||
}
|
||||
|
||||
if _, err := LoadOrCreate(link, true); err == nil {
|
||||
t.Fatal("LoadOrCreate aurait dû refuser un lien symbolique")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOrCreateConcurrent(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "cluster.key")
|
||||
|
||||
const goroutines = 16
|
||||
|
||||
type result struct {
|
||||
identity Identity
|
||||
err error
|
||||
}
|
||||
|
||||
results := make(chan result, goroutines)
|
||||
var waitGroup sync.WaitGroup
|
||||
|
||||
for range goroutines {
|
||||
waitGroup.Add(1)
|
||||
|
||||
go func() {
|
||||
defer waitGroup.Done()
|
||||
|
||||
identity, err := LoadOrCreate(path, true)
|
||||
results <- result{identity: identity, err: err}
|
||||
}()
|
||||
}
|
||||
|
||||
waitGroup.Wait()
|
||||
close(results)
|
||||
|
||||
var expected []byte
|
||||
|
||||
for current := range results {
|
||||
if current.err != nil {
|
||||
t.Fatalf("LoadOrCreate concurrent : %v", current.err)
|
||||
}
|
||||
|
||||
publicKey := current.identity.PublicKeyBytes()
|
||||
|
||||
if expected == nil {
|
||||
expected = publicKey
|
||||
continue
|
||||
}
|
||||
|
||||
if !bytes.Equal(expected, publicKey) {
|
||||
t.Fatal("deux processus concurrents ont obtenu des clés différentes")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user