blob: 78fb4ee0d8452e8741a1e6a276775c17bcb467ac [file] [log] [blame]
Jiri Simsad7616c92015-03-24 23:44:30 -07001// Copyright 2015 The Vanadium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07005package rpc
Jiri Simsa5293dcb2014-05-10 09:56:38 -07006
7import (
Asim Shankarf4864f42014-11-25 18:53:05 -08008 "encoding/hex"
Jiri Simsa5293dcb2014-05-10 09:56:38 -07009 "errors"
10 "fmt"
11 "io"
Cosmos Nicolaoud6c3c9c2014-09-30 15:42:53 -070012 "net"
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -080013 "path/filepath"
Jiri Simsa5293dcb2014-05-10 09:56:38 -070014 "reflect"
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -080015 "runtime"
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -080016 "sort"
Jiri Simsa5293dcb2014-05-10 09:56:38 -070017 "strings"
Bogdan Caprita27953142014-05-12 11:41:42 -070018 "sync"
Jiri Simsa5293dcb2014-05-10 09:56:38 -070019 "testing"
20 "time"
21
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -070022 "v.io/x/lib/netstate"
23 "v.io/x/lib/pubsub"
24 "v.io/x/lib/vlog"
25
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -070026 "v.io/v23"
Jiri Simsa6ac95222015-02-23 16:11:49 -080027 "v.io/v23/context"
Matt Rosencrantz88be1182015-04-27 13:45:43 -070028 "v.io/v23/i18n"
Todd Wang5082a552015-04-02 10:56:11 -070029 "v.io/v23/namespace"
Jiri Simsa6ac95222015-02-23 16:11:49 -080030 "v.io/v23/naming"
31 "v.io/v23/options"
Matt Rosencrantz94502cf2015-03-18 09:43:44 -070032 "v.io/v23/rpc"
Jiri Simsa6ac95222015-02-23 16:11:49 -080033 "v.io/v23/security"
Todd Wang387d8a42015-03-30 17:09:05 -070034 "v.io/v23/security/access"
Jiri Simsa6ac95222015-02-23 16:11:49 -080035 "v.io/v23/uniqueid"
36 "v.io/v23/vdl"
37 "v.io/v23/verror"
Jiri Simsa6ac95222015-02-23 16:11:49 -080038 "v.io/v23/vtrace"
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -070039
Jiri Simsaffceefa2015-02-28 11:03:34 -080040 "v.io/x/ref/lib/stats"
Matt Rosencrantz86ba1a12015-03-09 13:19:02 -070041 "v.io/x/ref/profiles/internal/lib/publisher"
Suharsh Sivakumarcbfe4742015-03-11 14:54:22 -070042 "v.io/x/ref/profiles/internal/lib/websocket"
Matt Rosencrantzdbc1be22015-02-28 15:15:49 -080043 inaming "v.io/x/ref/profiles/internal/naming"
Matt Rosencrantz94502cf2015-03-18 09:43:44 -070044 _ "v.io/x/ref/profiles/internal/rpc/protocols/tcp"
45 _ "v.io/x/ref/profiles/internal/rpc/protocols/ws"
46 _ "v.io/x/ref/profiles/internal/rpc/protocols/wsh"
Todd Wang54feabe2015-04-15 23:38:26 -070047 "v.io/x/ref/profiles/internal/rpc/stream"
Matt Rosencrantz94502cf2015-03-18 09:43:44 -070048 imanager "v.io/x/ref/profiles/internal/rpc/stream/manager"
49 "v.io/x/ref/profiles/internal/rpc/stream/vc"
Matt Rosencrantzdbc1be22015-02-28 15:15:49 -080050 tnaming "v.io/x/ref/profiles/internal/testing/mocks/naming"
Cosmos Nicolaou1381f8a2015-03-13 09:40:34 -070051 "v.io/x/ref/test/testutil"
Jiri Simsa5293dcb2014-05-10 09:56:38 -070052)
53
Suharsh Sivakumard19c95d2015-02-19 14:44:50 -080054//go:generate v23 test generate
55
Jiri Simsa5293dcb2014-05-10 09:56:38 -070056var (
Jiri Simsa074bf362015-02-17 09:29:45 -080057 errMethod = verror.New(verror.ErrAborted, nil)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -080058 clock = new(fakeClock)
Matt Rosencrantz94502cf2015-03-18 09:43:44 -070059 listenAddrs = rpc.ListenAddrs{{"tcp", "127.0.0.1:0"}}
60 listenWSAddrs = rpc.ListenAddrs{{"ws", "127.0.0.1:0"}, {"tcp", "127.0.0.1:0"}}
61 listenSpec = rpc.ListenSpec{Addrs: listenAddrs}
62 listenWSSpec = rpc.ListenSpec{Addrs: listenWSAddrs}
Jiri Simsa5293dcb2014-05-10 09:56:38 -070063)
64
Andres Erbsenb7f95f32014-07-07 12:07:56 -070065type fakeClock struct {
66 sync.Mutex
Suharsh Sivakumar8a0adbb2015-03-06 13:16:34 -080067 time int64
Andres Erbsenb7f95f32014-07-07 12:07:56 -070068}
69
Suharsh Sivakumar8a0adbb2015-03-06 13:16:34 -080070func (c *fakeClock) Now() int64 {
Andres Erbsenb7f95f32014-07-07 12:07:56 -070071 c.Lock()
72 defer c.Unlock()
73 return c.time
74}
75
76func (c *fakeClock) Advance(steps uint) {
77 c.Lock()
Suharsh Sivakumar8a0adbb2015-03-06 13:16:34 -080078 c.time += int64(steps)
Andres Erbsenb7f95f32014-07-07 12:07:56 -070079 c.Unlock()
80}
81
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -070082func testInternalNewServerWithPubsub(ctx *context.T, streamMgr stream.Manager, ns namespace.T, settingsPublisher *pubsub.Publisher, settingsStreamName string, principal security.Principal, opts ...rpc.ServerOpt) (rpc.Server, error) {
Suharsh Sivakumaraf99c972015-01-28 15:28:49 -080083 client, err := InternalNewClient(streamMgr, ns)
84 if err != nil {
85 return nil, err
86 }
Cosmos Nicolaou00fe9a42015-04-24 14:18:01 -070087 return InternalNewServer(ctx, streamMgr, ns, settingsPublisher, settingsStreamName, client, principal, opts...)
88}
89
90func testInternalNewServer(ctx *context.T, streamMgr stream.Manager, ns namespace.T, principal security.Principal, opts ...rpc.ServerOpt) (rpc.Server, error) {
91 return testInternalNewServerWithPubsub(ctx, streamMgr, ns, nil, "", principal, opts...)
Suharsh Sivakumaraf99c972015-01-28 15:28:49 -080092}
93
Jiri Simsa5293dcb2014-05-10 09:56:38 -070094type userType string
95
96type testServer struct{}
97
Todd Wang54feabe2015-04-15 23:38:26 -070098func (*testServer) Closure(*context.T, rpc.ServerCall) error {
Todd Wange77f9952015-02-18 13:20:50 -080099 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700100}
101
Todd Wang54feabe2015-04-15 23:38:26 -0700102func (*testServer) Error(*context.T, rpc.ServerCall) error {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700103 return errMethod
104}
105
Todd Wang54feabe2015-04-15 23:38:26 -0700106func (*testServer) Echo(_ *context.T, call rpc.ServerCall, arg string) (string, error) {
Matt Rosencrantz311378b2015-03-25 15:26:12 -0700107 return fmt.Sprintf("method:%q,suffix:%q,arg:%q", "Echo", call.Suffix(), arg), nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700108}
109
Todd Wang54feabe2015-04-15 23:38:26 -0700110func (*testServer) EchoUser(_ *context.T, call rpc.ServerCall, arg string, u userType) (string, userType, error) {
Matt Rosencrantz311378b2015-03-25 15:26:12 -0700111 return fmt.Sprintf("method:%q,suffix:%q,arg:%q", "EchoUser", call.Suffix(), arg), u, nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700112}
113
Matt Rosencrantz88be1182015-04-27 13:45:43 -0700114func (*testServer) EchoLang(ctx *context.T, call rpc.ServerCall) (string, error) {
115 return string(i18n.GetLangID(ctx)), nil
116}
117
Todd Wang4264e4b2015-04-16 22:43:40 -0700118func (*testServer) EchoBlessings(ctx *context.T, call rpc.ServerCall) (server, client string, _ error) {
119 local := security.LocalBlessingNames(ctx, call.Security())
120 remote, _ := security.RemoteBlessingNames(ctx, call.Security())
Todd Wange77f9952015-02-18 13:20:50 -0800121 return fmt.Sprintf("%v", local), fmt.Sprintf("%v", remote), nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700122}
123
Todd Wang54feabe2015-04-15 23:38:26 -0700124func (*testServer) EchoGrantedBlessings(_ *context.T, call rpc.ServerCall, arg string) (result, blessing string, _ error) {
Matt Rosencrantz9dce9b22015-03-02 10:48:37 -0800125 return arg, fmt.Sprintf("%v", call.GrantedBlessings()), nil
Asim Shankarb54d7642014-06-05 13:08:04 -0700126}
127
Todd Wang54feabe2015-04-15 23:38:26 -0700128func (*testServer) EchoAndError(_ *context.T, call rpc.ServerCall, arg string) (string, error) {
Matt Rosencrantz311378b2015-03-25 15:26:12 -0700129 result := fmt.Sprintf("method:%q,suffix:%q,arg:%q", "EchoAndError", call.Suffix(), arg)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700130 if arg == "error" {
131 return result, errMethod
132 }
133 return result, nil
134}
135
Todd Wang54feabe2015-04-15 23:38:26 -0700136func (*testServer) Stream(_ *context.T, call rpc.StreamServerCall, arg string) (string, error) {
Matt Rosencrantz311378b2015-03-25 15:26:12 -0700137 result := fmt.Sprintf("method:%q,suffix:%q,arg:%q", "Stream", call.Suffix(), arg)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700138 var u userType
139 var err error
140 for err = call.Recv(&u); err == nil; err = call.Recv(&u) {
141 result += " " + string(u)
142 if err := call.Send(u); err != nil {
143 return "", err
144 }
145 }
146 if err == io.EOF {
147 err = nil
148 }
149 return result, err
150}
151
Todd Wang54feabe2015-04-15 23:38:26 -0700152func (*testServer) Unauthorized(*context.T, rpc.StreamServerCall) (string, error) {
Todd Wange77f9952015-02-18 13:20:50 -0800153 return "UnauthorizedResult", nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700154}
155
156type testServerAuthorizer struct{}
157
Todd Wang4264e4b2015-04-16 22:43:40 -0700158func (testServerAuthorizer) Authorize(ctx *context.T, call security.Call) error {
Ankuredd74ee2015-03-04 16:38:45 -0800159 // Verify that the Call object seen by the authorizer
160 // has the necessary fields.
Todd Wang4264e4b2015-04-16 22:43:40 -0700161 lb := call.LocalBlessings()
Ankuredd74ee2015-03-04 16:38:45 -0800162 if lb.IsZero() {
Todd Wang4264e4b2015-04-16 22:43:40 -0700163 return fmt.Errorf("testServerAuthorzer: Call object %v has no LocalBlessings", call)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700164 }
Todd Wang4264e4b2015-04-16 22:43:40 -0700165 if tpcavs := lb.ThirdPartyCaveats(); len(tpcavs) > 0 && call.LocalDischarges() == nil {
166 return fmt.Errorf("testServerAuthorzer: Call object %v has no LocalDischarges even when LocalBlessings have third-party caveats", call)
Ankuredd74ee2015-03-04 16:38:45 -0800167
168 }
Todd Wang4264e4b2015-04-16 22:43:40 -0700169 if call.LocalPrincipal() == nil {
170 return fmt.Errorf("testServerAuthorzer: Call object %v has no LocalPrincipal", call)
Ankuredd74ee2015-03-04 16:38:45 -0800171 }
Todd Wang4264e4b2015-04-16 22:43:40 -0700172 if call.Method() == "" {
173 return fmt.Errorf("testServerAuthorzer: Call object %v has no Method", call)
Ankuredd74ee2015-03-04 16:38:45 -0800174 }
Todd Wang4264e4b2015-04-16 22:43:40 -0700175 if call.LocalEndpoint() == nil {
176 return fmt.Errorf("testServerAuthorzer: Call object %v has no LocalEndpoint", call)
Ankuredd74ee2015-03-04 16:38:45 -0800177 }
Todd Wang4264e4b2015-04-16 22:43:40 -0700178 if call.RemoteEndpoint() == nil {
179 return fmt.Errorf("testServerAuthorzer: Call object %v has no RemoteEndpoint", call)
Ankuredd74ee2015-03-04 16:38:45 -0800180 }
181
182 // Do not authorize the method "Unauthorized".
Todd Wang4264e4b2015-04-16 22:43:40 -0700183 if call.Method() == "Unauthorized" {
Ankuredd74ee2015-03-04 16:38:45 -0800184 return fmt.Errorf("testServerAuthorizer denied access")
185 }
186 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700187}
188
189type testServerDisp struct{ server interface{} }
190
Robin Thellenda02fe8f2014-11-19 09:58:29 -0800191func (t testServerDisp) Lookup(suffix string) (interface{}, security.Authorizer, error) {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700192 // If suffix is "nilAuth" we use default authorization, if it is "aclAuth" we
Adam Sadovskya4d4a692015-04-20 11:36:49 -0700193 // use an AccessList-based authorizer, and otherwise we use the custom testServerAuthorizer.
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700194 var authorizer security.Authorizer
195 switch suffix {
196 case "discharger":
Cosmos Nicolaou710daa22014-11-11 19:39:18 -0800197 return &dischargeServer{}, testServerAuthorizer{}, nil
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700198 case "nilAuth":
199 authorizer = nil
200 case "aclAuth":
Benjamin Prosnitzb60efb92015-03-11 17:47:43 -0700201 authorizer = &access.AccessList{
Ankur78b8b2a2015-02-04 20:16:28 -0800202 In: []security.BlessingPattern{"client", "server"},
Asim Shankar68885192014-11-26 12:48:35 -0800203 }
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700204 default:
205 authorizer = testServerAuthorizer{}
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700206 }
Cosmos Nicolaou710daa22014-11-11 19:39:18 -0800207 return t.server, authorizer, nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700208}
209
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -0800210type dischargeServer struct {
211 mu sync.Mutex
212 called bool
213}
Ankure49a86a2014-11-11 18:52:43 -0800214
Todd Wang4264e4b2015-04-16 22:43:40 -0700215func (ds *dischargeServer) Discharge(ctx *context.T, call rpc.StreamServerCall, cav security.Caveat, _ security.DischargeImpetus) (security.Discharge, error) {
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -0800216 ds.mu.Lock()
217 ds.called = true
218 ds.mu.Unlock()
Asim Shankar19da8182015-02-06 01:41:16 -0800219 tp := cav.ThirdPartyDetails()
220 if tp == nil {
Asim Shankar08642822015-03-02 21:21:09 -0800221 return security.Discharge{}, fmt.Errorf("discharger: %v does not represent a third-party caveat", cav)
Ankure49a86a2014-11-11 18:52:43 -0800222 }
Todd Wang4264e4b2015-04-16 22:43:40 -0700223 if err := tp.Dischargeable(ctx, call.Security()); err != nil {
Asim Shankar08642822015-03-02 21:21:09 -0800224 return security.Discharge{}, fmt.Errorf("third-party caveat %v cannot be discharged for this context: %v", cav, err)
Ankure49a86a2014-11-11 18:52:43 -0800225 }
226 // Add a fakeTimeCaveat to be able to control discharge expiration via 'clock'.
Asim Shankar7283dd82015-02-03 19:35:58 -0800227 expiry, err := security.NewCaveat(fakeTimeCaveat, clock.Now())
228 if err != nil {
Asim Shankar08642822015-03-02 21:21:09 -0800229 return security.Discharge{}, fmt.Errorf("failed to create an expiration on the discharge: %v", err)
Asim Shankar7283dd82015-02-03 19:35:58 -0800230 }
Todd Wang4264e4b2015-04-16 22:43:40 -0700231 return call.Security().LocalPrincipal().MintDischarge(cav, expiry)
Ankure49a86a2014-11-11 18:52:43 -0800232}
233
Todd Wang5082a552015-04-02 10:56:11 -0700234func startServer(t *testing.T, ctx *context.T, principal security.Principal, sm stream.Manager, ns namespace.T, name string, disp rpc.Dispatcher, opts ...rpc.ServerOpt) (naming.Endpoint, rpc.Server) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700235 return startServerWS(t, ctx, principal, sm, ns, name, disp, noWebsocket, opts...)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800236}
237
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800238func endpointsToStrings(eps []naming.Endpoint) []string {
239 r := make([]string, len(eps))
240 for i, e := range eps {
241 r[i] = e.String()
242 }
243 sort.Strings(r)
244 return r
245}
246
Todd Wang5082a552015-04-02 10:56:11 -0700247func startServerWS(t *testing.T, ctx *context.T, principal security.Principal, sm stream.Manager, ns namespace.T, name string, disp rpc.Dispatcher, shouldUseWebsocket websocketMode, opts ...rpc.ServerOpt) (naming.Endpoint, rpc.Server) {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700248 vlog.VI(1).Info("InternalNewServer")
Todd Wangad492042015-04-17 15:58:40 -0700249 ctx, _ = v23.WithPrincipal(ctx, principal)
Suharsh Sivakumar59c423c2015-03-11 14:06:03 -0700250 server, err := testInternalNewServer(ctx, sm, ns, principal, opts...)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700251 if err != nil {
252 t.Errorf("InternalNewServer failed: %v", err)
253 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700254 vlog.VI(1).Info("server.Listen")
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800255 spec := listenSpec
256 if shouldUseWebsocket {
257 spec = listenWSSpec
258 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800259 eps, err := server.Listen(spec)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700260 if err != nil {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700261 t.Errorf("server.Listen failed: %v", err)
262 }
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700263 vlog.VI(1).Info("server.Serve")
Ankure49a86a2014-11-11 18:52:43 -0800264 if err := server.ServeDispatcher(name, disp); err != nil {
265 t.Errorf("server.ServeDispatcher failed: %v", err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700266 }
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800267
268 status := server.Status()
269 if got, want := endpointsToStrings(status.Endpoints), endpointsToStrings(eps); !reflect.DeepEqual(got, want) {
270 t.Fatalf("got %v, want %v", got, want)
271 }
272 names := status.Mounts.Names()
273 if len(names) != 1 || names[0] != name {
274 t.Fatalf("unexpected names: %v", names)
275 }
276 return eps[0], server
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700277}
278
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800279func loc(d int) string {
280 _, file, line, _ := runtime.Caller(d + 1)
281 return fmt.Sprintf("%s:%d", filepath.Base(file), line)
282}
283
Todd Wang5082a552015-04-02 10:56:11 -0700284func verifyMount(t *testing.T, ctx *context.T, ns namespace.T, name string) []string {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700285 me, err := ns.Resolve(ctx, name)
Cosmos Nicolaou9388ae42014-11-10 10:57:15 -0800286 if err != nil {
287 t.Errorf("%s: %s not found in mounttable", loc(1), name)
288 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700289 }
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800290 return me.Names()
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700291}
292
Todd Wang5082a552015-04-02 10:56:11 -0700293func verifyMountMissing(t *testing.T, ctx *context.T, ns namespace.T, name string) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700294 if me, err := ns.Resolve(ctx, name); err == nil {
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800295 names := me.Names()
Asim Shankarb547ea92015-02-17 18:49:45 -0800296 t.Errorf("%s: %s not supposed to be found in mounttable; got %d servers instead: %v (%+v)", loc(1), name, len(names), names, me)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700297 }
298}
299
Todd Wang5082a552015-04-02 10:56:11 -0700300func stopServer(t *testing.T, ctx *context.T, server rpc.Server, ns namespace.T, name string) {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700301 vlog.VI(1).Info("server.Stop")
Ankure49a86a2014-11-11 18:52:43 -0800302 new_name := "should_appear_in_mt/server"
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700303 verifyMount(t, ctx, ns, name)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700304
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700305 // publish a second name
Ankure49a86a2014-11-11 18:52:43 -0800306 if err := server.AddName(new_name); err != nil {
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700307 t.Errorf("server.Serve failed: %v", err)
308 }
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700309 verifyMount(t, ctx, ns, new_name)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700310
311 if err := server.Stop(); err != nil {
312 t.Errorf("server.Stop failed: %v", err)
313 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700314
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700315 verifyMountMissing(t, ctx, ns, name)
316 verifyMountMissing(t, ctx, ns, new_name)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700317
318 // Check that we can no longer serve after Stop.
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800319 err := server.AddName("name doesn't matter")
Todd Wang8fa38762015-03-25 14:04:59 -0700320 if err == nil || verror.ErrorID(err) != verror.ErrBadState.ID {
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700321 t.Errorf("either no error, or a wrong error was returned: %v", err)
322 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700323 vlog.VI(1).Info("server.Stop DONE")
324}
325
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800326// fakeWSName creates a name containing a endpoint address that forces
327// the use of websockets. It does so by resolving the original name
328// and choosing the 'ws' endpoint from the set of endpoints returned.
329// It must return a name since it'll be passed to StartCall.
Todd Wang5082a552015-04-02 10:56:11 -0700330func fakeWSName(ctx *context.T, ns namespace.T, name string) (string, error) {
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800331 // Find the ws endpoint and use that.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700332 me, err := ns.Resolve(ctx, name)
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800333 if err != nil {
334 return "", err
335 }
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800336 names := me.Names()
337 for _, s := range names {
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800338 if strings.Index(s, "@ws@") != -1 {
339 return s, nil
340 }
341 }
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800342 return "", fmt.Errorf("No ws endpoint found %v", names)
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800343}
344
Bogdan Caprita27953142014-05-12 11:41:42 -0700345type bundle struct {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700346 client rpc.Client
347 server rpc.Server
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700348 ep naming.Endpoint
Todd Wang5082a552015-04-02 10:56:11 -0700349 ns namespace.T
Bogdan Caprita27953142014-05-12 11:41:42 -0700350 sm stream.Manager
Ankure49a86a2014-11-11 18:52:43 -0800351 name string
Bogdan Caprita27953142014-05-12 11:41:42 -0700352}
353
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700354func (b bundle) cleanup(t *testing.T, ctx *context.T) {
Ankura3c97652014-07-17 20:01:21 -0700355 if b.server != nil {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700356 stopServer(t, ctx, b.server, b.ns, b.name)
Ankura3c97652014-07-17 20:01:21 -0700357 }
358 if b.client != nil {
359 b.client.Close()
360 }
Bogdan Caprita27953142014-05-12 11:41:42 -0700361}
362
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700363func createBundle(t *testing.T, ctx *context.T, server security.Principal, ts interface{}) (b bundle) {
364 return createBundleWS(t, ctx, server, ts, noWebsocket)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800365}
366
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700367func createBundleWS(t *testing.T, ctx *context.T, server security.Principal, ts interface{}, shouldUseWebsocket websocketMode) (b bundle) {
Bogdan Caprita27953142014-05-12 11:41:42 -0700368 b.sm = imanager.InternalNew(naming.FixedRoutingID(0x555555555))
Matt Rosencrantz9fe60822014-09-12 10:09:53 -0700369 b.ns = tnaming.NewSimpleNamespace()
Ankure49a86a2014-11-11 18:52:43 -0800370 b.name = "mountpoint/server"
Asim Shankar8f05c222014-10-06 22:08:19 -0700371 if server != nil {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700372 b.ep, b.server = startServerWS(t, ctx, server, b.sm, b.ns, b.name, testServerDisp{ts}, shouldUseWebsocket)
Ankura3c97652014-07-17 20:01:21 -0700373 }
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700374 var err error
375 if b.client, err = InternalNewClient(b.sm, b.ns); err != nil {
376 t.Fatalf("InternalNewClient failed: %v", err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700377 }
Bogdan Caprita27953142014-05-12 11:41:42 -0700378 return
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700379}
380
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800381func matchesErrorPattern(err error, id verror.IDAction, pattern string) bool {
Asim Shankar558ea012015-01-28 12:49:36 -0800382 if len(pattern) > 0 && err != nil && strings.Index(err.Error(), pattern) < 0 {
383 return false
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700384 }
Cosmos Nicolaou1bce7d12015-01-05 17:42:06 -0800385 if err == nil && id.ID == "" {
386 return true
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800387 }
Todd Wang8fa38762015-03-25 14:04:59 -0700388 return verror.ErrorID(err) == id.ID
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700389}
390
Todd Wang5082a552015-04-02 10:56:11 -0700391func runServer(t *testing.T, ctx *context.T, ns namespace.T, principal security.Principal, name string, obj interface{}, opts ...rpc.ServerOpt) stream.Manager {
Suharsh Sivakumar0902b7f2015-02-27 19:06:41 -0800392 rid, err := naming.NewRoutingID()
393 if err != nil {
394 t.Fatal(err)
395 }
396 sm := imanager.InternalNew(rid)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700397 server, err := testInternalNewServer(ctx, sm, ns, principal, opts...)
Suharsh Sivakumar0902b7f2015-02-27 19:06:41 -0800398 if err != nil {
399 t.Fatal(err)
400 }
401 if _, err := server.Listen(listenSpec); err != nil {
402 t.Fatal(err)
403 }
Asim Shankar149b4972015-04-23 13:29:58 -0700404 if err := server.Serve(name, obj, security.AllowEveryone()); err != nil {
Suharsh Sivakumar0902b7f2015-02-27 19:06:41 -0800405 t.Fatal(err)
406 }
407 return sm
408}
409
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800410func TestMultipleCallsToServeAndName(t *testing.T) {
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700411 sm := imanager.InternalNew(naming.FixedRoutingID(0x555555555))
Matt Rosencrantz9fe60822014-09-12 10:09:53 -0700412 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700413 ctx, shutdown := initForTest()
414 defer shutdown()
Asim Shankar4a698282015-03-21 21:59:18 -0700415 server, err := testInternalNewServer(ctx, sm, ns, testutil.NewPrincipal("server"))
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700416 if err != nil {
417 t.Errorf("InternalNewServer failed: %v", err)
418 }
Cosmos Nicolaouf8d4c2b2014-10-23 22:36:38 -0700419 _, err = server.Listen(listenSpec)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700420 if err != nil {
421 t.Errorf("server.Listen failed: %v", err)
422 }
423
424 disp := &testServerDisp{&testServer{}}
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800425 if err := server.ServeDispatcher("mountpoint/server", disp); err != nil {
426 t.Errorf("server.ServeDispatcher failed: %v", err)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700427 }
428
429 n1 := "mountpoint/server"
430 n2 := "should_appear_in_mt/server"
431 n3 := "should_appear_in_mt/server"
432 n4 := "should_not_appear_in_mt/server"
433
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700434 verifyMount(t, ctx, ns, n1)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700435
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800436 if server.ServeDispatcher(n2, disp) == nil {
437 t.Errorf("server.ServeDispatcher should have failed")
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700438 }
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800439
440 if err := server.Serve(n2, &testServer{}, nil); err == nil {
441 t.Errorf("server.Serve should have failed")
442 }
443
444 if err := server.AddName(n3); err != nil {
445 t.Errorf("server.AddName failed: %v", err)
446 }
447
448 if err := server.AddName(n3); err != nil {
449 t.Errorf("server.AddName failed: %v", err)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700450 }
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700451 verifyMount(t, ctx, ns, n2)
452 verifyMount(t, ctx, ns, n3)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700453
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800454 server.RemoveName(n1)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700455 verifyMountMissing(t, ctx, ns, n1)
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800456
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800457 server.RemoveName("some randome name")
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800458
459 if err := server.ServeDispatcher(n4, &testServerDisp{&testServer{}}); err == nil {
460 t.Errorf("server.ServeDispatcher should have failed")
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700461 }
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700462 verifyMountMissing(t, ctx, ns, n4)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700463
464 if err := server.Stop(); err != nil {
465 t.Errorf("server.Stop failed: %v", err)
466 }
467
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700468 verifyMountMissing(t, ctx, ns, n1)
469 verifyMountMissing(t, ctx, ns, n2)
470 verifyMountMissing(t, ctx, ns, n3)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700471}
472
Ankure49a86a2014-11-11 18:52:43 -0800473func TestRPCServerAuthorization(t *testing.T) {
Asim Shankar263c73b2015-03-19 18:31:26 -0700474 ctx, shutdown := initForTest()
475 defer shutdown()
476
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700477 const (
Asim Shankar263c73b2015-03-19 18:31:26 -0700478 publicKeyErr = "not matched by server key"
479 missingDischargeErr = "missing discharge"
480 expiryErr = "is after expiry"
481 allowedErr = "do not match any allowed server patterns"
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700482 )
Asim Shankar263c73b2015-03-19 18:31:26 -0700483 type O []rpc.CallOpt // shorthand
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700484 var (
Asim Shankar4a698282015-03-21 21:59:18 -0700485 pprovider, pclient, pserver = testutil.NewPrincipal("root"), testutil.NewPrincipal(), testutil.NewPrincipal()
Ankure49a86a2014-11-11 18:52:43 -0800486 pdischarger = pprovider
Asim Shankar558ea012015-01-28 12:49:36 -0800487 now = time.Now()
488 noErrID verror.IDAction
Ankure49a86a2014-11-11 18:52:43 -0800489
490 // Third-party caveats on blessings presented by server.
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -0700491 cavTPValid = mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/dischargeserver", mkCaveat(security.NewExpiryCaveat(now.Add(24*time.Hour))))
492 cavTPExpired = mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/dischargeserver", mkCaveat(security.NewExpiryCaveat(now.Add(-1*time.Second))))
Ankure49a86a2014-11-11 18:52:43 -0800493
494 // Server blessings.
495 bServer = bless(pprovider, pserver, "server")
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -0700496 bServerExpired = bless(pprovider, pserver, "expiredserver", mkCaveat(security.NewExpiryCaveat(time.Now().Add(-1*time.Second))))
Ankure49a86a2014-11-11 18:52:43 -0800497 bServerTPValid = bless(pprovider, pserver, "serverWithTPCaveats", cavTPValid)
Asim Shankar263c73b2015-03-19 18:31:26 -0700498 bServerTPExpired = bless(pprovider, pserver, "serverWithExpiredTPCaveats", cavTPExpired)
499 bOther = bless(pprovider, pserver, "other")
500 bTwoBlessings, _ = security.UnionOfBlessings(bServer, bOther)
Asim Shankar8f05c222014-10-06 22:08:19 -0700501
502 mgr = imanager.InternalNew(naming.FixedRoutingID(0x1111111))
503 ns = tnaming.NewSimpleNamespace()
504 tests = []struct {
Ankur50a5f392015-02-27 18:46:30 -0800505 server security.Blessings // blessings presented by the server to the client.
506 name string // name provided by the client to StartCall
Asim Shankar263c73b2015-03-19 18:31:26 -0700507 opts O // options provided to StartCall.
Ankur50a5f392015-02-27 18:46:30 -0800508 errID verror.IDAction
509 err string
Asim Shankar8f05c222014-10-06 22:08:19 -0700510 }{
Asim Shankar558ea012015-01-28 12:49:36 -0800511 // Client accepts talking to the server only if the
Asim Shankar263c73b2015-03-19 18:31:26 -0700512 // server presents valid blessings (and discharges)
513 // consistent with the ones published in the endpoint.
514 {bServer, "mountpoint/server", nil, noErrID, ""},
515 {bServerTPValid, "mountpoint/server", nil, noErrID, ""},
Asim Shankar8f05c222014-10-06 22:08:19 -0700516
Asim Shankar263c73b2015-03-19 18:31:26 -0700517 // Client will not talk to a server that presents
518 // expired blessings or is missing discharges.
519 {bServerExpired, "mountpoint/server", nil, verror.ErrNotTrusted, expiryErr},
520 {bServerTPExpired, "mountpoint/server", nil, verror.ErrNotTrusted, missingDischargeErr},
Asim Shankar558ea012015-01-28 12:49:36 -0800521
522 // Testing the AllowedServersPolicy option.
Asim Shankar263c73b2015-03-19 18:31:26 -0700523 {bServer, "mountpoint/server", O{options.AllowedServersPolicy{"otherroot"}}, verror.ErrNotTrusted, allowedErr},
524 {bServer, "mountpoint/server", O{options.AllowedServersPolicy{"root"}}, noErrID, ""},
525 {bTwoBlessings, "mountpoint/server", O{options.AllowedServersPolicy{"root/other"}}, noErrID, ""},
Ankur50a5f392015-02-27 18:46:30 -0800526
527 // Test the ServerPublicKey option.
Asim Shankar263c73b2015-03-19 18:31:26 -0700528 {bOther, "mountpoint/server", O{options.SkipServerEndpointAuthorization{}, options.ServerPublicKey{bOther.PublicKey()}}, noErrID, ""},
Asim Shankar4a698282015-03-21 21:59:18 -0700529 {bOther, "mountpoint/server", O{options.SkipServerEndpointAuthorization{}, options.ServerPublicKey{testutil.NewPrincipal("irrelevant").PublicKey()}}, verror.ErrNotTrusted, publicKeyErr},
Asim Shankar263c73b2015-03-19 18:31:26 -0700530
531 // Test the "paranoid" names, where the pattern is provided in the name.
532 {bServer, "__(root/server)/mountpoint/server", nil, noErrID, ""},
533 {bServer, "__(root/other)/mountpoint/server", nil, verror.ErrNotTrusted, allowedErr},
534 {bTwoBlessings, "__(root/server)/mountpoint/server", O{options.AllowedServersPolicy{"root/other"}}, noErrID, ""},
Asim Shankar8f05c222014-10-06 22:08:19 -0700535 }
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700536 )
Ankure49a86a2014-11-11 18:52:43 -0800537 // Start the discharge server.
Asim Shankar149b4972015-04-23 13:29:58 -0700538 _, dischargeServer := startServer(t, ctx, pdischarger, mgr, ns, "mountpoint/dischargeserver", testutil.LeafDispatcher(&dischargeServer{}, security.AllowEveryone()))
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700539 defer stopServer(t, ctx, dischargeServer, ns, "mountpoint/dischargeserver")
Ankure49a86a2014-11-11 18:52:43 -0800540
Asim Shankar558ea012015-01-28 12:49:36 -0800541 // Make the client and server principals trust root certificates from
542 // pprovider
Asim Shankar8f05c222014-10-06 22:08:19 -0700543 pclient.AddToRoots(pprovider.BlessingStore().Default())
544 pserver.AddToRoots(pprovider.BlessingStore().Default())
Asim Shankar263c73b2015-03-19 18:31:26 -0700545 // Set a blessing that the client is willing to share with servers
546 // (that are blessed by pprovider).
Ankur78b8b2a2015-02-04 20:16:28 -0800547 pclient.BlessingStore().Set(bless(pprovider, pclient, "client"), "root")
Asim Shankar558ea012015-01-28 12:49:36 -0800548
Todd Wangad492042015-04-17 15:58:40 -0700549 clientCtx, _ := v23.WithPrincipal(ctx, pclient)
Asim Shankar263c73b2015-03-19 18:31:26 -0700550 client, err := InternalNewClient(mgr, ns)
551 if err != nil {
552 t.Fatal(err)
553 }
554 defer client.Close()
555
556 var server rpc.Server
557 stop := func() {
558 if server != nil {
559 stopServer(t, ctx, server, ns, "mountpoint/server")
560 }
561 }
562 defer stop()
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800563 for i, test := range tests {
Asim Shankar263c73b2015-03-19 18:31:26 -0700564 stop() // Stop any server started in the previous test.
565 name := fmt.Sprintf("(#%d: Name:%q, Server:%q, opts:%v)", i, test.name, test.server, test.opts)
Ankure49a86a2014-11-11 18:52:43 -0800566 if err := pserver.BlessingStore().SetDefault(test.server); err != nil {
567 t.Fatalf("SetDefault failed on server's BlessingStore: %v", err)
568 }
Ankur78b8b2a2015-02-04 20:16:28 -0800569 if _, err := pserver.BlessingStore().Set(test.server, "root"); err != nil {
Ankure49a86a2014-11-11 18:52:43 -0800570 t.Fatalf("Set failed on server's BlessingStore: %v", err)
571 }
Asim Shankar263c73b2015-03-19 18:31:26 -0700572 _, server = startServer(t, ctx, pserver, mgr, ns, "mountpoint/server", testServerDisp{&testServer{}})
573 clientCtx, cancel := context.WithCancel(clientCtx)
574 call, err := client.StartCall(clientCtx, test.name, "Method", nil, test.opts...)
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800575 if !matchesErrorPattern(err, test.errID, test.err) {
Asim Shankarb547ea92015-02-17 18:49:45 -0800576 t.Errorf(`%s: client.StartCall: got error "%v", want to match "%v"`, name, err, test.err)
Asim Shankar2d731a92014-09-29 17:46:38 -0700577 } else if call != nil {
Asim Shankar8f05c222014-10-06 22:08:19 -0700578 blessings, proof := call.RemoteBlessings()
Asim Shankar2bf7b1e2015-02-27 00:45:12 -0800579 if proof.IsZero() {
580 t.Errorf("%s: Returned zero value for remote blessings", name)
Asim Shankar8f05c222014-10-06 22:08:19 -0700581 }
Asim Shankar558ea012015-01-28 12:49:36 -0800582 // Currently all tests are configured so that the only
583 // blessings presented by the server that are
584 // recognized by the client match the pattern
Ankur78b8b2a2015-02-04 20:16:28 -0800585 // "root"
586 if len(blessings) < 1 || !security.BlessingPattern("root").MatchedBy(blessings...) {
587 t.Errorf("%s: Client sees server as %v, expected a single blessing matching root", name, blessings)
Asim Shankar2d731a92014-09-29 17:46:38 -0700588 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700589 }
Matt Rosencrantzcc922c12014-11-28 20:28:59 -0800590 cancel()
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700591 }
592}
593
Asim Shankarb547ea92015-02-17 18:49:45 -0800594func TestServerManInTheMiddleAttack(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700595 ctx, shutdown := initForTest()
596 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -0700597 // Test scenario: A server mounts itself, but then some other service
598 // somehow "takes over" the network endpoint (a naughty router
599 // perhaps), thus trying to steal traffic.
600 var (
Asim Shankar4a698282015-03-21 21:59:18 -0700601 pclient = testutil.NewPrincipal("client")
602 pserver = testutil.NewPrincipal("server")
603 pattacker = testutil.NewPrincipal("attacker")
Asim Shankar263c73b2015-03-19 18:31:26 -0700604 )
605 // Client recognizes both the server and the attacker's blessings.
606 // (Though, it doesn't need to do the latter for the purposes of this
607 // test).
608 pclient.AddToRoots(pserver.BlessingStore().Default())
609 pclient.AddToRoots(pattacker.BlessingStore().Default())
Asim Shankarb547ea92015-02-17 18:49:45 -0800610
611 // Start up the attacker's server.
612 attacker, err := testInternalNewServer(
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700613 ctx,
Asim Shankarb547ea92015-02-17 18:49:45 -0800614 imanager.InternalNew(naming.FixedRoutingID(0xaaaaaaaaaaaaaaaa)),
615 // (To prevent the attacker for legitimately mounting on the
616 // namespace that the client will use, provide it with a
617 // different namespace).
618 tnaming.NewSimpleNamespace(),
Asim Shankar263c73b2015-03-19 18:31:26 -0700619 pattacker)
Asim Shankarb547ea92015-02-17 18:49:45 -0800620 if err != nil {
621 t.Fatal(err)
622 }
623 if _, err := attacker.Listen(listenSpec); err != nil {
624 t.Fatal(err)
625 }
626 if err := attacker.ServeDispatcher("mountpoint/server", testServerDisp{&testServer{}}); err != nil {
627 t.Fatal(err)
628 }
629 var ep naming.Endpoint
630 if status := attacker.Status(); len(status.Endpoints) < 1 {
631 t.Fatalf("Attacker server does not have an endpoint: %+v", status)
632 } else {
633 ep = status.Endpoints[0]
634 }
635
636 // The legitimate server would have mounted the same endpoint on the
Asim Shankar263c73b2015-03-19 18:31:26 -0700637 // namespace, but with different blessings.
Asim Shankarb547ea92015-02-17 18:49:45 -0800638 ns := tnaming.NewSimpleNamespace()
Asim Shankar263c73b2015-03-19 18:31:26 -0700639 ep.(*inaming.Endpoint).Blessings = []string{"server"}
640 if err := ns.Mount(ctx, "mountpoint/server", ep.Name(), time.Hour); err != nil {
Asim Shankarb547ea92015-02-17 18:49:45 -0800641 t.Fatal(err)
642 }
643
644 // The RPC call should fail because the blessings presented by the
645 // (attacker's) server are not consistent with the ones registered in
646 // the mounttable trusted by the client.
647 client, err := InternalNewClient(
648 imanager.InternalNew(naming.FixedRoutingID(0xcccccccccccccccc)),
Asim Shankar263c73b2015-03-19 18:31:26 -0700649 ns)
Asim Shankarb547ea92015-02-17 18:49:45 -0800650 if err != nil {
651 t.Fatal(err)
652 }
653 defer client.Close()
Todd Wangad492042015-04-17 15:58:40 -0700654 ctx, _ = v23.WithPrincipal(ctx, pclient)
Todd Wang8fa38762015-03-25 14:04:59 -0700655 if _, err := client.StartCall(ctx, "mountpoint/server", "Closure", nil); verror.ErrorID(err) != verror.ErrNotTrusted.ID {
Asim Shankarb547ea92015-02-17 18:49:45 -0800656 t.Errorf("Got error %v (errorid=%v), want errorid=%v", err, verror.ErrorID(err), verror.ErrNotTrusted.ID)
657 }
658 // But the RPC should succeed if the client explicitly
659 // decided to skip server authorization.
Asim Shankar263c73b2015-03-19 18:31:26 -0700660 if _, err := client.StartCall(ctx, "mountpoint/server", "Closure", nil, options.SkipServerEndpointAuthorization{}); err != nil {
Asim Shankarb547ea92015-02-17 18:49:45 -0800661 t.Errorf("Unexpected error(%v) when skipping server authorization", err)
662 }
663}
664
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800665type websocketMode bool
666type closeSendMode bool
667
668const (
669 useWebsocket websocketMode = true
670 noWebsocket websocketMode = false
671
672 closeSend closeSendMode = true
673 noCloseSend closeSendMode = false
674)
675
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700676func TestRPC(t *testing.T) {
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800677 testRPC(t, closeSend, noWebsocket)
678}
679
680func TestRPCWithWebsocket(t *testing.T) {
681 testRPC(t, closeSend, useWebsocket)
Tilak Sharma0c766112014-05-20 17:47:27 -0700682}
683
684// TestCloseSendOnFinish tests that Finish informs the server that no more
685// inputs will be sent by the client if CloseSend has not already done so.
686func TestRPCCloseSendOnFinish(t *testing.T) {
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800687 testRPC(t, noCloseSend, noWebsocket)
Tilak Sharma0c766112014-05-20 17:47:27 -0700688}
689
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800690func TestRPCCloseSendOnFinishWithWebsocket(t *testing.T) {
691 testRPC(t, noCloseSend, useWebsocket)
692}
693
694func testRPC(t *testing.T, shouldCloseSend closeSendMode, shouldUseWebsocket websocketMode) {
Asim Shankar263c73b2015-03-19 18:31:26 -0700695 ctx, shutdown := initForTest()
696 defer shutdown()
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700697 type v []interface{}
698 type testcase struct {
699 name string
700 method string
701 args v
702 streamArgs v
703 startErr error
704 results v
705 finishErr error
706 }
Asim Shankar8f05c222014-10-06 22:08:19 -0700707 var (
708 tests = []testcase{
709 {"mountpoint/server/suffix", "Closure", nil, nil, nil, nil, nil},
Todd Wange77f9952015-02-18 13:20:50 -0800710 {"mountpoint/server/suffix", "Error", nil, nil, nil, nil, errMethod},
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700711
Asim Shankar8f05c222014-10-06 22:08:19 -0700712 {"mountpoint/server/suffix", "Echo", v{"foo"}, nil, nil, v{`method:"Echo",suffix:"suffix",arg:"foo"`}, nil},
713 {"mountpoint/server/suffix/abc", "Echo", v{"bar"}, nil, nil, v{`method:"Echo",suffix:"suffix/abc",arg:"bar"`}, nil},
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700714
Asim Shankar8f05c222014-10-06 22:08:19 -0700715 {"mountpoint/server/suffix", "EchoUser", v{"foo", userType("bar")}, nil, nil, v{`method:"EchoUser",suffix:"suffix",arg:"foo"`, userType("bar")}, nil},
716 {"mountpoint/server/suffix/abc", "EchoUser", v{"baz", userType("bla")}, nil, nil, v{`method:"EchoUser",suffix:"suffix/abc",arg:"baz"`, userType("bla")}, nil},
Todd Wange77f9952015-02-18 13:20:50 -0800717 {"mountpoint/server/suffix", "Stream", v{"foo"}, v{userType("bar"), userType("baz")}, nil, v{`method:"Stream",suffix:"suffix",arg:"foo" bar baz`}, nil},
718 {"mountpoint/server/suffix/abc", "Stream", v{"123"}, v{userType("456"), userType("789")}, nil, v{`method:"Stream",suffix:"suffix/abc",arg:"123" 456 789`}, nil},
Asim Shankar8f05c222014-10-06 22:08:19 -0700719 {"mountpoint/server/suffix", "EchoBlessings", nil, nil, nil, v{"[server]", "[client]"}, nil},
Todd Wange77f9952015-02-18 13:20:50 -0800720 {"mountpoint/server/suffix", "EchoAndError", v{"bugs bunny"}, nil, nil, v{`method:"EchoAndError",suffix:"suffix",arg:"bugs bunny"`}, nil},
721 {"mountpoint/server/suffix", "EchoAndError", v{"error"}, nil, nil, nil, errMethod},
Matt Rosencrantz88be1182015-04-27 13:45:43 -0700722 {"mountpoint/server/suffix", "EchoLang", nil, nil, nil, v{"foolang"}, nil},
Asim Shankar8f05c222014-10-06 22:08:19 -0700723 }
724 name = func(t testcase) string {
725 return fmt.Sprintf("%s.%s(%v)", t.name, t.method, t.args)
726 }
727
Asim Shankar263c73b2015-03-19 18:31:26 -0700728 pclient, pserver = newClientServerPrincipals()
729 b = createBundleWS(t, ctx, pserver, &testServer{}, shouldUseWebsocket)
Asim Shankar8f05c222014-10-06 22:08:19 -0700730 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700731 defer b.cleanup(t, ctx)
Todd Wangad492042015-04-17 15:58:40 -0700732 ctx, _ = v23.WithPrincipal(ctx, pclient)
Matt Rosencrantz88be1182015-04-27 13:45:43 -0700733 ctx = i18n.WithLangID(ctx, "foolang")
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700734 for _, test := range tests {
735 vlog.VI(1).Infof("%s client.StartCall", name(test))
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800736 vname := test.name
737 if shouldUseWebsocket {
738 var err error
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700739 vname, err = fakeWSName(ctx, b.ns, vname)
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800740 if err != nil && err != test.startErr {
741 t.Errorf(`%s ns.Resolve got error "%v", want "%v"`, name(test), err, test.startErr)
742 continue
743 }
744 }
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700745 call, err := b.client.StartCall(ctx, vname, test.method, test.args)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700746 if err != test.startErr {
747 t.Errorf(`%s client.StartCall got error "%v", want "%v"`, name(test), err, test.startErr)
748 continue
749 }
750 for _, sarg := range test.streamArgs {
751 vlog.VI(1).Infof("%s client.Send(%v)", name(test), sarg)
752 if err := call.Send(sarg); err != nil {
753 t.Errorf(`%s call.Send(%v) got unexpected error "%v"`, name(test), sarg, err)
754 }
755 var u userType
756 if err := call.Recv(&u); err != nil {
757 t.Errorf(`%s call.Recv(%v) got unexpected error "%v"`, name(test), sarg, err)
758 }
759 if !reflect.DeepEqual(u, sarg) {
760 t.Errorf("%s call.Recv got value %v, want %v", name(test), u, sarg)
761 }
762 }
Tilak Sharma0c766112014-05-20 17:47:27 -0700763 if shouldCloseSend {
764 vlog.VI(1).Infof("%s call.CloseSend", name(test))
Asim Shankar062d4222014-08-18 11:14:42 -0700765 // When the method does not involve streaming
766 // arguments, the server gets all the arguments in
767 // StartCall and then sends a response without
768 // (unnecessarily) waiting for a CloseSend message from
769 // the client. If the server responds before the
770 // CloseSend call is made at the client, the CloseSend
771 // call will fail. Thus, only check for errors on
772 // CloseSend if there are streaming arguments to begin
773 // with (i.e., only if the server is expected to wait
774 // for the CloseSend notification).
775 if err := call.CloseSend(); err != nil && len(test.streamArgs) > 0 {
Tilak Sharma0c766112014-05-20 17:47:27 -0700776 t.Errorf(`%s call.CloseSend got unexpected error "%v"`, name(test), err)
777 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700778 }
779 vlog.VI(1).Infof("%s client.Finish", name(test))
780 results := makeResultPtrs(test.results)
781 err = call.Finish(results...)
Todd Wange77f9952015-02-18 13:20:50 -0800782 if got, want := err, test.finishErr; (got == nil) != (want == nil) {
783 t.Errorf(`%s call.Finish got error "%v", want "%v'`, name(test), got, want)
Todd Wang8fa38762015-03-25 14:04:59 -0700784 } else if want != nil && verror.ErrorID(got) != verror.ErrorID(want) {
Todd Wange77f9952015-02-18 13:20:50 -0800785 t.Errorf(`%s call.Finish got error "%v", want "%v"`, name(test), got, want)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700786 }
787 checkResultPtrs(t, name(test), results, test.results)
788 }
789}
790
Ken Ashcraft2b8309a2014-09-09 10:44:43 -0700791func TestMultipleFinish(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700792 ctx, shutdown := initForTest()
793 defer shutdown()
Ken Ashcraft2b8309a2014-09-09 10:44:43 -0700794 type v []interface{}
Asim Shankar263c73b2015-03-19 18:31:26 -0700795 var (
796 pclient, pserver = newClientServerPrincipals()
797 b = createBundle(t, ctx, pserver, &testServer{})
798 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700799 defer b.cleanup(t, ctx)
Todd Wangad492042015-04-17 15:58:40 -0700800 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700801 call, err := b.client.StartCall(ctx, "mountpoint/server/suffix", "Echo", v{"foo"})
Ken Ashcraft2b8309a2014-09-09 10:44:43 -0700802 if err != nil {
803 t.Fatalf(`client.StartCall got error "%v"`, err)
804 }
805 var results string
806 err = call.Finish(&results)
807 if err != nil {
808 t.Fatalf(`call.Finish got error "%v"`, err)
809 }
810 // Calling Finish a second time should result in a useful error.
Jiri Simsa074bf362015-02-17 09:29:45 -0800811 if err = call.Finish(&results); !matchesErrorPattern(err, verror.ErrBadState, "Finish has already been called") {
812 t.Fatalf(`got "%v", want "%v"`, err, verror.ErrBadState)
Ken Ashcraft2b8309a2014-09-09 10:44:43 -0700813 }
814}
815
Ankurdda16492015-04-07 12:35:42 -0700816// granter implements rpc.Granter.
817//
818// It returns the specified (security.Blessings, error) pair if either the
819// blessing or the error is specified. Otherwise it returns a blessing
820// derived from the local blessings of the current call.
Asim Shankarb54d7642014-06-05 13:08:04 -0700821type granter struct {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700822 rpc.CallOpt
Asim Shankar8f05c222014-10-06 22:08:19 -0700823 b security.Blessings
Asim Shankarb54d7642014-06-05 13:08:04 -0700824 err error
825}
826
Todd Wang4264e4b2015-04-16 22:43:40 -0700827func (g granter) Grant(ctx *context.T, call security.Call) (security.Blessings, error) {
Ankurdda16492015-04-07 12:35:42 -0700828 if !g.b.IsZero() || g.err != nil {
829 return g.b, g.err
830 }
Ankurdda16492015-04-07 12:35:42 -0700831 return call.LocalPrincipal().Bless(call.RemoteBlessings().PublicKey(), call.LocalBlessings(), "blessed", security.UnconstrainedUse())
832}
Asim Shankarb54d7642014-06-05 13:08:04 -0700833
Asim Shankar8f05c222014-10-06 22:08:19 -0700834func TestGranter(t *testing.T) {
835 var (
Asim Shankar263c73b2015-03-19 18:31:26 -0700836 pclient, pserver = newClientServerPrincipals()
837 ctx, shutdown = initForTest()
838 b = createBundle(t, ctx, pserver, &testServer{})
Asim Shankar8f05c222014-10-06 22:08:19 -0700839 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700840 defer shutdown()
841 defer b.cleanup(t, ctx)
842
Todd Wangad492042015-04-17 15:58:40 -0700843 ctx, _ = v23.WithPrincipal(ctx, pclient)
Asim Shankarb54d7642014-06-05 13:08:04 -0700844 tests := []struct {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700845 granter rpc.Granter
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800846 startErrID, finishErrID verror.IDAction
Asim Shankarb54d7642014-06-05 13:08:04 -0700847 blessing, starterr, finisherr string
848 }{
Asim Shankar2bf7b1e2015-02-27 00:45:12 -0800849 {blessing: ""},
Asim Shankarb18a44f2014-10-21 20:25:07 -0700850 {granter: granter{b: bless(pclient, pserver, "blessed")}, blessing: "client/blessed"},
Jiri Simsa074bf362015-02-17 09:29:45 -0800851 {granter: granter{err: errors.New("hell no")}, startErrID: verror.ErrNotTrusted, starterr: "hell no"},
Ankurdda16492015-04-07 12:35:42 -0700852 {granter: granter{}, blessing: "client/blessed"},
Jiri Simsa074bf362015-02-17 09:29:45 -0800853 {granter: granter{b: pclient.BlessingStore().Default()}, finishErrID: verror.ErrNoAccess, finisherr: "blessing granted not bound to this server"},
Asim Shankarb54d7642014-06-05 13:08:04 -0700854 }
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800855 for i, test := range tests {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700856 call, err := b.client.StartCall(ctx, "mountpoint/server/suffix", "EchoGrantedBlessings", []interface{}{"argument"}, test.granter)
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800857 if !matchesErrorPattern(err, test.startErrID, test.starterr) {
858 t.Errorf("%d: %+v: StartCall returned error %v", i, test, err)
Asim Shankarb54d7642014-06-05 13:08:04 -0700859 }
860 if err != nil {
861 continue
862 }
863 var result, blessing string
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800864 if err = call.Finish(&result, &blessing); !matchesErrorPattern(err, test.finishErrID, test.finisherr) {
Asim Shankarb54d7642014-06-05 13:08:04 -0700865 t.Errorf("%+v: Finish returned error %v", test, err)
866 }
867 if err != nil {
868 continue
869 }
870 if result != "argument" || blessing != test.blessing {
871 t.Errorf("%+v: Got (%q, %q)", test, result, blessing)
872 }
873 }
874}
875
Asim Shankarf4864f42014-11-25 18:53:05 -0800876// dischargeTestServer implements the discharge service. Always fails to
877// issue a discharge, but records the impetus and traceid of the RPC call.
878type dischargeTestServer struct {
879 p security.Principal
880 impetus []security.DischargeImpetus
Benjamin Prosnitzc97fe192015-02-03 10:33:25 -0800881 traceid []uniqueid.Id
Asim Shankara94e5072014-08-19 18:18:36 -0700882}
883
Todd Wang54feabe2015-04-15 23:38:26 -0700884func (s *dischargeTestServer) Discharge(ctx *context.T, _ rpc.ServerCall, cav security.Caveat, impetus security.DischargeImpetus) (security.Discharge, error) {
Asim Shankarc8cfcf12014-11-20 12:26:58 -0800885 s.impetus = append(s.impetus, impetus)
Todd Wang54feabe2015-04-15 23:38:26 -0700886 s.traceid = append(s.traceid, vtrace.GetSpan(ctx).Trace())
Asim Shankar08642822015-03-02 21:21:09 -0800887 return security.Discharge{}, fmt.Errorf("discharges not issued")
Asim Shankara94e5072014-08-19 18:18:36 -0700888}
889
Benjamin Prosnitzc97fe192015-02-03 10:33:25 -0800890func (s *dischargeTestServer) Release() ([]security.DischargeImpetus, []uniqueid.Id) {
Asim Shankarf4864f42014-11-25 18:53:05 -0800891 impetus, traceid := s.impetus, s.traceid
892 s.impetus, s.traceid = nil, nil
893 return impetus, traceid
Asim Shankarc8cfcf12014-11-20 12:26:58 -0800894}
895
Asim Shankarf4864f42014-11-25 18:53:05 -0800896func TestDischargeImpetusAndContextPropagation(t *testing.T) {
Asim Shankar263c73b2015-03-19 18:31:26 -0700897 ctx, shutdown := initForTest()
898 defer shutdown()
Asim Shankara94e5072014-08-19 18:18:36 -0700899 var (
Asim Shankar4a698282015-03-21 21:59:18 -0700900 pserver = testutil.NewPrincipal("server")
901 pdischarger = testutil.NewPrincipal("discharger")
902 pclient = testutil.NewPrincipal("client")
Asim Shankar8f05c222014-10-06 22:08:19 -0700903 sm = imanager.InternalNew(naming.FixedRoutingID(0x555555555))
904 ns = tnaming.NewSimpleNamespace()
Asim Shankara94e5072014-08-19 18:18:36 -0700905
Asim Shankar263c73b2015-03-19 18:31:26 -0700906 // Setup the client so that it shares a blessing with a third-party caveat with the server.
907 setClientBlessings = func(req security.ThirdPartyRequirements) security.Principal {
Asim Shankar7283dd82015-02-03 19:35:58 -0800908 cav, err := security.NewPublicKeyCaveat(pdischarger.PublicKey(), "mountpoint/discharger", req, security.UnconstrainedUse())
Asim Shankara94e5072014-08-19 18:18:36 -0700909 if err != nil {
Asim Shankar8f05c222014-10-06 22:08:19 -0700910 t.Fatalf("Failed to create ThirdPartyCaveat(%+v): %v", req, err)
Asim Shankara94e5072014-08-19 18:18:36 -0700911 }
Asim Shankarf4864f42014-11-25 18:53:05 -0800912 b, err := pclient.BlessSelf("client_for_server", cav)
Asim Shankar8f05c222014-10-06 22:08:19 -0700913 if err != nil {
914 t.Fatalf("BlessSelf failed: %v", err)
915 }
Asim Shankar8f05c222014-10-06 22:08:19 -0700916 pclient.BlessingStore().Set(b, "server")
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700917 return pclient
Asim Shankara94e5072014-08-19 18:18:36 -0700918 }
919 )
Asim Shankarf4864f42014-11-25 18:53:05 -0800920 // Initialize the client principal.
921 // It trusts both the application server and the discharger.
922 pclient.AddToRoots(pserver.BlessingStore().Default())
923 pclient.AddToRoots(pdischarger.BlessingStore().Default())
Asim Shankarf4864f42014-11-25 18:53:05 -0800924
925 // Setup the discharge server.
926 var tester dischargeTestServer
Suharsh Sivakumar59c423c2015-03-11 14:06:03 -0700927 dischargeServer, err := testInternalNewServer(ctx, sm, ns, pdischarger)
Asim Shankara94e5072014-08-19 18:18:36 -0700928 if err != nil {
929 t.Fatal(err)
930 }
Asim Shankarf4864f42014-11-25 18:53:05 -0800931 defer dischargeServer.Stop()
932 if _, err := dischargeServer.Listen(listenSpec); err != nil {
933 t.Fatal(err)
934 }
935 if err := dischargeServer.Serve("mountpoint/discharger", &tester, &testServerAuthorizer{}); err != nil {
Asim Shankara94e5072014-08-19 18:18:36 -0700936 t.Fatal(err)
937 }
938
Asim Shankarf4864f42014-11-25 18:53:05 -0800939 // Setup the application server.
Suharsh Sivakumar59c423c2015-03-11 14:06:03 -0700940 appServer, err := testInternalNewServer(ctx, sm, ns, pserver)
Asim Shankarf4864f42014-11-25 18:53:05 -0800941 if err != nil {
942 t.Fatal(err)
943 }
944 defer appServer.Stop()
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800945 eps, err := appServer.Listen(listenSpec)
Asim Shankarf4864f42014-11-25 18:53:05 -0800946 if err != nil {
947 t.Fatal(err)
948 }
949 // TODO(bjornick,cnicolaou,ashankar): This is a hack to workaround the
950 // fact that a single Listen on the "tcp" protocol followed by a call
951 // to Serve(<name>, ...) transparently creates two endpoints (one for
952 // tcp, one for websockets) and maps both to <name> via a mount.
953 // Because all endpoints to a name are tried in a parallel, this
954 // transparency makes this test hard to follow (many discharge fetch
955 // attempts are made - one for VIF authentication, one for VC
956 // authentication and one for the actual RPC - and having them be made
957 // to two different endpoints in parallel leads to a lot of
958 // non-determinism). The last plan of record known by the author of
959 // this comment was to stop this sly creation of two endpoints and
960 // require that they be done explicitly. When that happens, this hack
961 // can go away, but till then, this workaround allows the test to be
962 // more predictable by ensuring there is only one VIF/VC/Flow to the
963 // server.
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800964 object := naming.JoinAddressName(eps[0].String(), "object") // instead of "mountpoint/object"
Asim Shankarf4864f42014-11-25 18:53:05 -0800965 if err := appServer.Serve("mountpoint/object", &testServer{}, &testServerAuthorizer{}); err != nil {
966 t.Fatal(err)
967 }
Asim Shankara94e5072014-08-19 18:18:36 -0700968 tests := []struct {
969 Requirements security.ThirdPartyRequirements
970 Impetus security.DischargeImpetus
971 }{
972 { // No requirements, no impetus
973 Requirements: security.ThirdPartyRequirements{},
974 Impetus: security.DischargeImpetus{},
975 },
976 { // Require everything
977 Requirements: security.ThirdPartyRequirements{ReportServer: true, ReportMethod: true, ReportArguments: true},
Todd Wangb31da592015-02-20 12:50:39 -0800978 Impetus: security.DischargeImpetus{Server: []security.BlessingPattern{"server"}, Method: "Method", Arguments: []*vdl.Value{vdl.StringValue("argument")}},
Asim Shankara94e5072014-08-19 18:18:36 -0700979 },
980 { // Require only the method name
981 Requirements: security.ThirdPartyRequirements{ReportMethod: true},
982 Impetus: security.DischargeImpetus{Method: "Method"},
983 },
984 }
985
Ankur50a5f392015-02-27 18:46:30 -0800986 for _, test := range tests {
Asim Shankar263c73b2015-03-19 18:31:26 -0700987 pclient := setClientBlessings(test.Requirements)
Todd Wangad492042015-04-17 15:58:40 -0700988 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700989 client, err := InternalNewClient(sm, ns)
Asim Shankara94e5072014-08-19 18:18:36 -0700990 if err != nil {
991 t.Fatalf("InternalNewClient(%+v) failed: %v", test.Requirements, err)
992 }
993 defer client.Close()
Matt Rosencrantz5f98d942015-01-08 13:48:30 -0800994 tid := vtrace.GetSpan(ctx).Trace()
Asim Shankara94e5072014-08-19 18:18:36 -0700995 // StartCall should fetch the discharge, do not worry about finishing the RPC - do not care about that for this test.
Asim Shankarf4864f42014-11-25 18:53:05 -0800996 if _, err := client.StartCall(ctx, object, "Method", []interface{}{"argument"}); err != nil {
Asim Shankara94e5072014-08-19 18:18:36 -0700997 t.Errorf("StartCall(%+v) failed: %v", test.Requirements, err)
998 continue
999 }
Asim Shankarf4864f42014-11-25 18:53:05 -08001000 impetus, traceid := tester.Release()
Ankur50a5f392015-02-27 18:46:30 -08001001 // There should have been exactly 1 attempt to fetch discharges when making
1002 // the RPC to the remote object.
1003 if len(impetus) != 1 || len(traceid) != 1 {
1004 t.Errorf("Test %+v: Got (%d, %d) (#impetus, #traceid), wanted exactly one", test.Requirements, len(impetus), len(traceid))
Asim Shankarf4864f42014-11-25 18:53:05 -08001005 continue
1006 }
1007 // VC creation does not have any "impetus", it is established without
1008 // knowledge of the context of the RPC. So ignore that.
1009 //
1010 // TODO(ashankar): Should the impetus of the RPC that initiated the
1011 // VIF/VC creation be propagated?
1012 if got, want := impetus[len(impetus)-1], test.Impetus; !reflect.DeepEqual(got, want) {
1013 t.Errorf("Test %+v: Got impetus %v, want %v", test.Requirements, got, want)
1014 }
1015 // But the context used for all of this should be the same
1016 // (thereby allowing debug traces to link VIF/VC creation with
1017 // the RPC that initiated them).
1018 for idx, got := range traceid {
1019 if !reflect.DeepEqual(got, tid) {
1020 t.Errorf("Test %+v: %d - Got trace id %q, want %q", test.Requirements, idx, hex.EncodeToString(got[:]), hex.EncodeToString(tid[:]))
1021 }
Asim Shankara94e5072014-08-19 18:18:36 -07001022 }
1023 }
1024}
1025
Ankure49a86a2014-11-11 18:52:43 -08001026func TestRPCClientAuthorization(t *testing.T) {
1027 type v []interface{}
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001028 var (
Asim Shankar8f05c222014-10-06 22:08:19 -07001029 // Principals
Asim Shankar4a698282015-03-21 21:59:18 -07001030 pclient, pserver = testutil.NewPrincipal("client"), testutil.NewPrincipal("server")
1031 pdischarger = testutil.NewPrincipal("discharger")
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001032
Asim Shankar8f05c222014-10-06 22:08:19 -07001033 now = time.Now()
1034
Ankure49a86a2014-11-11 18:52:43 -08001035 serverName = "mountpoint/server"
1036 dischargeServerName = "mountpoint/dischargeserver"
1037
Asim Shankar8f05c222014-10-06 22:08:19 -07001038 // Caveats on blessings to the client: First-party caveats
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001039 cavOnlyEcho = mkCaveat(security.NewMethodCaveat("Echo"))
1040 cavExpired = mkCaveat(security.NewExpiryCaveat(now.Add(-1 * time.Second)))
Asim Shankar8f05c222014-10-06 22:08:19 -07001041 // Caveats on blessings to the client: Third-party caveats
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001042 cavTPValid = mkThirdPartyCaveat(pdischarger.PublicKey(), dischargeServerName, mkCaveat(security.NewExpiryCaveat(now.Add(24*time.Hour))))
1043 cavTPExpired = mkThirdPartyCaveat(pdischarger.PublicKey(), dischargeServerName, mkCaveat(security.NewExpiryCaveat(now.Add(-1*time.Second))))
Asim Shankar8f05c222014-10-06 22:08:19 -07001044
1045 // Client blessings that will be tested.
1046 bServerClientOnlyEcho = bless(pserver, pclient, "onlyecho", cavOnlyEcho)
1047 bServerClientExpired = bless(pserver, pclient, "expired", cavExpired)
1048 bServerClientTPValid = bless(pserver, pclient, "dischargeable_third_party_caveat", cavTPValid)
1049 bServerClientTPExpired = bless(pserver, pclient, "expired_third_party_caveat", cavTPExpired)
1050 bClient = pclient.BlessingStore().Default()
1051 bRandom, _ = pclient.BlessSelf("random")
Ankure49a86a2014-11-11 18:52:43 -08001052
1053 mgr = imanager.InternalNew(naming.FixedRoutingID(0x1111111))
1054 ns = tnaming.NewSimpleNamespace()
1055 tests = []struct {
1056 blessings security.Blessings // Blessings used by the client
1057 name string // object name on which the method is invoked
1058 method string
1059 args v
1060 results v
1061 authorized bool // Whether or not the RPC should be authorized by the server.
1062 }{
1063 // There are three different authorization policies (security.Authorizer implementations)
1064 // used by the server, depending on the suffix (see testServerDisp.Lookup):
1065 // - nilAuth suffix: the default authorization policy (only delegates of or delegators of the server can call RPCs)
Benjamin Prosnitzb60efb92015-03-11 17:47:43 -07001066 // - aclAuth suffix: the AccessList only allows blessings matching the patterns "server" or "client"
Ankure49a86a2014-11-11 18:52:43 -08001067 // - other suffixes: testServerAuthorizer allows any principal to call any method except "Unauthorized"
1068
1069 // Expired blessings should fail nilAuth and aclAuth (which care about names), but should succeed on
1070 // other suffixes (which allow all blessings), unless calling the Unauthorized method.
1071 {bServerClientExpired, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, false},
1072 {bServerClientExpired, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, false},
1073 {bServerClientExpired, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1074 {bServerClientExpired, "mountpoint/server/suffix", "Unauthorized", nil, v{""}, false},
1075
1076 // Same for blessings that should fail to obtain a discharge for the third party caveat.
1077 {bServerClientTPExpired, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, false},
1078 {bServerClientTPExpired, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, false},
1079 {bServerClientTPExpired, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1080 {bServerClientTPExpired, "mountpoint/server/suffix", "Unauthorized", nil, v{""}, false},
1081
1082 // The "server/client" blessing (with MethodCaveat("Echo")) should satisfy all authorization policies
1083 // when "Echo" is called.
1084 {bServerClientOnlyEcho, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, true},
1085 {bServerClientOnlyEcho, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, true},
1086 {bServerClientOnlyEcho, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1087
1088 // The "server/client" blessing (with MethodCaveat("Echo")) should satisfy no authorization policy
1089 // when any other method is invoked, except for the testServerAuthorizer policy (which will
1090 // not recognize the blessing "server/onlyecho", but it would authorize anyone anyway).
1091 {bServerClientOnlyEcho, "mountpoint/server/nilAuth", "Closure", nil, nil, false},
1092 {bServerClientOnlyEcho, "mountpoint/server/aclAuth", "Closure", nil, nil, false},
1093 {bServerClientOnlyEcho, "mountpoint/server/suffix", "Closure", nil, nil, true},
1094
1095 // The "client" blessing doesn't satisfy the default authorization policy, but does satisfy
Benjamin Prosnitzb60efb92015-03-11 17:47:43 -07001096 // the AccessList and the testServerAuthorizer policy.
Ankure49a86a2014-11-11 18:52:43 -08001097 {bClient, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, false},
1098 {bClient, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, true},
1099 {bClient, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1100 {bClient, "mountpoint/server/suffix", "Unauthorized", nil, v{""}, false},
1101
Benjamin Prosnitzb60efb92015-03-11 17:47:43 -07001102 // The "random" blessing does not satisfy either the default policy or the AccessList, but does
Ankure49a86a2014-11-11 18:52:43 -08001103 // satisfy testServerAuthorizer.
1104 {bRandom, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, false},
1105 {bRandom, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, false},
1106 {bRandom, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1107 {bRandom, "mountpoint/server/suffix", "Unauthorized", nil, v{""}, false},
1108
1109 // The "server/dischargeable_third_party_caveat" blessing satisfies all policies.
1110 // (the discharges should be fetched).
1111 {bServerClientTPValid, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, true},
1112 {bServerClientTPValid, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, true},
1113 {bServerClientTPValid, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1114 {bServerClientTPValid, "mountpoint/server/suffix", "Unauthorized", nil, v{""}, false},
1115 }
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001116 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001117
1118 ctx, shutdown := initForTest()
1119 defer shutdown()
Ankure49a86a2014-11-11 18:52:43 -08001120 // Start the main server.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001121 _, server := startServer(t, ctx, pserver, mgr, ns, serverName, testServerDisp{&testServer{}})
1122 defer stopServer(t, ctx, server, ns, serverName)
Ankure49a86a2014-11-11 18:52:43 -08001123
1124 // Start the discharge server.
Asim Shankar149b4972015-04-23 13:29:58 -07001125 _, dischargeServer := startServer(t, ctx, pdischarger, mgr, ns, dischargeServerName, testutil.LeafDispatcher(&dischargeServer{}, security.AllowEveryone()))
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001126 defer stopServer(t, ctx, dischargeServer, ns, dischargeServerName)
Ankure49a86a2014-11-11 18:52:43 -08001127
Ankur78b8b2a2015-02-04 20:16:28 -08001128 // The server should recognize the client principal as an authority on "client" and "random" blessings.
Asim Shankar8f05c222014-10-06 22:08:19 -07001129 pserver.AddToRoots(bClient)
1130 pserver.AddToRoots(bRandom)
Ankure49a86a2014-11-11 18:52:43 -08001131 // And the client needs to recognize the server's and discharger's blessings to decide which of its
1132 // own blessings to share.
Asim Shankar8f05c222014-10-06 22:08:19 -07001133 pclient.AddToRoots(pserver.BlessingStore().Default())
Ankuredd74ee2015-03-04 16:38:45 -08001134 pclient.AddToRoots(pdischarger.BlessingStore().Default())
1135 // Set a blessing on the client's blessing store to be presented to the discharge server.
1136 pclient.BlessingStore().Set(pclient.BlessingStore().Default(), "discharger")
Asim Shankar4a698282015-03-21 21:59:18 -07001137 // testutil.NewPrincipal sets up a principal that shares blessings with all servers, undo that.
Asim Shankar2bf7b1e2015-02-27 00:45:12 -08001138 pclient.BlessingStore().Set(security.Blessings{}, security.AllPrincipals)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001139
Ankuredd74ee2015-03-04 16:38:45 -08001140 for i, test := range tests {
1141 name := fmt.Sprintf("#%d: %q.%s(%v) by %v", i, test.name, test.method, test.args, test.blessings)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001142 client, err := InternalNewClient(mgr, ns)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001143 if err != nil {
1144 t.Fatalf("InternalNewClient failed: %v", err)
1145 }
1146 defer client.Close()
Ankure49a86a2014-11-11 18:52:43 -08001147
Asim Shankar8f05c222014-10-06 22:08:19 -07001148 pclient.BlessingStore().Set(test.blessings, "server")
Todd Wangad492042015-04-17 15:58:40 -07001149 ctx, _ := v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001150 err = client.Call(ctx, test.name, test.method, test.args, makeResultPtrs(test.results))
Asim Shankar8f05c222014-10-06 22:08:19 -07001151 if err != nil && test.authorized {
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001152 t.Errorf(`%s client.Call got error: "%v", wanted the RPC to succeed`, name, err)
Asim Shankar8f05c222014-10-06 22:08:19 -07001153 } else if err == nil && !test.authorized {
1154 t.Errorf("%s call.Finish succeeded, expected authorization failure", name)
Todd Wang8fa38762015-03-25 14:04:59 -07001155 } else if !test.authorized && verror.ErrorID(err) != verror.ErrNoAccess.ID {
Jiri Simsa074bf362015-02-17 09:29:45 -08001156 t.Errorf("%s. call.Finish returned error %v(%v), wanted %v", name, verror.ErrorID(verror.Convert(verror.ErrNoAccess, nil, err)), err, verror.ErrNoAccess)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001157 }
1158 }
1159}
1160
Asim Shankar263c73b2015-03-19 18:31:26 -07001161// singleBlessingStore implements security.BlessingStore. It is a
Ankurb905dae2015-03-04 12:38:20 -08001162// BlessingStore that marks the last blessing that was set on it as
1163// shareable with any peer. It does not care about the public key that
1164// blessing being set is bound to.
Asim Shankar263c73b2015-03-19 18:31:26 -07001165type singleBlessingStore struct {
Ankurb905dae2015-03-04 12:38:20 -08001166 b security.Blessings
1167}
1168
Asim Shankar263c73b2015-03-19 18:31:26 -07001169func (s *singleBlessingStore) Set(b security.Blessings, _ security.BlessingPattern) (security.Blessings, error) {
Ankurb905dae2015-03-04 12:38:20 -08001170 s.b = b
1171 return security.Blessings{}, nil
1172}
Asim Shankar263c73b2015-03-19 18:31:26 -07001173func (s *singleBlessingStore) ForPeer(...string) security.Blessings {
Ankurb905dae2015-03-04 12:38:20 -08001174 return s.b
1175}
Asim Shankar263c73b2015-03-19 18:31:26 -07001176func (*singleBlessingStore) SetDefault(b security.Blessings) error {
Ankurb905dae2015-03-04 12:38:20 -08001177 return nil
1178}
Asim Shankar263c73b2015-03-19 18:31:26 -07001179func (*singleBlessingStore) Default() security.Blessings {
Ankurb905dae2015-03-04 12:38:20 -08001180 return security.Blessings{}
1181}
Asim Shankar263c73b2015-03-19 18:31:26 -07001182func (*singleBlessingStore) PublicKey() security.PublicKey {
Ankurb905dae2015-03-04 12:38:20 -08001183 return nil
1184}
Asim Shankar263c73b2015-03-19 18:31:26 -07001185func (*singleBlessingStore) DebugString() string {
Ankurb905dae2015-03-04 12:38:20 -08001186 return ""
1187}
Asim Shankar263c73b2015-03-19 18:31:26 -07001188func (*singleBlessingStore) PeerBlessings() map[security.BlessingPattern]security.Blessings {
Ankurb905dae2015-03-04 12:38:20 -08001189 return nil
1190}
1191
Asim Shankar263c73b2015-03-19 18:31:26 -07001192// singleBlessingPrincipal implements security.Principal. It is a wrapper over
Ankurb905dae2015-03-04 12:38:20 -08001193// a security.Principal that intercepts all invocations on the
Asim Shankar263c73b2015-03-19 18:31:26 -07001194// principal's BlessingStore and serves them via a singleBlessingStore.
1195type singleBlessingPrincipal struct {
Ankurb905dae2015-03-04 12:38:20 -08001196 security.Principal
Asim Shankar263c73b2015-03-19 18:31:26 -07001197 b singleBlessingStore
Ankurb905dae2015-03-04 12:38:20 -08001198}
1199
Asim Shankar263c73b2015-03-19 18:31:26 -07001200func (p *singleBlessingPrincipal) BlessingStore() security.BlessingStore {
Ankurb905dae2015-03-04 12:38:20 -08001201 return &p.b
1202}
1203
1204func TestRPCClientBlessingsPublicKey(t *testing.T) {
Asim Shankar263c73b2015-03-19 18:31:26 -07001205 ctx, shutdown := initForTest()
1206 defer shutdown()
Ankurb905dae2015-03-04 12:38:20 -08001207 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001208 pprovider, pserver = testutil.NewPrincipal("root"), testutil.NewPrincipal("server")
1209 pclient = &singleBlessingPrincipal{Principal: testutil.NewPrincipal("client")}
Ankurb905dae2015-03-04 12:38:20 -08001210
1211 bserver = bless(pprovider, pserver, "server")
1212 bclient = bless(pprovider, pclient, "client")
Asim Shankar4a698282015-03-21 21:59:18 -07001213 bvictim = bless(pprovider, testutil.NewPrincipal("victim"), "victim")
Ankurb905dae2015-03-04 12:38:20 -08001214 )
Ankurb905dae2015-03-04 12:38:20 -08001215 // Make the client and server trust blessings from pprovider.
1216 pclient.AddToRoots(pprovider.BlessingStore().Default())
1217 pserver.AddToRoots(pprovider.BlessingStore().Default())
1218
Asim Shankar263c73b2015-03-19 18:31:26 -07001219 // Make the server present bserver to all clients and start the server.
Ankurb905dae2015-03-04 12:38:20 -08001220 pserver.BlessingStore().SetDefault(bserver)
Asim Shankar263c73b2015-03-19 18:31:26 -07001221 b := createBundle(t, ctx, pserver, &testServer{})
1222 defer b.cleanup(t, ctx)
1223
Todd Wangad492042015-04-17 15:58:40 -07001224 ctx, _ = v23.WithPrincipal(ctx, pclient)
Ankurb905dae2015-03-04 12:38:20 -08001225 tests := []struct {
1226 blessings security.Blessings
1227 errID verror.IDAction
1228 err string
1229 }{
1230 {blessings: bclient},
1231 // server disallows clients from authenticating with blessings not bound to
1232 // the client principal's public key
1233 {blessings: bvictim, errID: verror.ErrNoAccess, err: "bound to a different public key"},
Ankurb905dae2015-03-04 12:38:20 -08001234 {blessings: bserver, errID: verror.ErrNoAccess, err: "bound to a different public key"},
1235 }
1236 for i, test := range tests {
1237 name := fmt.Sprintf("%d: Client RPCing with blessings %v", i, test.blessings)
Ankurb905dae2015-03-04 12:38:20 -08001238 pclient.BlessingStore().Set(test.blessings, "root")
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001239 if err := b.client.Call(ctx, "mountpoint/server/suffix", "Closure", nil, nil); !matchesErrorPattern(err, test.errID, test.err) {
1240 t.Errorf("%v: client.Call returned error %v", name, err)
Ankurb905dae2015-03-04 12:38:20 -08001241 continue
1242 }
1243 }
1244}
1245
Ankuredd74ee2015-03-04 16:38:45 -08001246func TestServerLocalBlessings(t *testing.T) {
Asim Shankar263c73b2015-03-19 18:31:26 -07001247 ctx, shutdown := initForTest()
1248 defer shutdown()
Ankuredd74ee2015-03-04 16:38:45 -08001249 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001250 pprovider, pclient, pserver = testutil.NewPrincipal("root"), testutil.NewPrincipal("client"), testutil.NewPrincipal("server")
Ankuredd74ee2015-03-04 16:38:45 -08001251 pdischarger = pprovider
1252
1253 mgr = imanager.InternalNew(naming.FixedRoutingID(0x1111111))
1254 ns = tnaming.NewSimpleNamespace()
1255
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001256 tpCav = mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/dischargeserver", mkCaveat(security.NewExpiryCaveat(time.Now().Add(time.Hour))))
Ankuredd74ee2015-03-04 16:38:45 -08001257
1258 bserver = bless(pprovider, pserver, "server", tpCav)
1259 bclient = bless(pprovider, pclient, "client")
1260 )
Ankuredd74ee2015-03-04 16:38:45 -08001261 // Make the client and server principals trust root certificates from
1262 // pprovider.
1263 pclient.AddToRoots(pprovider.BlessingStore().Default())
1264 pserver.AddToRoots(pprovider.BlessingStore().Default())
1265
1266 // Make the server present bserver to all clients.
1267 pserver.BlessingStore().SetDefault(bserver)
1268
Asim Shankar7171a252015-03-07 14:41:40 -08001269 // Start the server and the discharger.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001270 _, server := startServer(t, ctx, pserver, mgr, ns, "mountpoint/server", testServerDisp{&testServer{}})
1271 defer stopServer(t, ctx, server, ns, "mountpoint/server")
Asim Shankar7171a252015-03-07 14:41:40 -08001272
Asim Shankar149b4972015-04-23 13:29:58 -07001273 _, dischargeServer := startServer(t, ctx, pdischarger, mgr, ns, "mountpoint/dischargeserver", testutil.LeafDispatcher(&dischargeServer{}, security.AllowEveryone()))
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001274 defer stopServer(t, ctx, dischargeServer, ns, "mountpoint/dischargeserver")
Asim Shankar7171a252015-03-07 14:41:40 -08001275
Ankuredd74ee2015-03-04 16:38:45 -08001276 // Make the client present bclient to all servers that are blessed
1277 // by pprovider.
1278 pclient.BlessingStore().Set(bclient, "root")
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001279 client, err := InternalNewClient(mgr, ns)
Ankuredd74ee2015-03-04 16:38:45 -08001280 if err != nil {
1281 t.Fatalf("InternalNewClient failed: %v", err)
1282 }
1283 defer client.Close()
1284
Todd Wangad492042015-04-17 15:58:40 -07001285 ctx, _ = v23.WithPrincipal(ctx, pclient)
Ankuredd74ee2015-03-04 16:38:45 -08001286 var gotServer, gotClient string
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001287 if err := client.Call(ctx, "mountpoint/server/suffix", "EchoBlessings", nil, []interface{}{&gotServer, &gotClient}); err != nil {
Ankuredd74ee2015-03-04 16:38:45 -08001288 t.Fatalf("Finish failed: %v", err)
1289 }
1290 if wantServer, wantClient := "[root/server]", "[root/client]"; gotServer != wantServer || gotClient != wantClient {
1291 t.Fatalf("EchoBlessings: got %v, %v want %v, %v", gotServer, gotClient, wantServer, wantClient)
1292 }
1293}
1294
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001295func TestDischargePurgeFromCache(t *testing.T) {
Asim Shankar263c73b2015-03-19 18:31:26 -07001296 ctx, shutdown := initForTest()
1297 defer shutdown()
1298
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001299 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001300 pserver = testutil.NewPrincipal("server")
Asim Shankar8f05c222014-10-06 22:08:19 -07001301 pdischarger = pserver // In general, the discharger can be a separate principal. In this test, it happens to be the server.
Asim Shankar4a698282015-03-21 21:59:18 -07001302 pclient = testutil.NewPrincipal("client")
Asim Shankar8f05c222014-10-06 22:08:19 -07001303 // Client is blessed with a third-party caveat. The discharger service issues discharges with a fakeTimeCaveat.
1304 // This blessing is presented to "server".
1305 bclient = bless(pserver, pclient, "client", mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/server/discharger", security.UnconstrainedUse()))
Asim Shankar263c73b2015-03-19 18:31:26 -07001306
1307 b = createBundle(t, ctx, pserver, &testServer{})
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001308 )
Asim Shankar263c73b2015-03-19 18:31:26 -07001309 defer b.cleanup(t, ctx)
Asim Shankar8f05c222014-10-06 22:08:19 -07001310 // Setup the client to recognize the server's blessing and present bclient to it.
1311 pclient.AddToRoots(pserver.BlessingStore().Default())
1312 pclient.BlessingStore().Set(bclient, "server")
1313
Suharsh Sivakumar1b6683e2014-12-30 13:00:38 -08001314 var err error
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001315 if b.client, err = InternalNewClient(b.sm, b.ns); err != nil {
Ankure49a86a2014-11-11 18:52:43 -08001316 t.Fatalf("InternalNewClient failed: %v", err)
1317 }
Todd Wangad492042015-04-17 15:58:40 -07001318 ctx, _ = v23.WithPrincipal(ctx, pclient)
Mike Burrowsdc6b3602015-02-05 15:52:12 -08001319 call := func() error {
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001320 var got string
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001321 if err := b.client.Call(ctx, "mountpoint/server/aclAuth", "Echo", []interface{}{"batman"}, []interface{}{&got}); err != nil {
Asim Shankar263c73b2015-03-19 18:31:26 -07001322 return err
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001323 }
Asim Shankar8f05c222014-10-06 22:08:19 -07001324 if want := `method:"Echo",suffix:"aclAuth",arg:"batman"`; got != want {
Jiri Simsa074bf362015-02-17 09:29:45 -08001325 return verror.Convert(verror.ErrBadArg, nil, fmt.Errorf("Got [%v] want [%v]", got, want))
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001326 }
1327 return nil
1328 }
1329
1330 // First call should succeed
1331 if err := call(); err != nil {
1332 t.Fatal(err)
1333 }
1334 // Advance virtual clock, which will invalidate the discharge
1335 clock.Advance(1)
Jiri Simsa074bf362015-02-17 09:29:45 -08001336 if err, want := call(), "not authorized"; !matchesErrorPattern(err, verror.ErrNoAccess, want) {
Asim Shankar8f05c222014-10-06 22:08:19 -07001337 t.Errorf("Got error [%v] wanted to match pattern %q", err, want)
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001338 }
1339 // But retrying will succeed since the discharge should be purged from cache and refreshed
1340 if err := call(); err != nil {
1341 t.Fatal(err)
1342 }
1343}
1344
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001345type cancelTestServer struct {
1346 started chan struct{}
1347 cancelled chan struct{}
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001348 t *testing.T
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001349}
1350
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001351func newCancelTestServer(t *testing.T) *cancelTestServer {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001352 return &cancelTestServer{
1353 started: make(chan struct{}),
1354 cancelled: make(chan struct{}),
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001355 t: t,
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001356 }
1357}
1358
Todd Wang54feabe2015-04-15 23:38:26 -07001359func (s *cancelTestServer) CancelStreamReader(ctx *context.T, call rpc.StreamServerCall) error {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001360 close(s.started)
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001361 var b []byte
1362 if err := call.Recv(&b); err != io.EOF {
1363 s.t.Errorf("Got error %v, want io.EOF", err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001364 }
Todd Wang54feabe2015-04-15 23:38:26 -07001365 <-ctx.Done()
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001366 close(s.cancelled)
1367 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001368}
1369
1370// CancelStreamIgnorer doesn't read from it's input stream so all it's
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001371// buffers fill. The intention is to show that call.Done() is closed
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001372// even when the stream is stalled.
Todd Wang54feabe2015-04-15 23:38:26 -07001373func (s *cancelTestServer) CancelStreamIgnorer(ctx *context.T, _ rpc.StreamServerCall) error {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001374 close(s.started)
Todd Wang54feabe2015-04-15 23:38:26 -07001375 <-ctx.Done()
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001376 close(s.cancelled)
1377 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001378}
1379
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001380func waitForCancel(t *testing.T, ts *cancelTestServer, cancel context.CancelFunc) {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001381 <-ts.started
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001382 cancel()
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001383 <-ts.cancelled
1384}
1385
1386// TestCancel tests cancellation while the server is reading from a stream.
1387func TestCancel(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001388 ctx, shutdown := initForTest()
1389 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -07001390 var (
1391 ts = newCancelTestServer(t)
1392 pclient, pserver = newClientServerPrincipals()
1393 b = createBundle(t, ctx, pserver, ts)
1394 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001395 defer b.cleanup(t, ctx)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001396
Todd Wangad492042015-04-17 15:58:40 -07001397 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001398 ctx, cancel := context.WithCancel(ctx)
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001399 _, err := b.client.StartCall(ctx, "mountpoint/server/suffix", "CancelStreamReader", []interface{}{})
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001400 if err != nil {
1401 t.Fatalf("Start call failed: %v", err)
1402 }
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001403 waitForCancel(t, ts, cancel)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001404}
1405
1406// TestCancelWithFullBuffers tests that even if the writer has filled the buffers and
1407// the server is not reading that the cancel message gets through.
1408func TestCancelWithFullBuffers(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001409 ctx, shutdown := initForTest()
1410 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -07001411 var (
1412 ts = newCancelTestServer(t)
1413 pclient, pserver = newClientServerPrincipals()
1414 b = createBundle(t, ctx, pserver, ts)
1415 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001416 defer b.cleanup(t, ctx)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001417
Todd Wangad492042015-04-17 15:58:40 -07001418 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001419 ctx, cancel := context.WithCancel(ctx)
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001420 call, err := b.client.StartCall(ctx, "mountpoint/server/suffix", "CancelStreamIgnorer", []interface{}{})
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001421 if err != nil {
1422 t.Fatalf("Start call failed: %v", err)
1423 }
1424 // Fill up all the write buffers to ensure that cancelling works even when the stream
1425 // is blocked.
1426 call.Send(make([]byte, vc.MaxSharedBytes))
1427 call.Send(make([]byte, vc.DefaultBytesBufferedPerFlow))
1428
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001429 waitForCancel(t, ts, cancel)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001430}
1431
1432type streamRecvInGoroutineServer struct{ c chan error }
1433
Todd Wang54feabe2015-04-15 23:38:26 -07001434func (s *streamRecvInGoroutineServer) RecvInGoroutine(_ *context.T, call rpc.StreamServerCall) error {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001435 // Spawn a goroutine to read streaming data from the client.
1436 go func() {
1437 var i interface{}
1438 for {
1439 err := call.Recv(&i)
1440 if err != nil {
1441 s.c <- err
1442 return
1443 }
1444 }
1445 }()
1446 // Imagine the server did some processing here and now that it is done,
1447 // it does not care to see what else the client has to say.
1448 return nil
1449}
1450
1451func TestStreamReadTerminatedByServer(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001452 ctx, shutdown := initForTest()
1453 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -07001454 var (
1455 pclient, pserver = newClientServerPrincipals()
1456 s = &streamRecvInGoroutineServer{c: make(chan error, 1)}
1457 b = createBundle(t, ctx, pserver, s)
1458 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001459 defer b.cleanup(t, ctx)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001460
Todd Wangad492042015-04-17 15:58:40 -07001461 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001462 call, err := b.client.StartCall(ctx, "mountpoint/server/suffix", "RecvInGoroutine", []interface{}{})
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001463 if err != nil {
1464 t.Fatalf("StartCall failed: %v", err)
1465 }
1466
1467 c := make(chan error, 1)
1468 go func() {
1469 for i := 0; true; i++ {
1470 if err := call.Send(i); err != nil {
1471 c <- err
1472 return
1473 }
1474 }
1475 }()
1476
1477 // The goroutine at the server executing "Recv" should have terminated
1478 // with EOF.
1479 if err := <-s.c; err != io.EOF {
1480 t.Errorf("Got %v at server, want io.EOF", err)
1481 }
1482 // The client Send should have failed since the RPC has been
1483 // terminated.
1484 if err := <-c; err == nil {
1485 t.Errorf("Client Send should fail as the server should have closed the flow")
1486 }
1487}
1488
1489// TestConnectWithIncompatibleServers tests that clients ignore incompatible endpoints.
1490func TestConnectWithIncompatibleServers(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001491 ctx, shutdown := initForTest()
1492 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -07001493 var (
1494 pclient, pserver = newClientServerPrincipals()
1495 b = createBundle(t, ctx, pserver, &testServer{})
1496 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001497 defer b.cleanup(t, ctx)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001498
1499 // Publish some incompatible endpoints.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001500 publisher := publisher.New(ctx, b.ns, publishPeriod)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001501 defer publisher.WaitForStop()
1502 defer publisher.Stop()
Robin Thellend89e95232015-03-24 13:48:48 -07001503 publisher.AddName("incompatible", false, false)
1504 publisher.AddServer("/@2@tcp@localhost:10000@@1000000@2000000@@")
1505 publisher.AddServer("/@2@tcp@localhost:10001@@2000000@3000000@@")
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001506
Todd Wangad492042015-04-17 15:58:40 -07001507 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001508 _, err := b.client.StartCall(ctx, "incompatible/suffix", "Echo", []interface{}{"foo"}, options.NoRetry{})
Todd Wang8fa38762015-03-25 14:04:59 -07001509 if verror.ErrorID(err) != verror.ErrNoServers.ID {
Jiri Simsa074bf362015-02-17 09:29:45 -08001510 t.Errorf("Expected error %s, found: %v", verror.ErrNoServers, err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001511 }
1512
1513 // Now add a server with a compatible endpoint and try again.
Robin Thellend89e95232015-03-24 13:48:48 -07001514 publisher.AddServer("/" + b.ep.String())
1515 publisher.AddName("incompatible", false, false)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001516
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001517 call, err := b.client.StartCall(ctx, "incompatible/suffix", "Echo", []interface{}{"foo"})
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001518 if err != nil {
Asim Shankar3a8a7e22014-05-12 18:01:44 -07001519 t.Fatal(err)
1520 }
1521 var result string
1522 if err = call.Finish(&result); err != nil {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001523 t.Errorf("Unexpected error finishing call %v", err)
1524 }
Asim Shankar3a8a7e22014-05-12 18:01:44 -07001525 expected := `method:"Echo",suffix:"suffix",arg:"foo"`
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001526 if result != expected {
1527 t.Errorf("Wrong result returned. Got %s, wanted %s", result, expected)
1528 }
1529}
1530
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001531func TestPreferredAddress(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001532 ctx, shutdown := initForTest()
1533 defer shutdown()
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001534 sm := imanager.InternalNew(naming.FixedRoutingID(0x555555555))
1535 defer sm.Shutdown()
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001536 ns := tnaming.NewSimpleNamespace()
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -07001537 pa := func(string, []net.Addr) ([]net.Addr, error) {
1538 return []net.Addr{netstate.NewNetAddr("tcp", "1.1.1.1")}, nil
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001539 }
Asim Shankar4a698282015-03-21 21:59:18 -07001540 server, err := testInternalNewServer(ctx, sm, ns, testutil.NewPrincipal("server"))
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001541 if err != nil {
1542 t.Errorf("InternalNewServer failed: %v", err)
1543 }
1544 defer server.Stop()
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -08001545
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001546 spec := rpc.ListenSpec{
1547 Addrs: rpc.ListenAddrs{{"tcp", ":0"}},
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -08001548 AddressChooser: pa,
1549 }
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -08001550 eps, err := server.Listen(spec)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -08001551 if err != nil {
1552 t.Errorf("unexpected error: %s", err)
1553 }
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -08001554 iep := eps[0].(*inaming.Endpoint)
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001555 host, _, err := net.SplitHostPort(iep.Address)
1556 if err != nil {
1557 t.Errorf("unexpected error: %s", err)
1558 }
1559 if got, want := host, "1.1.1.1"; got != want {
1560 t.Errorf("got %q, want %q", got, want)
1561 }
1562 // Won't override the specified address.
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -08001563 eps, err = server.Listen(listenSpec)
1564 iep = eps[0].(*inaming.Endpoint)
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001565 host, _, err = net.SplitHostPort(iep.Address)
1566 if err != nil {
1567 t.Errorf("unexpected error: %s", err)
1568 }
1569 if got, want := host, "127.0.0.1"; got != want {
1570 t.Errorf("got %q, want %q", got, want)
1571 }
1572}
1573
1574func TestPreferredAddressErrors(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001575 ctx, shutdown := initForTest()
1576 defer shutdown()
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001577 sm := imanager.InternalNew(naming.FixedRoutingID(0x555555555))
1578 defer sm.Shutdown()
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001579 ns := tnaming.NewSimpleNamespace()
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -07001580 paerr := func(_ string, a []net.Addr) ([]net.Addr, error) {
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001581 return nil, fmt.Errorf("oops")
1582 }
Asim Shankar4a698282015-03-21 21:59:18 -07001583 server, err := testInternalNewServer(ctx, sm, ns, testutil.NewPrincipal("server"))
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001584 if err != nil {
1585 t.Errorf("InternalNewServer failed: %v", err)
1586 }
1587 defer server.Stop()
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001588 spec := rpc.ListenSpec{
1589 Addrs: rpc.ListenAddrs{{"tcp", ":0"}},
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -08001590 AddressChooser: paerr,
1591 }
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -08001592 eps, err := server.Listen(spec)
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -07001593
1594 if got, want := len(eps), 0; got != want {
1595 t.Errorf("got %q, want %q", got, want)
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001596 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -07001597 status := server.Status()
1598 if got, want := len(status.Errors), 1; got != want {
1599 t.Errorf("got %q, want %q", got, want)
Cosmos Nicolaoud6c3c9c2014-09-30 15:42:53 -07001600 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -07001601 if got, want := status.Errors[0].Error(), "oops"; got != want {
1602 t.Errorf("got %q, want %q", got, want)
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001603 }
1604}
1605
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001606func TestSecurityNone(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001607 ctx, shutdown := initForTest()
1608 defer shutdown()
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001609 sm := imanager.InternalNew(naming.FixedRoutingID(0x66666666))
1610 defer sm.Shutdown()
1611 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -07001612 server, err := testInternalNewServer(ctx, sm, ns, nil, options.SecurityNone)
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001613 if err != nil {
1614 t.Fatalf("InternalNewServer failed: %v", err)
1615 }
1616 if _, err = server.Listen(listenSpec); err != nil {
1617 t.Fatalf("server.Listen failed: %v", err)
1618 }
1619 disp := &testServerDisp{&testServer{}}
Cosmos Nicolaou92dba582014-11-05 17:24:10 -08001620 if err := server.ServeDispatcher("mp/server", disp); err != nil {
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001621 t.Fatalf("server.Serve failed: %v", err)
1622 }
Suharsh Sivakumarae774a52015-01-09 14:26:32 -08001623 client, err := InternalNewClient(sm, ns)
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001624 if err != nil {
1625 t.Fatalf("InternalNewClient failed: %v", err)
1626 }
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -07001627 // When using SecurityNone, all authorization checks should be skipped, so
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001628 // unauthorized methods should be callable.
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001629 var got string
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001630 if err := client.Call(ctx, "mp/server", "Unauthorized", nil, []interface{}{&got}, options.SecurityNone); err != nil {
1631 t.Fatalf("client.Call failed: %v", err)
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001632 }
1633 if want := "UnauthorizedResult"; got != want {
1634 t.Errorf("got (%v), want (%v)", got, want)
1635 }
1636}
1637
Suharsh Sivakumar0ed10c22015-04-06 12:55:55 -07001638func TestNoPrincipal(t *testing.T) {
1639 ctx, shutdown := initForTest()
1640 defer shutdown()
1641 sm := imanager.InternalNew(naming.FixedRoutingID(0x66666666))
1642 defer sm.Shutdown()
1643 ns := tnaming.NewSimpleNamespace()
1644 server, err := testInternalNewServer(ctx, sm, ns, testutil.NewPrincipal("server"))
1645 if err != nil {
1646 t.Fatalf("InternalNewServer failed: %v", err)
1647 }
1648 if _, err = server.Listen(listenSpec); err != nil {
1649 t.Fatalf("server.Listen failed: %v", err)
1650 }
1651 disp := &testServerDisp{&testServer{}}
1652 if err := server.ServeDispatcher("mp/server", disp); err != nil {
1653 t.Fatalf("server.Serve failed: %v", err)
1654 }
1655 client, err := InternalNewClient(sm, ns)
1656 if err != nil {
1657 t.Fatalf("InternalNewClient failed: %v", err)
1658 }
1659
1660 // A call should fail if the principal in the ctx is nil and SecurityNone is not specified.
Todd Wangad492042015-04-17 15:58:40 -07001661 ctx, err = v23.WithPrincipal(ctx, nil)
Suharsh Sivakumar0ed10c22015-04-06 12:55:55 -07001662 if err != nil {
1663 t.Fatalf("failed to set principal: %v", err)
1664 }
1665 _, err = client.StartCall(ctx, "mp/server", "Echo", []interface{}{"foo"})
1666 if err == nil || verror.ErrorID(err) != errNoPrincipal.ID {
1667 t.Fatalf("Expected errNoPrincipal, got %v", err)
1668 }
1669}
1670
Matt Rosencrantz321a51d2014-10-30 10:37:56 -07001671func TestCallWithNilContext(t *testing.T) {
1672 sm := imanager.InternalNew(naming.FixedRoutingID(0x66666666))
1673 defer sm.Shutdown()
1674 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumarae774a52015-01-09 14:26:32 -08001675 client, err := InternalNewClient(sm, ns)
Matt Rosencrantz321a51d2014-10-30 10:37:56 -07001676 if err != nil {
1677 t.Fatalf("InternalNewClient failed: %v", err)
1678 }
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -07001679 call, err := client.StartCall(nil, "foo", "bar", []interface{}{}, options.SecurityNone)
Matt Rosencrantz321a51d2014-10-30 10:37:56 -07001680 if call != nil {
1681 t.Errorf("Expected nil interface got: %#v", call)
1682 }
Todd Wang8fa38762015-03-25 14:04:59 -07001683 if verror.ErrorID(err) != verror.ErrBadArg.ID {
Suharsh Sivakumar0ed10c22015-04-06 12:55:55 -07001684 t.Errorf("Expected a BadArg error, got: %s", err.Error())
Matt Rosencrantz321a51d2014-10-30 10:37:56 -07001685 }
1686}
1687
Asim Shankara5b60b22014-11-06 15:37:07 -08001688func TestServerBlessingsOpt(t *testing.T) {
1689 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001690 pserver = testutil.NewPrincipal("server")
1691 pclient = testutil.NewPrincipal("client")
Asim Shankara5b60b22014-11-06 15:37:07 -08001692 batman, _ = pserver.BlessSelf("batman")
1693 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001694 ctx, shutdown := initForTest()
1695 defer shutdown()
Asim Shankar7171a252015-03-07 14:41:40 -08001696 // Client and server recognize the servers blessings
1697 for _, p := range []security.Principal{pserver, pclient} {
1698 if err := p.AddToRoots(pserver.BlessingStore().Default()); err != nil {
1699 t.Fatal(err)
1700 }
1701 if err := p.AddToRoots(batman); err != nil {
1702 t.Fatal(err)
1703 }
Asim Shankara5b60b22014-11-06 15:37:07 -08001704 }
1705 // Start a server that uses the ServerBlessings option to configure itself
1706 // to act as batman (as opposed to using the default blessing).
1707 ns := tnaming.NewSimpleNamespace()
Asim Shankara5b60b22014-11-06 15:37:07 -08001708
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001709 defer runServer(t, ctx, ns, pserver, "mountpoint/batman", &testServer{}, options.ServerBlessings{batman}).Shutdown()
1710 defer runServer(t, ctx, ns, pserver, "mountpoint/default", &testServer{}).Shutdown()
Asim Shankara5b60b22014-11-06 15:37:07 -08001711
Asim Shankarb547ea92015-02-17 18:49:45 -08001712 // And finally, make an RPC and see that the client sees "batman"
Asim Shankara5b60b22014-11-06 15:37:07 -08001713 runClient := func(server string) ([]string, error) {
1714 smc := imanager.InternalNew(naming.FixedRoutingID(0xc))
1715 defer smc.Shutdown()
1716 client, err := InternalNewClient(
1717 smc,
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001718 ns)
Asim Shankara5b60b22014-11-06 15:37:07 -08001719 if err != nil {
1720 return nil, err
1721 }
1722 defer client.Close()
Todd Wangad492042015-04-17 15:58:40 -07001723 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001724 call, err := client.StartCall(ctx, server, "Closure", nil)
Asim Shankara5b60b22014-11-06 15:37:07 -08001725 if err != nil {
1726 return nil, err
1727 }
1728 blessings, _ := call.RemoteBlessings()
1729 return blessings, nil
1730 }
1731
1732 // When talking to mountpoint/batman, should see "batman"
1733 // When talking to mountpoint/default, should see "server"
1734 if got, err := runClient("mountpoint/batman"); err != nil || len(got) != 1 || got[0] != "batman" {
1735 t.Errorf("Got (%v, %v) wanted 'batman'", got, err)
1736 }
1737 if got, err := runClient("mountpoint/default"); err != nil || len(got) != 1 || got[0] != "server" {
1738 t.Errorf("Got (%v, %v) wanted 'server'", got, err)
1739 }
1740}
1741
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001742func TestNoDischargesOpt(t *testing.T) {
1743 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001744 pdischarger = testutil.NewPrincipal("discharger")
1745 pserver = testutil.NewPrincipal("server")
1746 pclient = testutil.NewPrincipal("client")
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001747 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001748 ctx, shutdown := initForTest()
1749 defer shutdown()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001750 // Make the client recognize all server blessings
1751 if err := pclient.AddToRoots(pserver.BlessingStore().Default()); err != nil {
1752 t.Fatal(err)
1753 }
1754 if err := pclient.AddToRoots(pdischarger.BlessingStore().Default()); err != nil {
1755 t.Fatal(err)
1756 }
1757
1758 // Bless the client with a ThirdPartyCaveat.
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001759 tpcav := mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/discharger", mkCaveat(security.NewExpiryCaveat(time.Now().Add(time.Hour))))
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001760 blessings, err := pserver.Bless(pclient.PublicKey(), pserver.BlessingStore().Default(), "tpcav", tpcav)
1761 if err != nil {
1762 t.Fatalf("failed to create Blessings: %v", err)
1763 }
1764 if _, err = pclient.BlessingStore().Set(blessings, "server"); err != nil {
1765 t.Fatalf("failed to set blessings: %v", err)
1766 }
1767
1768 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001769
1770 // Setup the disharger and test server.
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001771 discharger := &dischargeServer{}
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001772 defer runServer(t, ctx, ns, pdischarger, "mountpoint/discharger", discharger).Shutdown()
1773 defer runServer(t, ctx, ns, pserver, "mountpoint/testServer", &testServer{}).Shutdown()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001774
1775 runClient := func(noDischarges bool) {
1776 rid, err := naming.NewRoutingID()
1777 if err != nil {
1778 t.Fatal(err)
1779 }
1780 smc := imanager.InternalNew(rid)
1781 defer smc.Shutdown()
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001782 client, err := InternalNewClient(smc, ns)
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001783 if err != nil {
1784 t.Fatalf("failed to create client: %v", err)
1785 }
1786 defer client.Close()
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001787 var opts []rpc.CallOpt
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001788 if noDischarges {
Ankur50a5f392015-02-27 18:46:30 -08001789 opts = append(opts, NoDischarges{})
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001790 }
Todd Wangad492042015-04-17 15:58:40 -07001791 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001792 if _, err = client.StartCall(ctx, "mountpoint/testServer", "Closure", nil, opts...); err != nil {
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001793 t.Fatalf("failed to StartCall: %v", err)
1794 }
1795 }
1796
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001797 // Test that when the NoDischarges option is set, dischargeServer does not get called.
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001798 if runClient(true); discharger.called {
1799 t.Errorf("did not expect discharger to be called")
1800 }
1801 discharger.called = false
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001802 // Test that when the Nodischarges option is not set, dischargeServer does get called.
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001803 if runClient(false); !discharger.called {
1804 t.Errorf("expected discharger to be called")
1805 }
1806}
1807
1808func TestNoImplicitDischargeFetching(t *testing.T) {
1809 // This test ensures that discharge clients only fetch discharges for the specified tp caveats and not its own.
1810 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001811 pdischarger1 = testutil.NewPrincipal("discharger1")
1812 pdischarger2 = testutil.NewPrincipal("discharger2")
1813 pdischargeClient = testutil.NewPrincipal("dischargeClient")
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001814 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001815 ctx, shutdown := initForTest()
1816 defer shutdown()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001817 // Bless the client with a ThirdPartyCaveat from discharger1.
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001818 tpcav1 := mkThirdPartyCaveat(pdischarger1.PublicKey(), "mountpoint/discharger1", mkCaveat(security.NewExpiryCaveat(time.Now().Add(time.Hour))))
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001819 blessings, err := pdischarger1.Bless(pdischargeClient.PublicKey(), pdischarger1.BlessingStore().Default(), "tpcav1", tpcav1)
1820 if err != nil {
1821 t.Fatalf("failed to create Blessings: %v", err)
1822 }
1823 if err = pdischargeClient.BlessingStore().SetDefault(blessings); err != nil {
1824 t.Fatalf("failed to set blessings: %v", err)
1825 }
Asim Shankar263c73b2015-03-19 18:31:26 -07001826 // The client will only talk to the discharge services if it recognizes them.
1827 pdischargeClient.AddToRoots(pdischarger1.BlessingStore().Default())
1828 pdischargeClient.AddToRoots(pdischarger2.BlessingStore().Default())
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001829
1830 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001831
1832 // Setup the disharger and test server.
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001833 discharger1 := &dischargeServer{}
1834 discharger2 := &dischargeServer{}
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001835 defer runServer(t, ctx, ns, pdischarger1, "mountpoint/discharger1", discharger1).Shutdown()
1836 defer runServer(t, ctx, ns, pdischarger2, "mountpoint/discharger2", discharger2).Shutdown()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001837
1838 rid, err := naming.NewRoutingID()
1839 if err != nil {
1840 t.Fatal(err)
1841 }
1842 sm := imanager.InternalNew(rid)
Suharsh Sivakumar1b6683e2014-12-30 13:00:38 -08001843
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001844 c, err := InternalNewClient(sm, ns)
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001845 if err != nil {
Suharsh Sivakumar1b6683e2014-12-30 13:00:38 -08001846 t.Fatalf("failed to create client: %v", err)
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001847 }
Suharsh Sivakumar1b6683e2014-12-30 13:00:38 -08001848 dc := c.(*client).dc
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001849 tpcav2, err := security.NewPublicKeyCaveat(pdischarger2.PublicKey(), "mountpoint/discharger2", security.ThirdPartyRequirements{}, mkCaveat(security.NewExpiryCaveat(time.Now().Add(time.Hour))))
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001850 if err != nil {
1851 t.Error(err)
1852 }
Todd Wangad492042015-04-17 15:58:40 -07001853 ctx, _ = v23.WithPrincipal(ctx, pdischargeClient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001854 dc.PrepareDischarges(ctx, []security.Caveat{tpcav2}, security.DischargeImpetus{})
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001855
1856 // Ensure that discharger1 was not called and discharger2 was called.
1857 if discharger1.called {
1858 t.Errorf("discharge for caveat on discharge client should not have been fetched.")
1859 }
1860 if !discharger2.called {
1861 t.Errorf("discharge for caveat passed to PrepareDischarges should have been fetched.")
1862 }
1863}
1864
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001865// TestBlessingsCache tests that the VCCache is used to sucessfully used to cache duplicate
1866// calls blessings.
1867func TestBlessingsCache(t *testing.T) {
1868 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001869 pserver = testutil.NewPrincipal("server")
1870 pclient = testutil.NewPrincipal("client")
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001871 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001872 ctx, shutdown := initForTest()
1873 defer shutdown()
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001874 // Make the client recognize all server blessings
1875 if err := pclient.AddToRoots(pserver.BlessingStore().Default()); err != nil {
1876 t.Fatal(err)
1877 }
1878
1879 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001880
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001881 serverSM := runServer(t, ctx, ns, pserver, "mountpoint/testServer", &testServer{})
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001882 defer serverSM.Shutdown()
Suharsh Sivakumar0902b7f2015-02-27 19:06:41 -08001883 rid := serverSM.RoutingID()
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001884
Todd Wangad492042015-04-17 15:58:40 -07001885 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001886
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001887 newClient := func() rpc.Client {
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001888 rid, err := naming.NewRoutingID()
1889 if err != nil {
1890 t.Fatal(err)
1891 }
1892 smc := imanager.InternalNew(rid)
1893 defer smc.Shutdown()
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001894 client, err := InternalNewClient(smc, ns)
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001895 if err != nil {
1896 t.Fatalf("failed to create client: %v", err)
1897 }
1898 return client
1899 }
1900
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001901 runClient := func(client rpc.Client) {
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001902 if err := client.Call(ctx, "mountpoint/testServer", "Closure", nil, nil); err != nil {
1903 t.Fatalf("failed to Call: %v", err)
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001904 }
1905 }
1906
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001907 cachePrefix := naming.Join("rpc", "server", "routing-id", rid.String(), "security", "blessings", "cache")
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001908 cacheHits, err := stats.GetStatsObject(naming.Join(cachePrefix, "hits"))
1909 if err != nil {
1910 t.Fatal(err)
1911 }
1912 cacheAttempts, err := stats.GetStatsObject(naming.Join(cachePrefix, "attempts"))
1913 if err != nil {
1914 t.Fatal(err)
1915 }
1916
1917 // Check that the blessings cache is not used on the first call.
1918 clientA := newClient()
1919 runClient(clientA)
1920 if gotAttempts, gotHits := cacheAttempts.Value().(int64), cacheHits.Value().(int64); gotAttempts != 1 || gotHits != 0 {
1921 t.Errorf("got cacheAttempts(%v), cacheHits(%v), expected cacheAttempts(1), cacheHits(0)", gotAttempts, gotHits)
1922 }
1923 // Check that the cache is hit on the second call with the same blessings.
1924 runClient(clientA)
1925 if gotAttempts, gotHits := cacheAttempts.Value().(int64), cacheHits.Value().(int64); gotAttempts != 2 || gotHits != 1 {
1926 t.Errorf("got cacheAttempts(%v), cacheHits(%v), expected cacheAttempts(2), cacheHits(1)", gotAttempts, gotHits)
1927 }
1928 clientA.Close()
1929 // Check that the cache is not used with a different client.
1930 clientB := newClient()
1931 runClient(clientB)
1932 if gotAttempts, gotHits := cacheAttempts.Value().(int64), cacheHits.Value().(int64); gotAttempts != 3 || gotHits != 1 {
1933 t.Errorf("got cacheAttempts(%v), cacheHits(%v), expected cacheAttempts(3), cacheHits(1)", gotAttempts, gotHits)
1934 }
1935 // clientB changes its blessings, the cache should not be used.
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001936 blessings, err := pserver.Bless(pclient.PublicKey(), pserver.BlessingStore().Default(), "cav", mkCaveat(security.NewExpiryCaveat(time.Now().Add(time.Hour))))
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001937 if err != nil {
1938 t.Fatalf("failed to create Blessings: %v", err)
1939 }
1940 if _, err = pclient.BlessingStore().Set(blessings, "server"); err != nil {
1941 t.Fatalf("failed to set blessings: %v", err)
1942 }
1943 runClient(clientB)
1944 if gotAttempts, gotHits := cacheAttempts.Value().(int64), cacheHits.Value().(int64); gotAttempts != 4 || gotHits != 1 {
1945 t.Errorf("got cacheAttempts(%v), cacheHits(%v), expected cacheAttempts(4), cacheHits(1)", gotAttempts, gotHits)
1946 }
1947 clientB.Close()
1948}
1949
Asim Shankar7283dd82015-02-03 19:35:58 -08001950var fakeTimeCaveat = security.CaveatDescriptor{
1951 Id: uniqueid.Id{0x18, 0xba, 0x6f, 0x84, 0xd5, 0xec, 0xdb, 0x9b, 0xf2, 0x32, 0x19, 0x5b, 0x53, 0x92, 0x80, 0x0},
1952 ParamType: vdl.TypeOf(int64(0)),
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001953}
Suharsh Sivakumar9d17e4a2015-02-02 22:42:16 -08001954
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001955func TestServerPublicKeyOpt(t *testing.T) {
1956 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001957 pserver = testutil.NewPrincipal("server")
1958 pother = testutil.NewPrincipal("other")
1959 pclient = testutil.NewPrincipal("client")
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001960 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001961 ctx, shutdown := initForTest()
1962 defer shutdown()
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001963 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001964 mountName := "mountpoint/default"
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001965
1966 // Start a server with pserver.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001967 defer runServer(t, ctx, ns, pserver, mountName, &testServer{}).Shutdown()
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001968
1969 smc := imanager.InternalNew(naming.FixedRoutingID(0xc))
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001970 client, err := InternalNewClient(smc, ns)
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001971 if err != nil {
1972 t.Fatal(err)
1973 }
1974 defer smc.Shutdown()
1975 defer client.Close()
1976
Todd Wangad492042015-04-17 15:58:40 -07001977 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001978 // The call should succeed when the server presents the same public as the opt...
Asim Shankar263c73b2015-03-19 18:31:26 -07001979 if _, err = client.StartCall(ctx, mountName, "Closure", nil, options.SkipServerEndpointAuthorization{}, options.ServerPublicKey{pserver.PublicKey()}); err != nil {
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001980 t.Errorf("Expected call to succeed but got %v", err)
1981 }
1982 // ...but fail if they differ.
Todd Wang8fa38762015-03-25 14:04:59 -07001983 if _, err = client.StartCall(ctx, mountName, "Closure", nil, options.SkipServerEndpointAuthorization{}, options.ServerPublicKey{pother.PublicKey()}); verror.ErrorID(err) != verror.ErrNotTrusted.ID {
Jiri Simsa074bf362015-02-17 09:29:45 -08001984 t.Errorf("got %v, want %v", verror.ErrorID(err), verror.ErrNotTrusted.ID)
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001985 }
1986}
1987
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001988type expiryDischarger struct {
1989 called bool
1990}
1991
Todd Wang4264e4b2015-04-16 22:43:40 -07001992func (ed *expiryDischarger) Discharge(ctx *context.T, call rpc.StreamServerCall, cav security.Caveat, _ security.DischargeImpetus) (security.Discharge, error) {
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001993 tp := cav.ThirdPartyDetails()
1994 if tp == nil {
Asim Shankar08642822015-03-02 21:21:09 -08001995 return security.Discharge{}, fmt.Errorf("discharger: %v does not represent a third-party caveat", cav)
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001996 }
Todd Wang4264e4b2015-04-16 22:43:40 -07001997 if err := tp.Dischargeable(ctx, call.Security()); err != nil {
Asim Shankar08642822015-03-02 21:21:09 -08001998 return security.Discharge{}, fmt.Errorf("third-party caveat %v cannot be discharged for this context: %v", cav, err)
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001999 }
2000 expDur := 10 * time.Millisecond
2001 if ed.called {
2002 expDur = time.Second
2003 }
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07002004 expiry, err := security.NewExpiryCaveat(time.Now().Add(expDur))
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002005 if err != nil {
Asim Shankar08642822015-03-02 21:21:09 -08002006 return security.Discharge{}, fmt.Errorf("failed to create an expiration on the discharge: %v", err)
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002007 }
Todd Wang4264e4b2015-04-16 22:43:40 -07002008 d, err := call.Security().LocalPrincipal().MintDischarge(cav, expiry)
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002009 if err != nil {
Asim Shankar08642822015-03-02 21:21:09 -08002010 return security.Discharge{}, err
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002011 }
2012 ed.called = true
Asim Shankar08642822015-03-02 21:21:09 -08002013 return d, nil
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002014}
2015
2016func TestDischargeClientFetchExpiredDischarges(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07002017 ctx, shutdown := initForTest()
2018 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -07002019 var (
2020 pclient, pdischarger = newClientServerPrincipals()
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07002021 tpcav = mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/discharger", mkCaveat(security.NewExpiryCaveat(time.Now().Add(time.Hour))))
Asim Shankar263c73b2015-03-19 18:31:26 -07002022 ns = tnaming.NewSimpleNamespace()
2023 discharger = &expiryDischarger{}
2024 )
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002025
2026 // Setup the disharge server.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07002027 defer runServer(t, ctx, ns, pdischarger, "mountpoint/discharger", discharger).Shutdown()
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002028
2029 // Create a discharge client.
2030 rid, err := naming.NewRoutingID()
2031 if err != nil {
2032 t.Fatal(err)
2033 }
2034 smc := imanager.InternalNew(rid)
2035 defer smc.Shutdown()
2036 client, err := InternalNewClient(smc, ns)
2037 if err != nil {
2038 t.Fatalf("failed to create client: %v", err)
2039 }
2040 defer client.Close()
Todd Wangad492042015-04-17 15:58:40 -07002041 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar08918582015-03-03 15:16:36 -08002042 dc := InternalNewDischargeClient(ctx, client, 0)
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002043
2044 // Fetch discharges for tpcav.
Asim Shankar263c73b2015-03-19 18:31:26 -07002045 dis := dc.PrepareDischarges(ctx, []security.Caveat{tpcav}, security.DischargeImpetus{})[0]
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002046 // Check that the discharges is not yet expired, but is expired after 100 milliseconds.
2047 expiry := dis.Expiry()
2048 // The discharge should expire.
2049 select {
2050 case <-time.After(time.Now().Sub(expiry)):
2051 break
2052 case <-time.After(time.Second):
2053 t.Fatalf("discharge didn't expire within a second")
2054 }
2055 // Preparing Discharges again to get fresh discharges.
2056 now := time.Now()
Asim Shankar263c73b2015-03-19 18:31:26 -07002057 dis = dc.PrepareDischarges(ctx, []security.Caveat{tpcav}, security.DischargeImpetus{})[0]
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002058 if expiry = dis.Expiry(); expiry.Before(now) {
2059 t.Fatalf("discharge has expired %v, but should be fresh", dis)
2060 }
2061}
2062
Asim Shankar263c73b2015-03-19 18:31:26 -07002063// newClientServerPrincipals creates a pair of principals and sets them up to
2064// recognize each others default blessings.
2065//
2066// If the client does not recognize the blessings presented by the server,
2067// then it will not even send it the request.
2068//
2069// If the server does not recognize the blessings presented by the client,
2070// it is likely to deny access (unless the server authorizes all principals).
2071func newClientServerPrincipals() (client, server security.Principal) {
Asim Shankar4a698282015-03-21 21:59:18 -07002072 client = testutil.NewPrincipal("client")
2073 server = testutil.NewPrincipal("server")
Asim Shankar263c73b2015-03-19 18:31:26 -07002074 client.AddToRoots(server.BlessingStore().Default())
2075 server.AddToRoots(client.BlessingStore().Default())
2076 return
2077}
2078
Suharsh Sivakumard19c95d2015-02-19 14:44:50 -08002079func init() {
Suharsh Sivakumar7e93ce52015-05-07 17:46:13 -07002080 rpc.RegisterUnknownProtocol("wsh", websocket.HybridDial, websocket.HybridResolve, websocket.HybridListener)
Todd Wang4264e4b2015-04-16 22:43:40 -07002081 security.RegisterCaveatValidator(fakeTimeCaveat, func(_ *context.T, _ security.Call, t int64) error {
Suharsh Sivakumar8a0adbb2015-03-06 13:16:34 -08002082 if now := clock.Now(); now > t {
Asim Shankar7283dd82015-02-03 19:35:58 -08002083 return fmt.Errorf("fakeTimeCaveat expired: now=%d > then=%d", now, t)
2084 }
2085 return nil
2086 })
Suharsh Sivakumar9d17e4a2015-02-02 22:42:16 -08002087}