1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6 "context"
7 "crypto/ed25519"
8 "crypto/rand"
9 "errors"
10 "fmt"
11 "strings"
12
13 "bnema.dev/ermite/internal/domain"
14 "bnema.dev/ermite/internal/ports"
15)
16
17const noSecretsKeyDetail = "the server has no ERMITE_SECRETS_KEY, so it cannot store the mirror key"
18
19// ShowKey lazily generates the server's mirror key for authenticated callers.
20func (m *Mirrors) ShowKey(ctx context.Context, p domain.Principal) (domain.MirrorPublicKey, error) {
21 if p.IsAnonymous() {
22 return domain.MirrorPublicKey{}, domain.ErrUnauthenticated
23 }
24 if m.cfg.Sealer == nil {
25 return domain.MirrorPublicKey{}, fmt.Errorf("%w: %s", domain.ErrPreconditionFailed, noSecretsKeyDetail)
26 }
27 m.keyMu.Lock()
28 defer m.keyMu.Unlock()
29 if err := m.loadKey(ctx, true); err != nil {
30 return domain.MirrorPublicKey{}, err
31 }
32 return m.publicKeyLocked(), nil
33}
34
35// RotateKey immediately replaces the mirror key and returns the replaced one (zero when there
36// was none, or when it could not be opened). Remote authorization must be updated separately.
37func (m *Mirrors) RotateKey(ctx context.Context, p domain.Principal) (ports.MirrorKeyRotation, error) {
38 if p.IsAnonymous() {
39 return ports.MirrorKeyRotation{}, domain.ErrUnauthenticated
40 }
41 if !p.HasOwnerRights() {
42 return ports.MirrorKeyRotation{}, domain.ErrForbidden
43 }
44 if m.cfg.Sealer == nil {
45 return ports.MirrorKeyRotation{}, fmt.Errorf("%w: %s", domain.ErrPreconditionFailed, noSecretsKeyDetail)
46 }
47 m.keyMu.Lock()
48 defer m.keyMu.Unlock()
49 var previous domain.MirrorPublicKey
50 // A missing key is not created just to be replaced, and a stored key that cannot be read
51 // or opened must not prevent its replacement.
52 if err := m.loadKey(ctx, false); err == nil {
53 previous = m.publicKeyLocked()
54 }
55 if err := m.storeNewKey(ctx, false); err != nil {
56 return ports.MirrorKeyRotation{}, err
57 }
58 return ports.MirrorKeyRotation{Key: m.publicKeyLocked(), Previous: previous}, nil
59}
60
61func (m *Mirrors) publicKeyLocked() domain.MirrorPublicKey {
62 host := strings.TrimPrefix(domain.MirrorKeyComment(m.cfg.PublicURL), "ermite-mirror@")
63 return domain.MirrorPublicKeyOf(m.key.Public().(ed25519.PublicKey), host, m.keyCreated)
64}
65
66// privateKey returns a copy so a transport cannot mutate the cached key. Failures are
67// *domain.MirrorError of class internal.
68func (m *Mirrors) privateKey(ctx context.Context) (ed25519.PrivateKey, error) {
69 if m.cfg.Sealer == nil {
70 return nil, &domain.MirrorError{Class: domain.MirrorClassInternal, Detail: noSecretsKeyDetail}
71 }
72 m.keyMu.Lock()
73 defer m.keyMu.Unlock()
74 if err := m.loadKey(ctx, true); err != nil {
75 detail := "cannot read the mirror key"
76 if errors.Is(err, domain.ErrPreconditionFailed) {
77 detail = err.Error()
78 }
79 return nil, &domain.MirrorError{Class: domain.MirrorClassInternal, Detail: detail}
80 }
81 return append(ed25519.PrivateKey(nil), m.key...), nil
82}
83
84// loadKey is called with keyMu held and a sealer present: it caches the stored key, creating
85// one when none exists and create is set (ErrNotFound otherwise).
86func (m *Mirrors) loadKey(ctx context.Context, create bool) error {
87 if m.key != nil {
88 return nil
89 }
90 sealed, created, err := m.cfg.Keys.GetMirrorKey(ctx)
91 if err == nil {
92 seed, err := m.cfg.Sealer.Open(sealed, []byte(domain.MirrorKeyPath))
93 if err != nil {
94 return fmt.Errorf("%w: cannot open the stored mirror key", domain.ErrPreconditionFailed)
95 }
96 if len(seed) != ed25519.SeedSize {
97 return fmt.Errorf("%w: invalid mirror key seed", domain.ErrPreconditionFailed)
98 }
99 m.key, m.keyCreated = ed25519.NewKeyFromSeed(seed), created
100 return nil
101 }
102 if !errors.Is(err, domain.ErrNotFound) {
103 return fmt.Errorf("read mirror key: %w", err)
104 }
105 if !create {
106 return err
107 }
108 err = m.storeNewKey(ctx, true)
109 if errors.Is(err, domain.ErrAlreadyExists) {
110 return m.loadKey(ctx, true) // another instance created it first
111 }
112 return err
113}
114
115// storeNewKey generates, seals and persists a key, caching it only once persisted.
116func (m *Mirrors) storeNewKey(ctx context.Context, ifAbsent bool) error {
117 _, key, err := ed25519.GenerateKey(rand.Reader)
118 if err != nil {
119 return fmt.Errorf("generate mirror key: %w", err)
120 }
121 created := m.cfg.Clock.Now().UTC()
122 sealed := m.cfg.Sealer.Seal(key.Seed(), []byte(domain.MirrorKeyPath))
123 if err := m.cfg.Keys.PutMirrorKey(ctx, sealed, created, ifAbsent); err != nil {
124 if errors.Is(err, domain.ErrAlreadyExists) {
125 return err
126 }
127 return fmt.Errorf("store mirror key: %w", err)
128 }
129 m.key, m.keyCreated = key, created
130 return nil
131}