aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/rosa/mirror.go
blob: 09419396d46ab4b92a3942cde16d4a4f17e5db9c (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package rosa

import (
	"compress/gzip"
	"context"
	"crypto/ed25519"
	"crypto/sha512"
	"errors"
	"io"
	"io/fs"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"unique"

	"hakurei.app/internal/pkg"
	"hakurei.app/message"
)

// Remote is an authenticated cache mirror.
type Remote struct {
	// Mirror URL.
	url *url.URL
	// Trusted public key.
	pub ed25519.PublicKey
	// For requests to the mirror.
	c *http.Client
}

// NewRemote returns a populated [Remote]
func NewRemote(base string, pub ed25519.PublicKey, c *http.Client) (Remote, error) {
	u, err := url.Parse(base)
	return Remote{u, pub, c}, err
}

// get makes a [http.MethodGet] request and returns the response, or nil if
// the response StatusCode is [http.StatusNotFound].
func (r Remote) get(ctx context.Context, elem ...string) (*http.Response, error) {
	if r.url == nil || len(r.pub) != ed25519.PublicKeySize || r.c == nil {
		return nil, os.ErrInvalid
	}

	req, err := http.NewRequestWithContext(
		ctx,
		http.MethodGet,
		r.url.JoinPath(elem...).String(),
		nil,
	)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", "Rosa/1.1")

	var resp *http.Response
	if resp, err = r.c.Do(req); err != nil {
		return nil, err
	}

	switch resp.StatusCode {
	case http.StatusOK:
		return resp, nil

	case http.StatusNotFound:
		return nil, resp.Body.Close()

	default:
		_ = resp.Body.Close()
		return nil, pkg.ResponseStatusError(resp.StatusCode)
	}
}

const (
	// dirArtifact holds signed artifact outcome checksums.
	dirArtifact = "artifact"
	// dirOutcome holds outcome archives by their checksum.
	dirOutcome = "outcome"
	// dirStatus holds signed status files.
	dirStatus = "status"
)

// An OutcomeBadSizeError describes a mirror outcome with unexpected size.
type OutcomeBadSizeError struct {
	Ident unique.Handle[pkg.ID]
	Size  int64
}

func (e OutcomeBadSizeError) Error() string {
	if e.Size < 0 {
		return "remote did not return outcome size for " +
			pkg.Encode(e.Ident.Value())
	}
	return "outcome size " + strconv.FormatInt(e.Size, 10) +
		" invalid for " + pkg.Encode(e.Ident.Value())
}

// An OutcomeAuthError describes a mirror outcome with invalid signature.
type OutcomeAuthError unique.Handle[pkg.ID]

func (e OutcomeAuthError) Error() string {
	return "invalid outcome signature for " +
		pkg.Encode(unique.Handle[pkg.ID](e).Value())
}

// Artifact fetches and authenticates an outcome.
func (r Remote) Artifact(
	ctx context.Context,
	id unique.Handle[pkg.ID],
) (*pkg.Checksum, error) {
	if len(r.pub) != ed25519.PublicKeySize || r.c == nil {
		return nil, os.ErrInvalid
	}

	resp, err := r.get(ctx, dirArtifact, pkg.Encode(id.Value()))
	if err != nil || resp == nil {
		return nil, err
	}

	var buf [ed25519.SignatureSize + 2*len(pkg.Checksum{})]byte
	if resp.ContentLength != int64(len(buf)) {
		_ = resp.Body.Close()
		return nil, OutcomeBadSizeError{id, resp.ContentLength}
	}
	if _, err = io.ReadFull(resp.Body, buf[:]); err != nil {
		return nil, errors.Join(err, resp.Body.Close())
	} else if err = resp.Body.Close(); err != nil {
		return nil, err
	}

	if !ed25519.Verify(
		r.pub,
		buf[ed25519.SignatureSize:],
		buf[:ed25519.SignatureSize],
	) {
		return nil, OutcomeAuthError(id)
	} else if unique.Make((pkg.ID)(buf[ed25519.SignatureSize:])) != id {
		return nil, OutcomeAuthError(id)
	}
	return (*pkg.Checksum)(buf[ed25519.SignatureSize+len(pkg.Checksum{}):]), nil
}

// Checksum returns an artifact satisfying checksum.
func (r Remote) Checksum(checksum unique.Handle[pkg.Checksum]) pkg.Artifact {
	return pkg.NewArchive(pkg.NewHTTPGet(
		r.c,
		r.url.JoinPath(dirOutcome, pkg.Encode(checksum.Value())).String(),
		checksum.Value(),
	))
}

// A StatusBadSizeError describes a mirror status with unexpected size.
type StatusBadSizeError unique.Handle[pkg.ID]

func (e StatusBadSizeError) Error() string {
	return "status payload too short for " +
		pkg.Encode(unique.Handle[pkg.ID](e).Value())
}

// A StatusAuthError describes a mirror status with invalid signature.
type StatusAuthError unique.Handle[pkg.ID]

func (e StatusAuthError) Error() string {
	return "invalid status signature for " +
		pkg.Encode(unique.Handle[pkg.ID](e).Value())
}

// Status authenticates the checksum of a status file and returns its
// corresponding measured reader.
func (r Remote) Status(
	ctx *pkg.RContext,
	id unique.Handle[pkg.ID],
) (io.ReadCloser, error) {
	resp, err := r.get(ctx.Unwrap(), dirStatus, pkg.Encode(id.Value()))
	if err != nil || resp == nil {
		return nil, err
	}

	var buf [ed25519.SignatureSize + 2*len(pkg.Checksum{})]byte
	if _, err = io.ReadFull(resp.Body, buf[:]); err != nil {
		if errors.Is(err, io.ErrUnexpectedEOF) {
			err = StatusBadSizeError(id)
		}
		return nil, err
	}

	if !ed25519.Verify(
		r.pub,
		buf[ed25519.SignatureSize:],
		buf[:ed25519.SignatureSize],
	) {
		_ = resp.Body.Close()
		return nil, StatusAuthError(id)
	} else if unique.Make((pkg.ID)(buf[ed25519.SignatureSize:])) != id {
		return nil, StatusAuthError(id)
	}
	return ctx.NewMeasuredReader(
		resp.Body,
		unique.Make((pkg.Checksum)(buf[ed25519.SignatureSize+len(pkg.Checksum{}):])),
	), nil
}

// NewMirror returns an [http.Handler] for servicing mirror requests.
func NewMirror(
	msg message.Msg,
	fsys fs.FS,
	key ed25519.PrivateKey,
) http.Handler {
	const identName = "ident"
	var mux http.ServeMux

	mux.HandleFunc("/"+dirArtifact+"/{"+identName+"}", func(
		w http.ResponseWriter,
		req *http.Request,
	) {
		var buf [2 * len(pkg.Checksum{})]byte
		if err := pkg.Decode(
			(*pkg.Checksum)(buf[:len(pkg.Checksum{})]),
			req.PathValue(identName),
		); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		ids := pkg.Encode((pkg.Checksum)(buf[:len(pkg.Checksum{})]))
		if linkname, err := fs.ReadLink(fsys, filepath.Join(
			"identifier",
			ids,
		)); err != nil {
			if errors.Is(err, os.ErrNotExist) {
				w.WriteHeader(http.StatusNotFound)
				return
			}
			msg.GetLogger().Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		} else if err = pkg.Decode(
			(*pkg.Checksum)(buf[len(pkg.Checksum{}):]),
			filepath.Base(linkname),
		); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		msg.Verbosef("serving artifact %s", ids)

		w.Header().Set(
			"Content-Length",
			strconv.Itoa(ed25519.SignatureSize+len(buf)),
		)
		if _, err := w.Write(append(
			ed25519.Sign(key, buf[:]),
			buf[:]...,
		)); err != nil {
			msg.Verbose(err)
		}
	})

	mux.HandleFunc("/"+dirOutcome+"/{"+identName+"}", func(
		w http.ResponseWriter,
		req *http.Request,
	) {
		if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
			w.WriteHeader(http.StatusNotAcceptable)
			return
		}

		var buf pkg.Checksum
		if err := pkg.Decode(
			&buf,
			req.PathValue(identName),
		); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		checksums := pkg.Encode(buf)
		rel := filepath.Join("checksum", checksums)
		if _, err := fs.Lstat(fsys, rel); err != nil {
			if errors.Is(err, os.ErrNotExist) {
				w.WriteHeader(http.StatusNotFound)
				return
			}
			msg.GetLogger().Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		msg.Verbosef("serving outcome %s", pkg.Encode(buf))

		_fsys, err := fs.Sub(fsys, rel)
		if err != nil {
			msg.GetLogger().Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

		var gw *gzip.Writer
		if gw, err = gzip.NewWriterLevel(w, gzip.BestCompression); err != nil {
			msg.GetLogger().Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Encoding", "gzip")
		if err = pkg.Write(_fsys, ".", gw); err != nil {
			msg.Verbose(err)
		}
		if err = gw.Close(); err != nil {
			msg.GetLogger().Println(err)
		}
	})

	mux.HandleFunc("/"+dirStatus+"/{"+identName+"}", func(
		w http.ResponseWriter,
		req *http.Request,
	) {
		var buf [2 * len(pkg.Checksum{})]byte
		if err := pkg.Decode(
			(*pkg.Checksum)(buf[:len(pkg.Checksum{})]),
			req.PathValue(identName),
		); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		ids := pkg.Encode((pkg.Checksum)(buf[:len(pkg.Checksum{})]))
		f, err := fsys.Open(filepath.Join(
			"status",
			ids,
		))
		if err != nil {
			if errors.Is(err, os.ErrNotExist) {
				w.WriteHeader(http.StatusNotFound)
				return
			}
			msg.GetLogger().Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		s, ok := f.(io.Seeker)
		if !ok {
			msg.GetLogger().Println("backing filesystem does not support seek")
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		msg.Verbosef("serving status %s", ids)

		h := sha512.New384()
		if _, err = io.Copy(h, f); err != nil {
			_ = f.Close()
			msg.Verbose(err)
			w.WriteHeader(http.StatusInternalServerError)
		}
		h.Sum(buf[len(pkg.Checksum{}):len(pkg.Checksum{})])
		if _, err = w.Write(append(ed25519.Sign(key, buf[:]), buf[:]...)); err != nil {
			msg.Verbose(err)
			return
		} else if _, err = s.Seek(0, io.SeekStart); err != nil {
			msg.GetLogger().Println(err)
			return
		} else if _, err = io.Copy(w, f); err != nil {
			msg.Verbose(err)
			return
		}
	})

	return &mux
}