package hostedwire import ( "bytes" "context" "crypto/ed25519" "encoding/base64" "errors" "io" "net/http" "net/http/httptest" "strconv" "strings" "sync" "testing" "time" ) const ( nonceA = "nonce-aaaaaaaaaaaaaaaa" nonceB = "nonce-bbbbbbbbbbbbbbbb" ) func testKey(seed byte) ed25519.PrivateKey { return ed25519.NewKeyFromSeed(bytes.Repeat([]byte{seed}, ed25519.SeedSize)) } func pub(k ed25519.PrivateKey) ed25519.PublicKey { return k.Public().(ed25519.PublicKey) } // memNonces is a NonceStore that keeps every nonce it is shown. type memNonces struct { mu sync.Mutex seen map[string]bool calls int lastUntil time.Time err error } func (m *memNonces) Remember(_ context.Context, id KeyID, nonce string, until time.Time) (bool, error) { m.mu.Lock() defer m.mu.Unlock() m.calls++ m.lastUntil = until if m.err != nil { return false, m.err } k := string(id) + "\x00" + nonce if m.seen[k] { return false, nil } m.seen[k] = true return true, nil } func (m *memNonces) count() int { m.mu.Lock() defer m.mu.Unlock() return m.calls } type fixture struct { now time.Time inst ed25519.PrivateKey inst2 ed25519.PrivateKey op ed25519.PrivateKey ctl ed25519.PrivateKey nonces *memNonces v *Verifier } func newFixture() *fixture { f := &fixture{ now: time.Unix(1_800_000_000, 0).UTC(), inst: testKey(1), inst2: testKey(2), op: testKey(3), ctl: testKey(4), nonces: &memNonces{seen: map[string]bool{}}, } f.v = &Verifier{ Keys: map[KeyID]VerifyKey{ "inst-1": {Public: pub(f.inst), Role: RoleInstance}, "inst-2": {Public: pub(f.inst2), Role: RoleInstance}, "op-1": {Public: pub(f.op), Role: RoleOperator}, }, Nonces: f.nonces, Now: func() time.Time { return f.now }, } return f } // signed builds a request as the controller's handler sees it, signed by the // given key at time at. func (f *fixture) signed(t *testing.T, method, target string, body []byte, id KeyID, key ed25519.PrivateKey, at time.Time, nonce string) *http.Request { t.Helper() r := httptest.NewRequest(method, "http://controller.test"+target, bytes.NewReader(body)) if err := SignRequest(r, body, id, key, at, nonce); err != nil { t.Fatalf("SignRequest: %v", err) } return r } func TestSignedRequestRoundTrip(t *testing.T) { f := newFixture() type seen struct { id KeyID role Role err error } got := make(chan seen, 1) reply := []byte(`{"generation":7}`) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(io.LimitReader(r.Body, MaxBody+1)) if err != nil { got <- seen{err: err} w.WriteHeader(http.StatusBadRequest) return } id, key, err := f.v.Verify(r, body) got <- seen{id, key.Role, err} if err != nil { w.WriteHeader(http.StatusUnauthorized) return } SignResponse(w.Header(), http.StatusOK, r.Header.Get(HeaderNonce), reply, f.ctl) w.WriteHeader(http.StatusOK) _, _ = w.Write(reply) })) defer srv.Close() cases := []struct { method, target string body []byte id KeyID key ed25519.PrivateKey role Role }{ {"POST", "/v1/jobs/a%2Fb/drain?x=1&y=a+b", []byte(`{}`), "inst-1", f.inst, RoleInstance}, {"POST", "/v1/jobs", []byte(`{"attempt_id":"a1"}`), "inst-2", f.inst2, RoleInstance}, {"GET", "/v1/vms", nil, "op-1", f.op, RoleOperator}, {"GET", "/v1/vms?", nil, "op-1", f.op, RoleOperator}, } for _, c := range cases { var rd io.Reader if c.body != nil { rd = bytes.NewReader(c.body) } req, err := http.NewRequest(c.method, srv.URL+c.target, rd) if err != nil { t.Fatal(err) } nonce, err := NewNonce() if err != nil { t.Fatal(err) } if err := SignRequest(req, c.body, c.id, c.key, f.now, nonce); err != nil { t.Fatalf("%s %s: SignRequest: %v", c.method, c.target, err) } resp, err := srv.Client().Do(req) if err != nil { t.Fatal(err) } rb, err := io.ReadAll(resp.Body) _ = resp.Body.Close() if err != nil { t.Fatal(err) } s := <-got if s.err != nil || s.id != c.id || s.role != c.role { 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) } if err := VerifyResponse(resp, rb, nonce, pub(f.ctl)); err != nil { t.Fatalf("%s %s: VerifyResponse = %v, want nil", c.method, c.target, err) } } if n := f.nonces.count(); n != len(cases) { t.Fatalf("Remember called %d times, want %d", n, len(cases)) } } func TestSignatureCoversEveryField(t *testing.T) { body := []byte(`{"reason":"done"}`) const target = "/v1/jobs/a%2Fb/stop?x=1" cases := []struct { name string mutate func(f *fixture, r *http.Request) []byte want error }{ {"unchanged", func(_ *fixture, _ *http.Request) []byte { return body }, nil}, {"method", func(_ *fixture, r *http.Request) []byte { r.Method = "PUT"; return body }, ErrBadSignature}, {"path", func(_ *fixture, r *http.Request) []byte { r.URL.Path, r.URL.RawPath = "/v1/jobs/a%2Fc/stop", "" return body }, ErrBadSignature}, {"escaped path", func(_ *fixture, r *http.Request) []byte { r.URL.RawPath = ""; return body }, ErrBadSignature}, {"query changed", func(_ *fixture, r *http.Request) []byte { r.URL.RawQuery = "x=2"; return body }, ErrBadSignature}, {"query dropped", func(_ *fixture, r *http.Request) []byte { r.URL.RawQuery = ""; return body }, ErrBadSignature}, {"timestamp", func(f *fixture, r *http.Request) []byte { r.Header.Set(HeaderTimestamp, strconv.FormatInt(f.now.Unix()+1, 10)) return body }, ErrBadSignature}, {"nonce", func(_ *fixture, r *http.Request) []byte { r.Header.Set(HeaderNonce, nonceB); return body }, ErrBadSignature}, {"body", func(_ *fixture, _ *http.Request) []byte { return []byte(`{"reason":"evil"}`) }, ErrBadSignature}, {"body emptied", func(_ *fixture, _ *http.Request) []byte { return nil }, ErrBadSignature}, {"key id to another known key", func(_ *fixture, r *http.Request) []byte { r.Header.Set(HeaderKeyID, "inst-2"); return body }, ErrBadSignature}, {"key id to the operator key", func(_ *fixture, r *http.Request) []byte { r.Header.Set(HeaderKeyID, "op-1"); return body }, ErrBadSignature}, {"key id unknown", func(_ *fixture, r *http.Request) []byte { r.Header.Set(HeaderKeyID, "nobody"); return body }, ErrUnknownKey}, {"signature", func(_ *fixture, r *http.Request) []byte { sig, _ := base64.StdEncoding.DecodeString(r.Header.Get(HeaderSignature)) sig[10] ^= 1 r.Header.Set(HeaderSignature, base64.StdEncoding.EncodeToString(sig)) return body }, ErrBadSignature}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { f := newFixture() r := f.signed(t, "POST", target, body, "inst-1", f.inst, f.now, nonceA) b := c.mutate(f, r) id, key, err := f.v.Verify(r, b) if c.want == nil { if err != nil || id != "inst-1" || key.Role != RoleInstance { t.Fatalf("Verify = (%q, %q, %v), want (inst-1, instance, nil)", id, key.Role, err) } return } if !errors.Is(err, c.want) { t.Fatalf("Verify after changing the %s = %v, want %v", c.name, err, c.want) } if id != "" || key.Public != nil { t.Fatalf("Verify refused but returned identity (%q, %v)", id, key) } if n := f.nonces.count(); n != 0 { t.Fatalf("Remember called %d times for a refused request, want 0", n) } }) } // An empty query is still part of the target: "/v1/vms?" and "/v1/vms" // sign differently, in both directions. for _, c := range []struct { name, target string force bool }{ {"empty query added", "/v1/vms", true}, {"empty query removed", "/v1/vms?", false}, } { t.Run(c.name, func(t *testing.T) { f := newFixture() r := f.signed(t, "GET", c.target, nil, "op-1", f.op, f.now, nonceA) if r.URL.ForceQuery == c.force { t.Fatalf("fixture: %s parsed with ForceQuery %v", c.target, r.URL.ForceQuery) } r.URL.ForceQuery = c.force if _, _, err := f.v.Verify(r, nil); !errors.Is(err, ErrBadSignature) { t.Fatalf("Verify after the %s = %v, want ErrBadSignature", c.name, err) } if n := f.nonces.count(); n != 0 { t.Fatalf("Remember called %d times for a refused request, want 0", n) } }) } } func TestSkewRefused(t *testing.T) { cases := []struct { offset time.Duration want error }{ {0, nil}, {-MaxSkew, nil}, {MaxSkew, nil}, {-MaxSkew - time.Second, ErrSkew}, {MaxSkew + time.Second, ErrSkew}, {-24 * time.Hour, ErrSkew}, {24 * time.Hour, ErrSkew}, } for _, c := range cases { f := newFixture() r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now.Add(c.offset), nonceA) _, _, err := f.v.Verify(r, nil) if !errors.Is(err, c.want) || (c.want == nil) != (err == nil) { t.Fatalf("Verify with the clock %v off = %v, want %v", c.offset, err, c.want) } if c.want != nil && f.nonces.count() != 0 { t.Fatalf("Remember called for a request %v off", c.offset) } } // A timestamp at the edge of int64 is refused as skew, not wrapped round. f := newFixture() r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now, nonceA) r.Header.Set(HeaderTimestamp, "9223372036854775807") if _, _, err := f.v.Verify(r, nil); !errors.Is(err, ErrSkew) { t.Fatalf("Verify with the largest timestamp = %v, want ErrSkew", err) } } func TestNonceReplayRefused(t *testing.T) { f := newFixture() body := []byte(`{"generation":3}`) r := f.signed(t, "POST", "/v1/jobs/a1/suspend", body, "inst-1", f.inst, f.now, nonceA) if _, _, err := f.v.Verify(r, body); err != nil { t.Fatalf("first Verify = %v, want nil", err) } firstNow, firstUntil := f.now, f.nonces.lastUntil f.now = f.now.Add(30 * time.Second) again := f.signed(t, "POST", "/v1/jobs/a1/suspend", body, "inst-1", f.inst, firstNow, nonceA) id, _, err := f.v.Verify(again, body) if !errors.Is(err, ErrReplay) || id != "" { t.Fatalf("replayed Verify = (%q, %v), want ErrReplay", id, err) } if want := firstNow.Add(NonceTTL); !firstUntil.Equal(want) { t.Fatalf("Remember until = %v, want %v", firstUntil, want) } // The nonce must outlive every timestamp that could still pass the skew check. if NonceTTL <= 2*MaxSkew { t.Fatalf("NonceTTL %v does not outlive the skew window %v", NonceTTL, 2*MaxSkew) } } func TestNonceStoreErrorDenies(t *testing.T) { f := newFixture() storeErr := errors.New("disk full") f.nonces.err = storeErr r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now, nonceA) id, key, err := f.v.Verify(r, nil) if !errors.Is(err, ErrNonceStore) || !errors.Is(err, storeErr) || id != "" || key.Public != nil { t.Fatalf("Verify with a failing nonce store = (%q, %v), want ErrNonceStore wrapping the store error", id, err) } for _, broken := range []func(v *Verifier){ func(v *Verifier) { v.Nonces = nil }, func(v *Verifier) { v.Now = nil }, func(v *Verifier) { v.Keys = nil }, } { f := newFixture() broken(f.v) r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now, nonceA) if _, _, err := f.v.Verify(r, nil); err == nil { t.Fatalf("Verify with an incomplete Verifier = nil, want a refusal") } } } func TestResponseBoundToRequestNonce(t *testing.T) { f := newFixture() body := []byte(`{"epoch":2}`) h := http.Header{} SignResponse(h, http.StatusOK, nonceA, body, f.ctl) resp := func(status int, h http.Header) *http.Response { return &http.Response{StatusCode: status, Header: h} } if err := VerifyResponse(resp(200, h), body, nonceA, pub(f.ctl)); err != nil { t.Fatalf("VerifyResponse = %v, want nil", err) } dup := h.Clone() dup.Add(HeaderSignature, h.Get(HeaderSignature)) lower := h.Clone() lower["equipo-signature"] = []string{h.Get(HeaderSignature)} badB64 := http.Header{HeaderSignature: {"!!!"}} short := http.Header{HeaderSignature: {base64.StdEncoding.EncodeToString(make([]byte, 63))}} cases := []struct { name string resp *http.Response body []byte nonce string pub ed25519.PublicKey want error }{ {"another request's nonce", resp(200, h), body, nonceB, pub(f.ctl), ErrBadSignature}, {"status", resp(201, h), body, nonceA, pub(f.ctl), ErrBadSignature}, {"body", resp(200, h), []byte(`{"epoch":3}`), nonceA, pub(f.ctl), ErrBadSignature}, {"another key", resp(200, h), body, nonceA, pub(f.inst), ErrBadSignature}, {"missing signature", resp(200, http.Header{}), body, nonceA, pub(f.ctl), ErrUnsigned}, {"duplicate signature", resp(200, dup), body, nonceA, pub(f.ctl), ErrMalformed}, {"duplicate in another case", resp(200, lower), body, nonceA, pub(f.ctl), ErrMalformed}, {"bad base64", resp(200, badB64), body, nonceA, pub(f.ctl), ErrMalformed}, {"short signature", resp(200, short), body, nonceA, pub(f.ctl), ErrMalformed}, {"empty request nonce", resp(200, h), body, "", pub(f.ctl), ErrMalformed}, {"no controller key", resp(200, h), body, nonceA, nil, ErrNotConfigured}, {"no response", nil, body, nonceA, pub(f.ctl), ErrUnsigned}, } for _, c := range cases { if err := VerifyResponse(c.resp, c.body, c.nonce, c.pub); !errors.Is(err, c.want) { t.Fatalf("VerifyResponse with a changed %s = %v, want %v", c.name, err, c.want) } } } func TestOversizeBodyRefused(t *testing.T) { f := newFixture() big := bytes.Repeat([]byte("a"), MaxBody+1) r := httptest.NewRequest("POST", "http://controller.test/v1/jobs", nil) if err := SignRequest(r, big, "inst-1", f.inst, f.now, nonceA); !errors.Is(err, ErrTooLarge) { t.Fatalf("SignRequest of %d bytes = %v, want ErrTooLarge", len(big), err) } // A peer that signs an oversize body anyway is still refused. forge := func(body []byte, nonce string) *http.Request { r := httptest.NewRequest("POST", "http://controller.test/v1/jobs", nil) ts := f.now.Unix() r.Header.Set(HeaderKeyID, "inst-1") r.Header.Set(HeaderTimestamp, strconv.FormatInt(ts, 10)) r.Header.Set(HeaderNonce, nonce) sig := ed25519.Sign(f.inst, requestMessage("POST", "/v1/jobs", ts, nonce, body)) r.Header.Set(HeaderSignature, base64.StdEncoding.EncodeToString(sig)) return r } if _, _, err := f.v.Verify(forge(big, nonceA), big); !errors.Is(err, ErrTooLarge) { t.Fatalf("Verify of %d signed bytes = %v, want ErrTooLarge", len(big), err) } if n := f.nonces.count(); n != 0 { t.Fatalf("Remember called %d times for an oversize body, want 0", n) } limit := big[:MaxBody] if _, _, err := f.v.Verify(forge(limit, nonceB), limit); err != nil { t.Fatalf("Verify of exactly MaxBody bytes = %v, want nil", err) } h := http.Header{} SignResponse(h, 200, nonceA, big, f.ctl) if err := VerifyResponse(&http.Response{StatusCode: 200, Header: h}, big, nonceA, pub(f.ctl)); !errors.Is(err, ErrTooLarge) { t.Fatalf("VerifyResponse of %d bytes = %v, want ErrTooLarge", len(big), err) } } func TestRequestHeadersStrict(t *testing.T) { cases := []struct { name string mutate func(f *fixture, h http.Header) want error }{ {"key id missing", func(_ *fixture, h http.Header) { h.Del(HeaderKeyID) }, ErrUnsigned}, {"timestamp missing", func(_ *fixture, h http.Header) { h.Del(HeaderTimestamp) }, ErrUnsigned}, {"nonce missing", func(_ *fixture, h http.Header) { h.Del(HeaderNonce) }, ErrUnsigned}, {"signature missing", func(_ *fixture, h http.Header) { h.Del(HeaderSignature) }, ErrUnsigned}, {"key id twice", func(_ *fixture, h http.Header) { h.Add(HeaderKeyID, h.Get(HeaderKeyID)) }, ErrMalformed}, {"timestamp twice", func(_ *fixture, h http.Header) { h.Add(HeaderTimestamp, h.Get(HeaderTimestamp)) }, ErrMalformed}, {"nonce twice", func(_ *fixture, h http.Header) { h.Add(HeaderNonce, nonceB) }, ErrMalformed}, {"signature twice", func(_ *fixture, h http.Header) { h.Add(HeaderSignature, h.Get(HeaderSignature)) }, ErrMalformed}, {"nonce twice in another case", func(_ *fixture, h http.Header) { h["equipo-nonce"] = []string{h.Get(HeaderNonce)} }, ErrMalformed}, {"timestamp with a plus", func(f *fixture, h http.Header) { h.Set(HeaderTimestamp, "+"+strconv.FormatInt(f.now.Unix(), 10)) }, ErrMalformed}, {"timestamp with a leading zero", func(f *fixture, h http.Header) { h.Set(HeaderTimestamp, "0"+strconv.FormatInt(f.now.Unix(), 10)) }, ErrMalformed}, {"timestamp negative", func(_ *fixture, h http.Header) { h.Set(HeaderTimestamp, "-5") }, ErrMalformed}, {"timestamp empty", func(_ *fixture, h http.Header) { h.Set(HeaderTimestamp, "") }, ErrMalformed}, {"timestamp too big", func(_ *fixture, h http.Header) { h.Set(HeaderTimestamp, "99999999999999999999") }, ErrMalformed}, {"nonce short", func(_ *fixture, h http.Header) { h.Set(HeaderNonce, strings.Repeat("n", 15)) }, ErrMalformed}, {"nonce long", func(_ *fixture, h http.Header) { h.Set(HeaderNonce, strings.Repeat("n", 65)) }, ErrMalformed}, {"nonce bad character", func(_ *fixture, h http.Header) { h.Set(HeaderNonce, "nonce-aaaaaaaaaaaa.a") }, ErrMalformed}, {"signature not base64", func(_ *fixture, h http.Header) { h.Set(HeaderSignature, "not base64!") }, ErrMalformed}, {"signature unpadded", func(_ *fixture, h http.Header) { h.Set(HeaderSignature, strings.TrimRight(h.Get(HeaderSignature), "=")) }, ErrMalformed}, {"signature short", func(_ *fixture, h http.Header) { h.Set(HeaderSignature, base64.StdEncoding.EncodeToString(make([]byte, 63))) }, ErrMalformed}, {"key id with a space", func(_ *fixture, h http.Header) { h.Set(HeaderKeyID, "inst 1") }, ErrMalformed}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { f := newFixture() r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now, nonceA) c.mutate(f, r.Header) if _, _, err := f.v.Verify(r, nil); !errors.Is(err, c.want) { t.Fatalf("Verify with %s = %v, want %v", c.name, err, c.want) } if n := f.nonces.count(); n != 0 { t.Fatalf("Remember called %d times, want 0", n) } }) } } func TestSharedPublicKeyRefused(t *testing.T) { f := newFixture() // The instance key also listed as an operator key would let an instance // claim the operator role by changing the unsigned key ID header. f.v.Keys["op-alias"] = VerifyKey{Public: pub(f.inst), Role: RoleOperator} for _, id := range []KeyID{"op-alias", "inst-1"} { r := f.signed(t, "GET", "/v1/vms", nil, id, f.inst, f.now, nonceA) if got, _, err := f.v.Verify(r, nil); !errors.Is(err, ErrSharedKey) { t.Fatalf("Verify as %s with a shared public key = (%q, %v), want ErrSharedKey", id, got, err) } } f = newFixture() f.v.Keys["inst-1"] = VerifyKey{Public: pub(f.inst)[:31], Role: RoleInstance} r := f.signed(t, "GET", "/v1/jobs/a1", nil, "inst-1", f.inst, f.now, nonceA) if _, _, err := f.v.Verify(r, nil); !errors.Is(err, ErrNotConfigured) { t.Fatalf("Verify with a short public key = %v, want ErrNotConfigured", err) } } func TestSignRequestRefusesBadInput(t *testing.T) { f := newFixture() cases := []struct { name string id KeyID key ed25519.PrivateKey nonce string url string want error }{ {"bad nonce", "inst-1", f.inst, "short", "http://c.test/v1/vms", ErrMalformed}, {"bad key id", "inst 1", f.inst, nonceA, "http://c.test/v1/vms", ErrMalformed}, {"empty key id", "", f.inst, nonceA, "http://c.test/v1/vms", ErrMalformed}, {"short key", "inst-1", f.inst[:10], nonceA, "http://c.test/v1/vms", ErrNotConfigured}, {"opaque url", "inst-1", f.inst, nonceA, "mailto:x@example.com", ErrMalformed}, } for _, c := range cases { r, err := http.NewRequest("GET", c.url, nil) if err != nil { t.Fatal(err) } if err := SignRequest(r, nil, c.id, c.key, f.now, c.nonce); !errors.Is(err, c.want) { t.Fatalf("SignRequest with %s = %v, want %v", c.name, err, c.want) } if r.Header.Get(HeaderSignature) != "" { t.Fatalf("SignRequest with %s set a signature", c.name) } } } func TestNewNonce(t *testing.T) { seen := map[string]bool{} for range 100 { n, err := NewNonce() if err != nil { t.Fatal(err) } if !validNonce(n) { t.Fatalf("NewNonce = %q, not a valid nonce", n) } if seen[n] { t.Fatalf("NewNonce repeated %q", n) } seen[n] = true } }