package executor import ( "context" "testing" "time" millproto "tangled.org/core/spindle/mill/proto" millv1 "tangled.org/core/spindle/mill/proto/gen" ) func askWith(t *testing.T, answer func(*DebugKeyClient, *millv1.DebugKeyRequest)) (bool, *millv1.DebugKeyRequest) { t.Helper() client := NewDebugKeyClient() var asked *millv1.DebugKeyRequest client.SetSendFn(func(msg *millproto.Message) error { asked = msg.GetDebugKeyReq() go answer(client, asked) return nil }) return client.ForLease("lease-1")(context.Background(), []byte("wire-key")), asked } func TestDebugKeyClientReturnsTheMillsAnswer(t *testing.T) { for _, allowed := range []bool{true, false} { got, asked := askWith(t, func(c *DebugKeyClient, req *millv1.DebugKeyRequest) { c.HandleResponse(&millv1.DebugKeyResponse{RequestId: req.GetRequestId(), Allowed: allowed}) }) if got != allowed { t.Errorf("mill said %v, client answered %v", allowed, got) } if asked.GetLeaseId() != "lease-1" || string(asked.GetPublicKey()) != "wire-key" { t.Errorf("asked %+v, want the lease and key it was given", asked) } } } func TestDebugKeyClientRefusesWhenTheMillErrors(t *testing.T) { got, _ := askWith(t, func(c *DebugKeyClient, req *millv1.DebugKeyRequest) { c.HandleResponse(&millv1.DebugKeyResponse{RequestId: req.GetRequestId(), Allowed: true, Error: "no live lease"}) }) if got { t.Fatal("a key got in on an error response that also said allowed") } } func TestDebugKeyClientRefusesWhenDisconnectedOrSilent(t *testing.T) { if NewDebugKeyClient().ForLease("lease-1")(context.Background(), []byte("k")) { t.Fatal("a key got in with no connection to the mill") } client := NewDebugKeyClient() client.SetSendFn(func(*millproto.Message) error { return nil }) ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() if client.ForLease("lease-1")(ctx, []byte("k")) { t.Fatal("a key got in while the mill stayed silent") } client = NewDebugKeyClient() client.SetSendFn(func(*millproto.Message) error { go client.OnDisconnect() return nil }) if client.ForLease("lease-1")(context.Background(), []byte("k")) { t.Fatal("a key got in after the connection dropped") } }