generate identity
This commit is contained in:
+60
-1
@@ -1,9 +1,12 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mediarr/cluster"
|
||||
"mediarr/database"
|
||||
"mediarr/ident"
|
||||
"time"
|
||||
@@ -29,7 +32,63 @@ func (n *Node) Up() error {
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return n.ensureClusterIdentity(ctx)
|
||||
|
||||
}
|
||||
|
||||
func (n *Node) ensureClusterIdentity(ctx context.Context) error {
|
||||
|
||||
principal, err := n.db.Queries.GetClusterPrincipal(ctx)
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
identity, loadErr := cluster.LoadOrCreate(n.clusterKeyPath, false)
|
||||
if loadErr != nil {
|
||||
return fmt.Errorf("cluster : principal présent en base mais clé indisponible : %w", loadErr)
|
||||
}
|
||||
|
||||
if !bytes.Equal(principal.PublicKey, identity.PublicKey) {
|
||||
return errors.New("cluster : la clé publique de cluster.key ne correspond pas au principal en base")
|
||||
}
|
||||
|
||||
n.cluster = identity
|
||||
return nil
|
||||
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
identity, createErr := cluster.LoadOrCreate(n.clusterKeyPath, true)
|
||||
if createErr != nil {
|
||||
return createErr
|
||||
}
|
||||
|
||||
clusterID, idErr := ident.NewV7()
|
||||
if idErr != nil {
|
||||
return idErr
|
||||
}
|
||||
|
||||
_, createErr = n.db.WriteQueries.CreatePrincipal(ctx, database.CreatePrincipalParams{
|
||||
ID: clusterID,
|
||||
Kind: "cluster",
|
||||
Name: "cluster",
|
||||
PublicKey: identity.PublicKeyBytes(),
|
||||
Status: "active",
|
||||
CreatedAt: time.Now().UnixMilli(),
|
||||
})
|
||||
if createErr != nil {
|
||||
existing, getErr := n.db.Queries.GetClusterPrincipal(ctx)
|
||||
if getErr == nil && bytes.Equal(existing.PublicKey, identity.PublicKey) {
|
||||
n.cluster = identity
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("cluster : création du principal : %w", createErr)
|
||||
}
|
||||
|
||||
n.cluster = identity
|
||||
return nil
|
||||
|
||||
default:
|
||||
return fmt.Errorf("cluster : lecture du principal : %w", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user