blob: a6781903d15b1e6ca01ed070c7456bf6bac8c609 [file] [log] [blame]
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001package keys
2
3import (
4 "crypto/ecdsa"
5 "crypto/elliptic"
6 "crypto/rand"
7 "errors"
8 "fmt"
9 "strings"
10 "testing"
Asim Shankar1c5b94a2014-09-05 16:36:12 -070011
Jiri Simsa519c5072014-09-17 21:37:57 -070012 "veyron.io/veyron/veyron2/security"
Jiri Simsa5293dcb2014-05-10 09:56:38 -070013)
14
Asim Shankar1c5b94a2014-09-05 16:36:12 -070015func mkkey() security.PublicKey {
Jiri Simsa5293dcb2014-05-10 09:56:38 -070016 s, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
17 if err != nil {
18 panic(err)
19 }
Asim Shankar1c5b94a2014-09-05 16:36:12 -070020 return security.NewECDSAPublicKey(&s.PublicKey)
Jiri Simsa5293dcb2014-05-10 09:56:38 -070021}
22
23func TestTrustedKeys(t *testing.T) {
24 k1 := mkkey()
25 k2 := mkkey()
26 test := func(name string, k1Trust, k2Trust TrustLevel) error {
27 var errs []string
28 t1 := LevelOfTrust(k1, name)
29 t2 := LevelOfTrust(k2, name)
30 if t1 != k1Trust {
31 errs = append(errs, fmt.Sprintf("Got %v want %v for LevelOfTrust(k1, %v)", t1, k1Trust, name))
32 }
33 if t2 != k2Trust {
34 errs = append(errs, fmt.Sprintf("Got %v want %v for LevelOfTrust(k2, %v)", t2, k2Trust, name))
35 }
36 switch len(errs) {
37 case 0:
38 return nil
39 case 1:
40 return errors.New(errs[0])
41 default:
42 return errors.New(strings.Join(errs, ". "))
43 }
44 }
45
46 // Initially, everything is unregistered
47 if err := test("foo", Unknown, Unknown); err != nil {
48 t.Error(err)
49 }
50 // k1 will be trusted for "foo" after Trust is called.
51 Trust(k1, "foo")
52 if err := test("foo", Trusted, Mistrusted); err != nil {
53 t.Error(err)
54 }
55 // multiple keys can be trusted for the same name
56 Trust(k2, "foo")
57 if err := test("foo", Trusted, Trusted); err != nil {
58 t.Error(err)
59 }
60 // Trust so far is only for "foo", not "bar"
61 if err := test("bar", Unknown, Unknown); err != nil {
62 t.Error(err)
63 }
64 Trust(k2, "bar")
65 if err := test("bar", Mistrusted, Trusted); err != nil {
66 t.Error(err)
67 }
68}