gunk-dev/the-valley

state.go

source9b709a18cb1fmain's published tip history
6.0 KiB
1package main
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "crypto/rand"
7 "crypto/x509"
8 "encoding/json"
9 "encoding/pem"
10 "errors"
11 "fmt"
12 "os"
13 "path/filepath"
14 "syscall"
15 "time"
16
17 "the-valley/note"
18)
19
20// The state directory holds:
21//
22// lock held for the whole of a pass
23// key the export key, PKCS #8 in PEM, mode 0400
24// verifier its verifier line, under the signing name
25// acknowledged the export the receiver last said it serves
26const (
27 keyFile = "key"
28 verifierFile = "verifier"
29 acknowledgedFile = "acknowledged"
30)
31
32// lockFile takes an exclusive flock(2) lock on path, waiting for a pass
33// that holds it to finish.
34func lockFile(path string) (func(), error) {
35 f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600)
36 if err != nil {
37 return nil, err
38 }
39 for {
40 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
41 if !errors.Is(err, syscall.EINTR) {
42 break
43 }
44 }
45 if err != nil {
46 f.Close()
47 return nil, fmt.Errorf("could not lock %s: %w", path, err)
48 }
49 return func() { f.Close() }, nil
50}
51
52// loadKey reads the export key from the state directory, or makes one the
53// first time. The key is made under a temporary name and renamed into
54// place, so a start killed half way leaves no key, and the next start
55// makes one. The private key is never printed. Its verifier line is
56// written beside it on every pass, and said whenever it changes: a new key,
57// or a new signing name.
58func (p *publisher) loadKey() (ed25519.PrivateKey, error) {
59 path := filepath.Join(p.cfg.state, keyFile)
60 data, err := os.ReadFile(path)
61 if errors.Is(err, os.ErrNotExist) {
62 data, err = makeKey(path)
63 }
64 if err != nil {
65 return nil, err
66 }
67 block, _ := pem.Decode(data)
68 if block == nil || block.Type != "PRIVATE KEY" {
69 return nil, fmt.Errorf("%s is not a PEM private key", path)
70 }
71 parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes)
72 if err != nil {
73 return nil, fmt.Errorf("%s: %w", path, err)
74 }
75 key, ok := parsed.(ed25519.PrivateKey)
76 if !ok {
77 return nil, fmt.Errorf("%s is not an Ed25519 key", path)
78 }
79 if err := note.CheckName(p.signer); err != nil {
80 return nil, err
81 }
82 line := note.NewVerifierKey(p.signer, key.Public().(ed25519.PublicKey)).String() + "\n"
83 verifier := filepath.Join(p.cfg.state, verifierFile)
84 if old, err := os.ReadFile(verifier); err == nil && bytes.Equal(old, []byte(line)) {
85 return key, nil
86 }
87 if err := writeFile(verifier, []byte(line), 0o644); err != nil {
88 return nil, err
89 }
90 p.say("the export key's verifier line is %s", bytes.TrimSuffix([]byte(line), []byte("\n")))
91 return key, nil
92}
93
94// makeKey makes a new export key at path and returns its PEM.
95func makeKey(path string) ([]byte, error) {
96 _, key, err := ed25519.GenerateKey(rand.Reader)
97 if err != nil {
98 return nil, err
99 }
100 der, err := x509.MarshalPKCS8PrivateKey(key)
101 if err != nil {
102 return nil, err
103 }
104 data := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})
105 if err := writeFile(path, data, 0o400); err != nil {
106 return nil, err
107 }
108 return data, nil
109}
110
111// writeFile writes data to path whole or not at all: to a temporary file
112// beside it, synced, then renamed over it.
113func writeFile(path string, data []byte, mode os.FileMode) error {
114 f, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".new-")
115 if err != nil {
116 return err
117 }
118 defer os.Remove(f.Name())
119 if _, err := f.Write(data); err != nil {
120 f.Close()
121 return err
122 }
123 if err := f.Chmod(mode); err != nil {
124 f.Close()
125 return err
126 }
127 if err := f.Sync(); err != nil {
128 f.Close()
129 return err
130 }
131 if err := f.Close(); err != nil {
132 return err
133 }
134 return os.Rename(f.Name(), path)
135}
136
137// acknowledgedSchema is the acknowledged file's schema.
138const acknowledgedSchema = "valley-web-publish-acknowledged/v1"
139
140// acknowledged is the export the receiver last said it serves: in a
141// commit's reply, or in an inventory whose active export had the same
142// digest. A pass records it only from the receiver's reply, never from an
143// upload it merely attempted.
144type acknowledged struct {
145 Schema string `json:"schema"`
146 Receiver string `json:"receiver"`
147 Destination string `json:"destination"`
148 Digest string `json:"digest"`
149 // Sequence is the receiver's active sequence. No later manifest is
150 // signed with a sequence at or below it.
151 Sequence int64 `json:"sequence"`
152 // At is when the receiver said so, in RFC 3339.
153 At string `json:"at"`
154}
155
156// readAcknowledged reads the last acknowledgement, or none.
157func (p *publisher) readAcknowledged() (acknowledged, error) {
158 data, err := os.ReadFile(filepath.Join(p.cfg.state, acknowledgedFile))
159 if errors.Is(err, os.ErrNotExist) {
160 return acknowledged{}, nil
161 }
162 if err != nil {
163 return acknowledged{}, err
164 }
165 var a acknowledged
166 if err := json.Unmarshal(data, &a); err != nil || a.Schema != acknowledgedSchema {
167 p.warn("%s is not an acknowledgement this publisher wrote; it is set aside", filepath.Join(p.cfg.state, acknowledgedFile))
168 return acknowledged{}, nil
169 }
170 return a, nil
171}
172
173// covers reports whether the acknowledgement makes an upload of the export
174// with digest needless: the same receiver and destination acknowledged the
175// same digest less than recheck ago. Past recheck the publisher asks
176// again, so a receiver that lost its state is synchronised again within
177// recheck.
178func (a acknowledged) covers(cfg config, digest string, now time.Time, recheck time.Duration) bool {
179 if a.Receiver != cfg.receiver || a.Destination != cfg.destination || a.Digest != digest {
180 return false
181 }
182 at, err := time.Parse(time.RFC3339Nano, a.At)
183 return err == nil && now.Sub(at) < recheck && !at.After(now)
184}
185
186// recordAcknowledged writes an acknowledgement the receiver gave.
187func (p *publisher) recordAcknowledged(digest string, sequence int64) error {
188 a := acknowledged{
189 Schema: acknowledgedSchema, Receiver: p.cfg.receiver, Destination: p.cfg.destination,
190 Digest: digest, Sequence: sequence, At: p.now().UTC().Format(time.RFC3339Nano),
191 }
192 data, err := json.MarshalIndent(a, "", " ")
193 if err != nil {
194 return err
195 }
196 return writeFile(filepath.Join(p.cfg.state, acknowledgedFile), append(data, '\n'), 0o600)
197}