oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package hostedwire
2
3import (
4 "bytes"
5 "context"
6 "crypto/ed25519"
7 "encoding/base64"
8 "errors"
9 "io"
10 "net/http"
11 "net/http/httptest"
12 "strconv"
13 "strings"
14 "sync"
15 "testing"
16 "time"
17)
18
19const (
20 nonceA = "nonce-aaaaaaaaaaaaaaaa"
21 nonceB = "nonce-bbbbbbbbbbbbbbbb"
22)
23
24func testKey(seed byte) ed25519.PrivateKey {
25 return ed25519.NewKeyFromSeed(bytes.Repeat([]byte{seed}, ed25519.SeedSize))
26}
27
28func pub(k ed25519.PrivateKey) ed25519.PublicKey { return k.Public().(ed25519.PublicKey) }
29
30// memNonces is a NonceStore that keeps every nonce it is shown.
31type memNonces struct {
32 mu sync.Mutex
33 seen map[string]bool
34 calls int
35 lastUntil time.Time
36 err error
37}
38
39func (m *memNonces) Remember(_ context.Context, id KeyID, nonce string, until time.Time) (bool, error) {
40 m.mu.Lock()
41 defer m.mu.Unlock()
42 m.calls++
43 m.lastUntil = until
44 if m.err != nil {
45 return false, m.err
46 }
47 k := string(id) + "\x00" + nonce
48 if m.seen[k] {
49 return false, nil
50 }
51 m.seen[k] = true
52 return true, nil
53}
54
55func (m *memNonces) count() int {
56 m.mu.Lock()
57 defer m.mu.Unlock()
58 return m.calls
59}
60
61type fixture struct {
62 now time.Time
63 inst ed25519.PrivateKey
64 inst2 ed25519.PrivateKey
65 op ed25519.PrivateKey
66 ctl ed25519.PrivateKey
67 nonces *memNonces
68 v *Verifier
69}
70
71func newFixture() *fixture {
72 f := &fixture{
73 now: time.Unix(1_800_000_000, 0).UTC(),
74 inst: testKey(1),
75 inst2: testKey(2),
76 op: testKey(3),
77 ctl: testKey(4),
78 nonces: &memNonces{seen: map[string]bool{}},
79 }
80 f.v = &Verifier{
81 Keys: map[KeyID]VerifyKey{
82 "inst-1": {Public: pub(f.inst), Role: RoleInstance},
83 "inst-2": {Public: pub(f.inst2), Role: RoleInstance},
84 "op-1": {Public: pub(f.op), Role: RoleOperator},
85 },
86 Nonces: f.nonces,
87 Now: func() time.Time { return f.now },
88 }
89 return f
90}
91
92// signed builds a request as the controller's handler sees it, signed by the
93// given key at time at.
94func (f *fixture) signed(t *testing.T, method, target string, body []byte, id KeyID, key ed25519.PrivateKey, at time.Time, nonce string) *http.Request {
95 t.Helper()
96 r := httptest.NewRequest(method, "http://controller.test"+target, bytes.NewReader(body))
97 if err := SignRequest(r, body, id, key, at, nonce); err != nil {
98 t.Fatalf("SignRequest: %v", err)
99 }
100 return r
101}
102
103func TestSignedRequestRoundTrip(t *testing.T) {
104 f := newFixture()
105 type seen struct {
106 id KeyID
107 role Role
108 err error
109 }
110 got := make(chan seen, 1)
111 reply := []byte(`{"generation":7}`)
112 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
113 body, err := io.ReadAll(io.LimitReader(r.Body, MaxBody+1))
114 if err != nil {
115 got <- seen{err: err}
116 w.WriteHeader(http.StatusBadRequest)
117 return
118 }
119 id, key, err := f.v.Verify(r, body)
120 got <- seen{id, key.Role, err}
121 if err != nil {
122 w.WriteHeader(http.StatusUnauthorized)
123 return
124 }
125 SignResponse(w.Header(), http.StatusOK, r.Header.Get(HeaderNonce), reply, f.ctl)
126 w.WriteHeader(http.StatusOK)
127 _, _ = w.Write(reply)
128 }))
129 defer srv.Close()
130
131 cases := []struct {
132 method, target string
133 body []byte
134 id KeyID
135 key ed25519.PrivateKey
136 role Role
137 }{
138 {"POST", "/v1/jobs/a%2Fb/drain?x=1&y=a+b", []byte(`{}`), "inst-1", f.inst, RoleInstance},
139 {"POST", "/v1/jobs", []byte(`{"attempt_id":"a1"}`), "inst-2", f.inst2, RoleInstance},
140 {"GET", "/v1/vms", nil, "op-1", f.op, RoleOperator},
141 {"GET", "/v1/vms?", nil, "op-1", f.op, RoleOperator},
142 }
143 for _, c := range cases {
144 var rd io.Reader
145 if c.body != nil {
146 rd = bytes.NewReader(c.body)
147 }
148 req, err := http.NewRequest(c.method, srv.URL+c.target, rd)
149 if err != nil {
150 t.Fatal(err)
151 }
152 nonce, err := NewNonce()
153 if err != nil {
154 t.Fatal(err)
155 }
156 if err := SignRequest(req, c.body, c.id, c.key, f.now, nonce); err != nil {
157 t.Fatalf("%s %s: SignRequest: %v", c.method, c.target, err)
158 }
159 resp, err := srv.Client().Do(req)
160 if err != nil {
161 t.Fatal(err)
162 }
163 rb, err := io.ReadAll(resp.Body)
164 _ = resp.Body.Close()
165 if err != nil {
166 t.Fatal(err)
167 }
168 s := <-got
169 if s.err != nil || s.id != c.id || s.role != c.role {
170 t.Fatalf("%s %s: Verify = (%q, %q, %v), want (%q, %q, nil)", c.method, c.target, s.id, s.role, s.err, c.id, c.role)
171 }
172 if err := VerifyResponse(resp, rb, nonce, pub(f.ctl)); err != nil {
173 t.Fatalf("%s %s: VerifyResponse = %v, want nil", c.method, c.target, err)
174 }
175 }
176 if n := f.nonces.count(); n != len(cases) {
177 t.Fatalf("Remember called %d times, want %d", n, len(cases))
178 }
179}
180
181func TestSignatureCoversEveryField(t *testing.T) {
182 body := []byte(`{"reason":"done"}`)
183 const target = "/v1/jobs/a%2Fb/stop?x=1"
184 cases := []struct {
185 name string
186 mutate func(f *fixture, r *http.Request) []byte
187 want error
188 }{
189 {"unchanged", func(_ *fixture, _ *http.Request) []byte { return body }, nil},
190 {"method", func(_ *fixture, r *http.Request) []byte { r.Method = "PUT"; return body }, ErrBadSignature},
191 {"path", func(_ *fixture, r *http.Request) []byte {
192 r.URL.Path, r.URL.RawPath = "/v1/jobs/a%2Fc/stop", ""
193 return body
194 }, ErrBadSignature},
195 {"escaped path", func(_ *fixture, r *http.Request) []byte { r.URL.RawPath = ""; return body }, ErrBadSignature},
196 {"query changed", func(_ *fixture, r *http.Request) []byte { r.URL.RawQuery = "x=2"; return body }, ErrBadSignature},
197 {"query dropped", func(_ *fixture, r *http.Request) []byte { r.URL.RawQuery = ""; return body }, ErrBadSignature},
198 {"timestamp", func(f *fixture, r *http.Request) []byte {
199 r.Header.Set(HeaderTimestamp, strconv.FormatInt(f.now.Unix()+1, 10))
200 return body
201 }, ErrBadSignature},
202 {"nonce", func(_ *fixture, r *http.Request) []byte { r.Header.Set(HeaderNonce, nonceB); return body }, ErrBadSignature},
203 {"body", func(_ *fixture, _ *http.Request) []byte { return []byte(`{"reason":"evil"}`) }, ErrBadSignature},
204 {"body emptied", func(_ *fixture, _ *http.Request) []byte { return nil }, ErrBadSignature},
205 {"key id to another known key", func(_ *fixture, r *http.Request) []byte { r.Header.Set(HeaderKeyID, "inst-2"); return body }, ErrBadSignature},
206 {"key id to the operator key", func(_ *fixture, r *http.Request) []byte { r.Header.Set(HeaderKeyID, "op-1"); return body }, ErrBadSignature},
207 {"key id unknown", func(_ *fixture, r *http.Request) []byte { r.Header.Set(HeaderKeyID, "nobody"); return body }, ErrUnknownKey},
208 {"signature", func(_ *fixture, r *http.Request) []byte {
209 sig, _ := base64.StdEncoding.DecodeString(r.Header.Get(HeaderSignature))
210 sig[10] ^= 1
211 r.Header.Set(HeaderSignature, base64.StdEncoding.EncodeToString(sig))
212 return body
213 }, ErrBadSignature},
214 }
215 for _, c := range cases {
216 t.Run(c.name, func(t *testing.T) {
217 f := newFixture()
218 r := f.signed(t, "POST", target, body, "inst-1", f.inst, f.now, nonceA)
219 b := c.mutate(f, r)
220 id, key, err := f.v.Verify(r, b)
221 if c.want == nil {
222 if err != nil || id != "inst-1" || key.Role != RoleInstance {
223 t.Fatalf("Verify = (%q, %q, %v), want (inst-1, instance, nil)", id, key.Role, err)
224 }
225 return
226 }
227 if !errors.Is(err, c.want) {
228 t.Fatalf("Verify after changing the %s = %v, want %v", c.name, err, c.want)
229 }
230 if id != "" || key.Public != nil {
231 t.Fatalf("Verify refused but returned identity (%q, %v)", id, key)
232 }
233 if n := f.nonces.count(); n != 0 {
234 t.Fatalf("Remember called %d times for a refused request, want 0", n)
235 }
236 })
237 }
238
239 // An empty query is still part of the target: "/v1/vms?" and "/v1/vms"
240 // sign differently, in both directions.
241 for _, c := range []struct {
242 name, target string
243 force bool
244 }{
245 {"empty query added", "/v1/vms", true},
246 {"empty query removed", "/v1/vms?", false},
247 } {
248 t.Run(c.name, func(t *testing.T) {
249 f := newFixture()
250 r := f.signed(t, "GET", c.target, nil, "op-1", f.op, f.now, nonceA)
251 if r.URL.ForceQuery == c.force {
252 t.Fatalf("fixture: %s parsed with ForceQuery %v", c.target, r.URL.ForceQuery)
253 }
254 r.URL.ForceQuery = c.force
255 if _, _, err := f.v.Verify(r, nil); !errors.Is(err, ErrBadSignature) {
256 t.Fatalf("Verify after the %s = %v, want ErrBadSignature", c.name, err)
257 }
258 if n := f.nonces.count(); n != 0 {
259 t.Fatalf("Remember called %d times for a refused request, want 0", n)
260 }
261 })
262 }
263}
264
265func TestSkewRefused(t *testing.T) {
266 cases := []struct {
267 offset time.Duration
268 want error
269 }{
270 {0, nil},
271 {-MaxSkew, nil},
272 {MaxSkew, nil},
273 {-MaxSkew - time.Second, ErrSkew},
274 {MaxSkew + time.Second, ErrSkew},
275 {-24 * time.Hour, ErrSkew},
276 {24 * time.Hour, ErrSkew},
277 }
278 for _, c := range cases {
279 f := newFixture()
280 r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now.Add(c.offset), nonceA)
281 _, _, err := f.v.Verify(r, nil)
282 if !errors.Is(err, c.want) || (c.want == nil) != (err == nil) {
283 t.Fatalf("Verify with the clock %v off = %v, want %v", c.offset, err, c.want)
284 }
285 if c.want != nil && f.nonces.count() != 0 {
286 t.Fatalf("Remember called for a request %v off", c.offset)
287 }
288 }
289
290 // A timestamp at the edge of int64 is refused as skew, not wrapped round.
291 f := newFixture()
292 r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now, nonceA)
293 r.Header.Set(HeaderTimestamp, "9223372036854775807")
294 if _, _, err := f.v.Verify(r, nil); !errors.Is(err, ErrSkew) {
295 t.Fatalf("Verify with the largest timestamp = %v, want ErrSkew", err)
296 }
297}
298
299func TestNonceReplayRefused(t *testing.T) {
300 f := newFixture()
301 body := []byte(`{"generation":3}`)
302 r := f.signed(t, "POST", "/v1/jobs/a1/suspend", body, "inst-1", f.inst, f.now, nonceA)
303 if _, _, err := f.v.Verify(r, body); err != nil {
304 t.Fatalf("first Verify = %v, want nil", err)
305 }
306 firstNow, firstUntil := f.now, f.nonces.lastUntil
307
308 f.now = f.now.Add(30 * time.Second)
309 again := f.signed(t, "POST", "/v1/jobs/a1/suspend", body, "inst-1", f.inst, firstNow, nonceA)
310 id, _, err := f.v.Verify(again, body)
311 if !errors.Is(err, ErrReplay) || id != "" {
312 t.Fatalf("replayed Verify = (%q, %v), want ErrReplay", id, err)
313 }
314
315 if want := firstNow.Add(NonceTTL); !firstUntil.Equal(want) {
316 t.Fatalf("Remember until = %v, want %v", firstUntil, want)
317 }
318 // The nonce must outlive every timestamp that could still pass the skew check.
319 if NonceTTL <= 2*MaxSkew {
320 t.Fatalf("NonceTTL %v does not outlive the skew window %v", NonceTTL, 2*MaxSkew)
321 }
322}
323
324func TestNonceStoreErrorDenies(t *testing.T) {
325 f := newFixture()
326 storeErr := errors.New("disk full")
327 f.nonces.err = storeErr
328 r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now, nonceA)
329 id, key, err := f.v.Verify(r, nil)
330 if !errors.Is(err, ErrNonceStore) || !errors.Is(err, storeErr) || id != "" || key.Public != nil {
331 t.Fatalf("Verify with a failing nonce store = (%q, %v), want ErrNonceStore wrapping the store error", id, err)
332 }
333
334 for _, broken := range []func(v *Verifier){
335 func(v *Verifier) { v.Nonces = nil },
336 func(v *Verifier) { v.Now = nil },
337 func(v *Verifier) { v.Keys = nil },
338 } {
339 f := newFixture()
340 broken(f.v)
341 r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now, nonceA)
342 if _, _, err := f.v.Verify(r, nil); err == nil {
343 t.Fatalf("Verify with an incomplete Verifier = nil, want a refusal")
344 }
345 }
346}
347
348func TestResponseBoundToRequestNonce(t *testing.T) {
349 f := newFixture()
350 body := []byte(`{"epoch":2}`)
351 h := http.Header{}
352 SignResponse(h, http.StatusOK, nonceA, body, f.ctl)
353 resp := func(status int, h http.Header) *http.Response {
354 return &http.Response{StatusCode: status, Header: h}
355 }
356 if err := VerifyResponse(resp(200, h), body, nonceA, pub(f.ctl)); err != nil {
357 t.Fatalf("VerifyResponse = %v, want nil", err)
358 }
359
360 dup := h.Clone()
361 dup.Add(HeaderSignature, h.Get(HeaderSignature))
362 lower := h.Clone()
363 lower["equipo-signature"] = []string{h.Get(HeaderSignature)}
364 badB64 := http.Header{HeaderSignature: {"!!!"}}
365 short := http.Header{HeaderSignature: {base64.StdEncoding.EncodeToString(make([]byte, 63))}}
366
367 cases := []struct {
368 name string
369 resp *http.Response
370 body []byte
371 nonce string
372 pub ed25519.PublicKey
373 want error
374 }{
375 {"another request's nonce", resp(200, h), body, nonceB, pub(f.ctl), ErrBadSignature},
376 {"status", resp(201, h), body, nonceA, pub(f.ctl), ErrBadSignature},
377 {"body", resp(200, h), []byte(`{"epoch":3}`), nonceA, pub(f.ctl), ErrBadSignature},
378 {"another key", resp(200, h), body, nonceA, pub(f.inst), ErrBadSignature},
379 {"missing signature", resp(200, http.Header{}), body, nonceA, pub(f.ctl), ErrUnsigned},
380 {"duplicate signature", resp(200, dup), body, nonceA, pub(f.ctl), ErrMalformed},
381 {"duplicate in another case", resp(200, lower), body, nonceA, pub(f.ctl), ErrMalformed},
382 {"bad base64", resp(200, badB64), body, nonceA, pub(f.ctl), ErrMalformed},
383 {"short signature", resp(200, short), body, nonceA, pub(f.ctl), ErrMalformed},
384 {"empty request nonce", resp(200, h), body, "", pub(f.ctl), ErrMalformed},
385 {"no controller key", resp(200, h), body, nonceA, nil, ErrNotConfigured},
386 {"no response", nil, body, nonceA, pub(f.ctl), ErrUnsigned},
387 }
388 for _, c := range cases {
389 if err := VerifyResponse(c.resp, c.body, c.nonce, c.pub); !errors.Is(err, c.want) {
390 t.Fatalf("VerifyResponse with a changed %s = %v, want %v", c.name, err, c.want)
391 }
392 }
393}
394
395func TestOversizeBodyRefused(t *testing.T) {
396 f := newFixture()
397 big := bytes.Repeat([]byte("a"), MaxBody+1)
398 r := httptest.NewRequest("POST", "http://controller.test/v1/jobs", nil)
399 if err := SignRequest(r, big, "inst-1", f.inst, f.now, nonceA); !errors.Is(err, ErrTooLarge) {
400 t.Fatalf("SignRequest of %d bytes = %v, want ErrTooLarge", len(big), err)
401 }
402
403 // A peer that signs an oversize body anyway is still refused.
404 forge := func(body []byte, nonce string) *http.Request {
405 r := httptest.NewRequest("POST", "http://controller.test/v1/jobs", nil)
406 ts := f.now.Unix()
407 r.Header.Set(HeaderKeyID, "inst-1")
408 r.Header.Set(HeaderTimestamp, strconv.FormatInt(ts, 10))
409 r.Header.Set(HeaderNonce, nonce)
410 sig := ed25519.Sign(f.inst, requestMessage("POST", "/v1/jobs", ts, nonce, body))
411 r.Header.Set(HeaderSignature, base64.StdEncoding.EncodeToString(sig))
412 return r
413 }
414 if _, _, err := f.v.Verify(forge(big, nonceA), big); !errors.Is(err, ErrTooLarge) {
415 t.Fatalf("Verify of %d signed bytes = %v, want ErrTooLarge", len(big), err)
416 }
417 if n := f.nonces.count(); n != 0 {
418 t.Fatalf("Remember called %d times for an oversize body, want 0", n)
419 }
420 limit := big[:MaxBody]
421 if _, _, err := f.v.Verify(forge(limit, nonceB), limit); err != nil {
422 t.Fatalf("Verify of exactly MaxBody bytes = %v, want nil", err)
423 }
424
425 h := http.Header{}
426 SignResponse(h, 200, nonceA, big, f.ctl)
427 if err := VerifyResponse(&http.Response{StatusCode: 200, Header: h}, big, nonceA, pub(f.ctl)); !errors.Is(err, ErrTooLarge) {
428 t.Fatalf("VerifyResponse of %d bytes = %v, want ErrTooLarge", len(big), err)
429 }
430}
431
432func TestRequestHeadersStrict(t *testing.T) {
433 cases := []struct {
434 name string
435 mutate func(f *fixture, h http.Header)
436 want error
437 }{
438 {"key id missing", func(_ *fixture, h http.Header) { h.Del(HeaderKeyID) }, ErrUnsigned},
439 {"timestamp missing", func(_ *fixture, h http.Header) { h.Del(HeaderTimestamp) }, ErrUnsigned},
440 {"nonce missing", func(_ *fixture, h http.Header) { h.Del(HeaderNonce) }, ErrUnsigned},
441 {"signature missing", func(_ *fixture, h http.Header) { h.Del(HeaderSignature) }, ErrUnsigned},
442 {"key id twice", func(_ *fixture, h http.Header) { h.Add(HeaderKeyID, h.Get(HeaderKeyID)) }, ErrMalformed},
443 {"timestamp twice", func(_ *fixture, h http.Header) { h.Add(HeaderTimestamp, h.Get(HeaderTimestamp)) }, ErrMalformed},
444 {"nonce twice", func(_ *fixture, h http.Header) { h.Add(HeaderNonce, nonceB) }, ErrMalformed},
445 {"signature twice", func(_ *fixture, h http.Header) { h.Add(HeaderSignature, h.Get(HeaderSignature)) }, ErrMalformed},
446 {"nonce twice in another case", func(_ *fixture, h http.Header) { h["equipo-nonce"] = []string{h.Get(HeaderNonce)} }, ErrMalformed},
447 {"timestamp with a plus", func(f *fixture, h http.Header) { h.Set(HeaderTimestamp, "+"+strconv.FormatInt(f.now.Unix(), 10)) }, ErrMalformed},
448 {"timestamp with a leading zero", func(f *fixture, h http.Header) { h.Set(HeaderTimestamp, "0"+strconv.FormatInt(f.now.Unix(), 10)) }, ErrMalformed},
449 {"timestamp negative", func(_ *fixture, h http.Header) { h.Set(HeaderTimestamp, "-5") }, ErrMalformed},
450 {"timestamp empty", func(_ *fixture, h http.Header) { h.Set(HeaderTimestamp, "") }, ErrMalformed},
451 {"timestamp too big", func(_ *fixture, h http.Header) { h.Set(HeaderTimestamp, "99999999999999999999") }, ErrMalformed},
452 {"nonce short", func(_ *fixture, h http.Header) { h.Set(HeaderNonce, strings.Repeat("n", 15)) }, ErrMalformed},
453 {"nonce long", func(_ *fixture, h http.Header) { h.Set(HeaderNonce, strings.Repeat("n", 65)) }, ErrMalformed},
454 {"nonce bad character", func(_ *fixture, h http.Header) { h.Set(HeaderNonce, "nonce-aaaaaaaaaaaa.a") }, ErrMalformed},
455 {"signature not base64", func(_ *fixture, h http.Header) { h.Set(HeaderSignature, "not base64!") }, ErrMalformed},
456 {"signature unpadded", func(_ *fixture, h http.Header) {
457 h.Set(HeaderSignature, strings.TrimRight(h.Get(HeaderSignature), "="))
458 }, ErrMalformed},
459 {"signature short", func(_ *fixture, h http.Header) {
460 h.Set(HeaderSignature, base64.StdEncoding.EncodeToString(make([]byte, 63)))
461 }, ErrMalformed},
462 {"key id with a space", func(_ *fixture, h http.Header) { h.Set(HeaderKeyID, "inst 1") }, ErrMalformed},
463 }
464 for _, c := range cases {
465 t.Run(c.name, func(t *testing.T) {
466 f := newFixture()
467 r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now, nonceA)
468 c.mutate(f, r.Header)
469 if _, _, err := f.v.Verify(r, nil); !errors.Is(err, c.want) {
470 t.Fatalf("Verify with %s = %v, want %v", c.name, err, c.want)
471 }
472 if n := f.nonces.count(); n != 0 {
473 t.Fatalf("Remember called %d times, want 0", n)
474 }
475 })
476 }
477}
478
479func TestSharedPublicKeyRefused(t *testing.T) {
480 f := newFixture()
481 // The instance key also listed as an operator key would let an instance
482 // claim the operator role by changing the unsigned key ID header.
483 f.v.Keys["op-alias"] = VerifyKey{Public: pub(f.inst), Role: RoleOperator}
484 for _, id := range []KeyID{"op-alias", "inst-1"} {
485 r := f.signed(t, "GET", "/v1/vms", nil, id, f.inst, f.now, nonceA)
486 if got, _, err := f.v.Verify(r, nil); !errors.Is(err, ErrSharedKey) {
487 t.Fatalf("Verify as %s with a shared public key = (%q, %v), want ErrSharedKey", id, got, err)
488 }
489 }
490
491 f = newFixture()
492 f.v.Keys["inst-1"] = VerifyKey{Public: pub(f.inst)[:31], Role: RoleInstance}
493 r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now, nonceA)
494 if _, _, err := f.v.Verify(r, nil); !errors.Is(err, ErrNotConfigured) {
495 t.Fatalf("Verify with a short public key = %v, want ErrNotConfigured", err)
496 }
497}
498
499func TestSignRequestRefusesBadInput(t *testing.T) {
500 f := newFixture()
501 cases := []struct {
502 name string
503 id KeyID
504 key ed25519.PrivateKey
505 nonce string
506 url string
507 want error
508 }{
509 {"bad nonce", "inst-1", f.inst, "short", "http://c.test/v1/vms", ErrMalformed},
510 {"bad key id", "inst 1", f.inst, nonceA, "http://c.test/v1/vms", ErrMalformed},
511 {"empty key id", "", f.inst, nonceA, "http://c.test/v1/vms", ErrMalformed},
512 {"short key", "inst-1", f.inst[:10], nonceA, "http://c.test/v1/vms", ErrNotConfigured},
513 {"opaque url", "inst-1", f.inst, nonceA, "mailto:x@example.com", ErrMalformed},
514 }
515 for _, c := range cases {
516 r, err := http.NewRequest("GET", c.url, nil)
517 if err != nil {
518 t.Fatal(err)
519 }
520 if err := SignRequest(r, nil, c.id, c.key, f.now, c.nonce); !errors.Is(err, c.want) {
521 t.Fatalf("SignRequest with %s = %v, want %v", c.name, err, c.want)
522 }
523 if r.Header.Get(HeaderSignature) != "" {
524 t.Fatalf("SignRequest with %s set a signature", c.name)
525 }
526 }
527}
528
529func TestNewNonce(t *testing.T) {
530 seen := map[string]bool{}
531 for range 100 {
532 n, err := NewNonce()
533 if err != nil {
534 t.Fatal(err)
535 }
536 if !validNonce(n) {
537 t.Fatalf("NewNonce = %q, not a valid nonce", n)
538 }
539 if seen[n] {
540 t.Fatalf("NewNonce repeated %q", n)
541 }
542 seen[n] = true
543 }
544}
545