1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package logic

import (
	"fmt"
	"rss-kakapo/dal"
	"rss-kakapo/shared"
)

// EnsureBirb gives the birb an account if it has none, with a key pair made
// for it, and checks that the account it has can sign.
//
// Keys are made where the account is made, which is what every feed account
// has always done (feedFollower.AddAccount): the identity of an account comes
// into being with the account and lives in its row, and nothing has to be
// prepared or configured for it. The birb used to be the exception, carrying
// its pair in the configuration, so an instance could not be started without
// one being generated by hand beforehand (and then sitting in a config file
// for as long as the instance lived).
//
// An existing account with no private key is refused rather than given a new
// one. That is what a database restored without its keys looks like, and the
// right answer is not to mint a new identity under the old name: other
// servers have the old public key, and the followers in that same database
// expect it. See CAVEATS in rss-kakapo(1).
func EnsureBirb(cfg *shared.Config, repo dal.IRepo, keyStore IKeyStore, clock shared.Clock, logger shared.ILogger) error {

	user := cfg.Birb.User
	if user == "" {
		return fmt.Errorf("birb.user is not set; the instance has no built-in account")
	}

	pubKey, privKey, err := keyStore.MakeKeyPair()
	if err != nil {
		return fmt.Errorf("making the birb's key pair: %w", err)
	}
	// The pair is made before it is known whether it is needed, since
	// INSERT-or-nothing is what makes this safe to run at every startup. An
	// unused pair costs one key generation and is simply dropped.
	isNew, err := repo.AddBirbIfNotExist(pubKey, privKey, clock.Now().UTC())
	if err != nil {
		return fmt.Errorf("creating the birb's account: %w", err)
	}
	if isNew {
		logger.Printf("Created the account of the birb '%s', with a new key pair", user)
		return nil
	}

	stored, err := repo.GetPrivKey(user)
	if err != nil {
		return err
	}
	if stored == "" {
		return fmt.Errorf("the account of the birb '%s' has no private key: it cannot sign, and a new key would not be the one other servers know it by", user)
	}
	if _, err := ParsePrivKey(stored); err != nil {
		return fmt.Errorf("the private key of the birb '%s' cannot be read: %w", user, err)
	}
	return nil
}