gunk-dev/the-valley

state.go

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