blob: 82247763923023616d1acc1adb98e658246534fa [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"
Suharsh Sivakumardcc11d72015-05-11 12:19:20 -070041 "v.io/x/ref/runtime/internal/lib/publisher"
42 "v.io/x/ref/runtime/internal/lib/websocket"
43 inaming "v.io/x/ref/runtime/internal/naming"
44 _ "v.io/x/ref/runtime/internal/rpc/protocols/tcp"
45 _ "v.io/x/ref/runtime/internal/rpc/protocols/ws"
46 _ "v.io/x/ref/runtime/internal/rpc/protocols/wsh"
47 "v.io/x/ref/runtime/internal/rpc/stream"
48 imanager "v.io/x/ref/runtime/internal/rpc/stream/manager"
49 "v.io/x/ref/runtime/internal/rpc/stream/vc"
50 tnaming "v.io/x/ref/runtime/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 {
Cosmos Nicolaou33cf8982015-05-26 10:39:49 -0700285 for {
286 me, err := ns.Resolve(ctx, name)
287 if err == nil {
288 return me.Names()
289 }
290 time.Sleep(10 * time.Millisecond)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700291 }
292}
293
Todd Wang5082a552015-04-02 10:56:11 -0700294func verifyMountMissing(t *testing.T, ctx *context.T, ns namespace.T, name string) {
Cosmos Nicolaou33cf8982015-05-26 10:39:49 -0700295 for {
296 if _, err := ns.Resolve(ctx, name); err != nil {
297 // Assume that any error (since we're using a mock namespace) means
298 // that the name is no longer present.
299 return
300 }
301 time.Sleep(10 * time.Millisecond)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700302 }
303}
304
Todd Wang5082a552015-04-02 10:56:11 -0700305func stopServer(t *testing.T, ctx *context.T, server rpc.Server, ns namespace.T, name string) {
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700306 vlog.VI(1).Info("server.Stop")
Ankure49a86a2014-11-11 18:52:43 -0800307 new_name := "should_appear_in_mt/server"
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700308 verifyMount(t, ctx, ns, name)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700309
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700310 // publish a second name
Ankure49a86a2014-11-11 18:52:43 -0800311 if err := server.AddName(new_name); err != nil {
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700312 t.Errorf("server.Serve failed: %v", err)
313 }
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700314 verifyMount(t, ctx, ns, new_name)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700315
316 if err := server.Stop(); err != nil {
317 t.Errorf("server.Stop failed: %v", err)
318 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700319
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700320 verifyMountMissing(t, ctx, ns, name)
321 verifyMountMissing(t, ctx, ns, new_name)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700322
323 // Check that we can no longer serve after Stop.
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800324 err := server.AddName("name doesn't matter")
Todd Wang8fa38762015-03-25 14:04:59 -0700325 if err == nil || verror.ErrorID(err) != verror.ErrBadState.ID {
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700326 t.Errorf("either no error, or a wrong error was returned: %v", err)
327 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700328 vlog.VI(1).Info("server.Stop DONE")
329}
330
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800331// fakeWSName creates a name containing a endpoint address that forces
332// the use of websockets. It does so by resolving the original name
333// and choosing the 'ws' endpoint from the set of endpoints returned.
334// It must return a name since it'll be passed to StartCall.
Todd Wang5082a552015-04-02 10:56:11 -0700335func fakeWSName(ctx *context.T, ns namespace.T, name string) (string, error) {
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800336 // Find the ws endpoint and use that.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700337 me, err := ns.Resolve(ctx, name)
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800338 if err != nil {
339 return "", err
340 }
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800341 names := me.Names()
342 for _, s := range names {
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800343 if strings.Index(s, "@ws@") != -1 {
344 return s, nil
345 }
346 }
Cosmos Nicolaou8bd8e102015-01-13 21:52:53 -0800347 return "", fmt.Errorf("No ws endpoint found %v", names)
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800348}
349
Bogdan Caprita27953142014-05-12 11:41:42 -0700350type bundle struct {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700351 client rpc.Client
352 server rpc.Server
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700353 ep naming.Endpoint
Todd Wang5082a552015-04-02 10:56:11 -0700354 ns namespace.T
Bogdan Caprita27953142014-05-12 11:41:42 -0700355 sm stream.Manager
Ankure49a86a2014-11-11 18:52:43 -0800356 name string
Bogdan Caprita27953142014-05-12 11:41:42 -0700357}
358
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700359func (b bundle) cleanup(t *testing.T, ctx *context.T) {
Ankura3c97652014-07-17 20:01:21 -0700360 if b.server != nil {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700361 stopServer(t, ctx, b.server, b.ns, b.name)
Ankura3c97652014-07-17 20:01:21 -0700362 }
363 if b.client != nil {
364 b.client.Close()
365 }
Bogdan Caprita27953142014-05-12 11:41:42 -0700366}
367
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700368func createBundle(t *testing.T, ctx *context.T, server security.Principal, ts interface{}) (b bundle) {
369 return createBundleWS(t, ctx, server, ts, noWebsocket)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -0800370}
371
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700372func createBundleWS(t *testing.T, ctx *context.T, server security.Principal, ts interface{}, shouldUseWebsocket websocketMode) (b bundle) {
Bogdan Caprita27953142014-05-12 11:41:42 -0700373 b.sm = imanager.InternalNew(naming.FixedRoutingID(0x555555555))
Matt Rosencrantz9fe60822014-09-12 10:09:53 -0700374 b.ns = tnaming.NewSimpleNamespace()
Ankure49a86a2014-11-11 18:52:43 -0800375 b.name = "mountpoint/server"
Asim Shankar8f05c222014-10-06 22:08:19 -0700376 if server != nil {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700377 b.ep, b.server = startServerWS(t, ctx, server, b.sm, b.ns, b.name, testServerDisp{ts}, shouldUseWebsocket)
Ankura3c97652014-07-17 20:01:21 -0700378 }
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700379 var err error
380 if b.client, err = InternalNewClient(b.sm, b.ns); err != nil {
381 t.Fatalf("InternalNewClient failed: %v", err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700382 }
Bogdan Caprita27953142014-05-12 11:41:42 -0700383 return
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700384}
385
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800386func matchesErrorPattern(err error, id verror.IDAction, pattern string) bool {
Asim Shankar558ea012015-01-28 12:49:36 -0800387 if len(pattern) > 0 && err != nil && strings.Index(err.Error(), pattern) < 0 {
388 return false
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700389 }
Cosmos Nicolaou1bce7d12015-01-05 17:42:06 -0800390 if err == nil && id.ID == "" {
391 return true
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800392 }
Todd Wang8fa38762015-03-25 14:04:59 -0700393 return verror.ErrorID(err) == id.ID
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700394}
395
Todd Wang5082a552015-04-02 10:56:11 -0700396func 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 -0800397 rid, err := naming.NewRoutingID()
398 if err != nil {
399 t.Fatal(err)
400 }
401 sm := imanager.InternalNew(rid)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700402 server, err := testInternalNewServer(ctx, sm, ns, principal, opts...)
Suharsh Sivakumar0902b7f2015-02-27 19:06:41 -0800403 if err != nil {
404 t.Fatal(err)
405 }
406 if _, err := server.Listen(listenSpec); err != nil {
407 t.Fatal(err)
408 }
Asim Shankar149b4972015-04-23 13:29:58 -0700409 if err := server.Serve(name, obj, security.AllowEveryone()); err != nil {
Suharsh Sivakumar0902b7f2015-02-27 19:06:41 -0800410 t.Fatal(err)
411 }
412 return sm
413}
414
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800415func TestMultipleCallsToServeAndName(t *testing.T) {
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700416 sm := imanager.InternalNew(naming.FixedRoutingID(0x555555555))
Matt Rosencrantz9fe60822014-09-12 10:09:53 -0700417 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700418 ctx, shutdown := initForTest()
419 defer shutdown()
Asim Shankar4a698282015-03-21 21:59:18 -0700420 server, err := testInternalNewServer(ctx, sm, ns, testutil.NewPrincipal("server"))
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700421 if err != nil {
422 t.Errorf("InternalNewServer failed: %v", err)
423 }
Cosmos Nicolaouf8d4c2b2014-10-23 22:36:38 -0700424 _, err = server.Listen(listenSpec)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700425 if err != nil {
426 t.Errorf("server.Listen failed: %v", err)
427 }
428
429 disp := &testServerDisp{&testServer{}}
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800430 if err := server.ServeDispatcher("mountpoint/server", disp); err != nil {
431 t.Errorf("server.ServeDispatcher failed: %v", err)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700432 }
433
434 n1 := "mountpoint/server"
435 n2 := "should_appear_in_mt/server"
436 n3 := "should_appear_in_mt/server"
437 n4 := "should_not_appear_in_mt/server"
438
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700439 verifyMount(t, ctx, ns, n1)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700440
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800441 if server.ServeDispatcher(n2, disp) == nil {
442 t.Errorf("server.ServeDispatcher should have failed")
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700443 }
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800444
445 if err := server.Serve(n2, &testServer{}, nil); err == nil {
446 t.Errorf("server.Serve should have failed")
447 }
448
449 if err := server.AddName(n3); err != nil {
450 t.Errorf("server.AddName failed: %v", err)
451 }
452
453 if err := server.AddName(n3); err != nil {
454 t.Errorf("server.AddName failed: %v", err)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700455 }
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700456 verifyMount(t, ctx, ns, n2)
457 verifyMount(t, ctx, ns, n3)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700458
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800459 server.RemoveName(n1)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700460 verifyMountMissing(t, ctx, ns, n1)
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800461
Cosmos Nicolaou9fbe7d22015-01-25 22:13:13 -0800462 server.RemoveName("some randome name")
Cosmos Nicolaou92dba582014-11-05 17:24:10 -0800463
464 if err := server.ServeDispatcher(n4, &testServerDisp{&testServer{}}); err == nil {
465 t.Errorf("server.ServeDispatcher should have failed")
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700466 }
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700467 verifyMountMissing(t, ctx, ns, n4)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700468
469 if err := server.Stop(); err != nil {
470 t.Errorf("server.Stop failed: %v", err)
471 }
472
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700473 verifyMountMissing(t, ctx, ns, n1)
474 verifyMountMissing(t, ctx, ns, n2)
475 verifyMountMissing(t, ctx, ns, n3)
Cosmos Nicolaoufdc838b2014-06-30 21:44:27 -0700476}
477
Ankure49a86a2014-11-11 18:52:43 -0800478func TestRPCServerAuthorization(t *testing.T) {
Asim Shankar263c73b2015-03-19 18:31:26 -0700479 ctx, shutdown := initForTest()
480 defer shutdown()
481
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700482 const (
Asim Shankar263c73b2015-03-19 18:31:26 -0700483 publicKeyErr = "not matched by server key"
484 missingDischargeErr = "missing discharge"
485 expiryErr = "is after expiry"
486 allowedErr = "do not match any allowed server patterns"
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700487 )
Asim Shankar263c73b2015-03-19 18:31:26 -0700488 type O []rpc.CallOpt // shorthand
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700489 var (
Asim Shankar4a698282015-03-21 21:59:18 -0700490 pprovider, pclient, pserver = testutil.NewPrincipal("root"), testutil.NewPrincipal(), testutil.NewPrincipal()
Ankure49a86a2014-11-11 18:52:43 -0800491 pdischarger = pprovider
Asim Shankar558ea012015-01-28 12:49:36 -0800492 now = time.Now()
493 noErrID verror.IDAction
Ankure49a86a2014-11-11 18:52:43 -0800494
495 // Third-party caveats on blessings presented by server.
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -0700496 cavTPValid = mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/dischargeserver", mkCaveat(security.NewExpiryCaveat(now.Add(24*time.Hour))))
497 cavTPExpired = mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/dischargeserver", mkCaveat(security.NewExpiryCaveat(now.Add(-1*time.Second))))
Ankure49a86a2014-11-11 18:52:43 -0800498
499 // Server blessings.
500 bServer = bless(pprovider, pserver, "server")
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -0700501 bServerExpired = bless(pprovider, pserver, "expiredserver", mkCaveat(security.NewExpiryCaveat(time.Now().Add(-1*time.Second))))
Ankure49a86a2014-11-11 18:52:43 -0800502 bServerTPValid = bless(pprovider, pserver, "serverWithTPCaveats", cavTPValid)
Asim Shankar263c73b2015-03-19 18:31:26 -0700503 bServerTPExpired = bless(pprovider, pserver, "serverWithExpiredTPCaveats", cavTPExpired)
504 bOther = bless(pprovider, pserver, "other")
505 bTwoBlessings, _ = security.UnionOfBlessings(bServer, bOther)
Asim Shankar8f05c222014-10-06 22:08:19 -0700506
507 mgr = imanager.InternalNew(naming.FixedRoutingID(0x1111111))
508 ns = tnaming.NewSimpleNamespace()
509 tests = []struct {
Ankur50a5f392015-02-27 18:46:30 -0800510 server security.Blessings // blessings presented by the server to the client.
511 name string // name provided by the client to StartCall
Asim Shankar263c73b2015-03-19 18:31:26 -0700512 opts O // options provided to StartCall.
Ankur50a5f392015-02-27 18:46:30 -0800513 errID verror.IDAction
514 err string
Asim Shankar8f05c222014-10-06 22:08:19 -0700515 }{
Asim Shankar558ea012015-01-28 12:49:36 -0800516 // Client accepts talking to the server only if the
Asim Shankar263c73b2015-03-19 18:31:26 -0700517 // server presents valid blessings (and discharges)
518 // consistent with the ones published in the endpoint.
519 {bServer, "mountpoint/server", nil, noErrID, ""},
520 {bServerTPValid, "mountpoint/server", nil, noErrID, ""},
Asim Shankar8f05c222014-10-06 22:08:19 -0700521
Asim Shankar263c73b2015-03-19 18:31:26 -0700522 // Client will not talk to a server that presents
523 // expired blessings or is missing discharges.
524 {bServerExpired, "mountpoint/server", nil, verror.ErrNotTrusted, expiryErr},
525 {bServerTPExpired, "mountpoint/server", nil, verror.ErrNotTrusted, missingDischargeErr},
Asim Shankar558ea012015-01-28 12:49:36 -0800526
527 // Testing the AllowedServersPolicy option.
Asim Shankar263c73b2015-03-19 18:31:26 -0700528 {bServer, "mountpoint/server", O{options.AllowedServersPolicy{"otherroot"}}, verror.ErrNotTrusted, allowedErr},
529 {bServer, "mountpoint/server", O{options.AllowedServersPolicy{"root"}}, noErrID, ""},
530 {bTwoBlessings, "mountpoint/server", O{options.AllowedServersPolicy{"root/other"}}, noErrID, ""},
Ankur50a5f392015-02-27 18:46:30 -0800531
532 // Test the ServerPublicKey option.
Asim Shankar263c73b2015-03-19 18:31:26 -0700533 {bOther, "mountpoint/server", O{options.SkipServerEndpointAuthorization{}, options.ServerPublicKey{bOther.PublicKey()}}, noErrID, ""},
Asim Shankar4a698282015-03-21 21:59:18 -0700534 {bOther, "mountpoint/server", O{options.SkipServerEndpointAuthorization{}, options.ServerPublicKey{testutil.NewPrincipal("irrelevant").PublicKey()}}, verror.ErrNotTrusted, publicKeyErr},
Asim Shankar263c73b2015-03-19 18:31:26 -0700535
536 // Test the "paranoid" names, where the pattern is provided in the name.
537 {bServer, "__(root/server)/mountpoint/server", nil, noErrID, ""},
538 {bServer, "__(root/other)/mountpoint/server", nil, verror.ErrNotTrusted, allowedErr},
539 {bTwoBlessings, "__(root/server)/mountpoint/server", O{options.AllowedServersPolicy{"root/other"}}, noErrID, ""},
Asim Shankar8f05c222014-10-06 22:08:19 -0700540 }
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700541 )
Ankure49a86a2014-11-11 18:52:43 -0800542 // Start the discharge server.
Asim Shankar149b4972015-04-23 13:29:58 -0700543 _, dischargeServer := startServer(t, ctx, pdischarger, mgr, ns, "mountpoint/dischargeserver", testutil.LeafDispatcher(&dischargeServer{}, security.AllowEveryone()))
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700544 defer stopServer(t, ctx, dischargeServer, ns, "mountpoint/dischargeserver")
Ankure49a86a2014-11-11 18:52:43 -0800545
Asim Shankar558ea012015-01-28 12:49:36 -0800546 // Make the client and server principals trust root certificates from
547 // pprovider
Asim Shankar8f05c222014-10-06 22:08:19 -0700548 pclient.AddToRoots(pprovider.BlessingStore().Default())
549 pserver.AddToRoots(pprovider.BlessingStore().Default())
Asim Shankar263c73b2015-03-19 18:31:26 -0700550 // Set a blessing that the client is willing to share with servers
551 // (that are blessed by pprovider).
Ankur78b8b2a2015-02-04 20:16:28 -0800552 pclient.BlessingStore().Set(bless(pprovider, pclient, "client"), "root")
Asim Shankar558ea012015-01-28 12:49:36 -0800553
Todd Wangad492042015-04-17 15:58:40 -0700554 clientCtx, _ := v23.WithPrincipal(ctx, pclient)
Asim Shankar263c73b2015-03-19 18:31:26 -0700555 client, err := InternalNewClient(mgr, ns)
556 if err != nil {
557 t.Fatal(err)
558 }
559 defer client.Close()
560
561 var server rpc.Server
562 stop := func() {
563 if server != nil {
564 stopServer(t, ctx, server, ns, "mountpoint/server")
565 }
566 }
567 defer stop()
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800568 for i, test := range tests {
Asim Shankar263c73b2015-03-19 18:31:26 -0700569 stop() // Stop any server started in the previous test.
570 name := fmt.Sprintf("(#%d: Name:%q, Server:%q, opts:%v)", i, test.name, test.server, test.opts)
Ankure49a86a2014-11-11 18:52:43 -0800571 if err := pserver.BlessingStore().SetDefault(test.server); err != nil {
572 t.Fatalf("SetDefault failed on server's BlessingStore: %v", err)
573 }
Ankur78b8b2a2015-02-04 20:16:28 -0800574 if _, err := pserver.BlessingStore().Set(test.server, "root"); err != nil {
Ankure49a86a2014-11-11 18:52:43 -0800575 t.Fatalf("Set failed on server's BlessingStore: %v", err)
576 }
Asim Shankar263c73b2015-03-19 18:31:26 -0700577 _, server = startServer(t, ctx, pserver, mgr, ns, "mountpoint/server", testServerDisp{&testServer{}})
578 clientCtx, cancel := context.WithCancel(clientCtx)
579 call, err := client.StartCall(clientCtx, test.name, "Method", nil, test.opts...)
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800580 if !matchesErrorPattern(err, test.errID, test.err) {
Asim Shankarb547ea92015-02-17 18:49:45 -0800581 t.Errorf(`%s: client.StartCall: got error "%v", want to match "%v"`, name, err, test.err)
Asim Shankar2d731a92014-09-29 17:46:38 -0700582 } else if call != nil {
Asim Shankar8f05c222014-10-06 22:08:19 -0700583 blessings, proof := call.RemoteBlessings()
Asim Shankar2bf7b1e2015-02-27 00:45:12 -0800584 if proof.IsZero() {
585 t.Errorf("%s: Returned zero value for remote blessings", name)
Asim Shankar8f05c222014-10-06 22:08:19 -0700586 }
Asim Shankar558ea012015-01-28 12:49:36 -0800587 // Currently all tests are configured so that the only
588 // blessings presented by the server that are
589 // recognized by the client match the pattern
Ankur78b8b2a2015-02-04 20:16:28 -0800590 // "root"
591 if len(blessings) < 1 || !security.BlessingPattern("root").MatchedBy(blessings...) {
592 t.Errorf("%s: Client sees server as %v, expected a single blessing matching root", name, blessings)
Asim Shankar2d731a92014-09-29 17:46:38 -0700593 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700594 }
Matt Rosencrantzcc922c12014-11-28 20:28:59 -0800595 cancel()
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700596 }
597}
598
Asim Shankarb547ea92015-02-17 18:49:45 -0800599func TestServerManInTheMiddleAttack(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700600 ctx, shutdown := initForTest()
601 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -0700602 // Test scenario: A server mounts itself, but then some other service
603 // somehow "takes over" the network endpoint (a naughty router
604 // perhaps), thus trying to steal traffic.
605 var (
Asim Shankar4a698282015-03-21 21:59:18 -0700606 pclient = testutil.NewPrincipal("client")
607 pserver = testutil.NewPrincipal("server")
608 pattacker = testutil.NewPrincipal("attacker")
Asim Shankar263c73b2015-03-19 18:31:26 -0700609 )
610 // Client recognizes both the server and the attacker's blessings.
611 // (Though, it doesn't need to do the latter for the purposes of this
612 // test).
613 pclient.AddToRoots(pserver.BlessingStore().Default())
614 pclient.AddToRoots(pattacker.BlessingStore().Default())
Asim Shankarb547ea92015-02-17 18:49:45 -0800615
616 // Start up the attacker's server.
617 attacker, err := testInternalNewServer(
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700618 ctx,
Asim Shankarb547ea92015-02-17 18:49:45 -0800619 imanager.InternalNew(naming.FixedRoutingID(0xaaaaaaaaaaaaaaaa)),
620 // (To prevent the attacker for legitimately mounting on the
621 // namespace that the client will use, provide it with a
622 // different namespace).
623 tnaming.NewSimpleNamespace(),
Asim Shankar263c73b2015-03-19 18:31:26 -0700624 pattacker)
Asim Shankarb547ea92015-02-17 18:49:45 -0800625 if err != nil {
626 t.Fatal(err)
627 }
628 if _, err := attacker.Listen(listenSpec); err != nil {
629 t.Fatal(err)
630 }
631 if err := attacker.ServeDispatcher("mountpoint/server", testServerDisp{&testServer{}}); err != nil {
632 t.Fatal(err)
633 }
634 var ep naming.Endpoint
635 if status := attacker.Status(); len(status.Endpoints) < 1 {
636 t.Fatalf("Attacker server does not have an endpoint: %+v", status)
637 } else {
638 ep = status.Endpoints[0]
639 }
640
641 // The legitimate server would have mounted the same endpoint on the
Asim Shankar263c73b2015-03-19 18:31:26 -0700642 // namespace, but with different blessings.
Asim Shankarb547ea92015-02-17 18:49:45 -0800643 ns := tnaming.NewSimpleNamespace()
Asim Shankar263c73b2015-03-19 18:31:26 -0700644 ep.(*inaming.Endpoint).Blessings = []string{"server"}
645 if err := ns.Mount(ctx, "mountpoint/server", ep.Name(), time.Hour); err != nil {
Asim Shankarb547ea92015-02-17 18:49:45 -0800646 t.Fatal(err)
647 }
648
649 // The RPC call should fail because the blessings presented by the
650 // (attacker's) server are not consistent with the ones registered in
651 // the mounttable trusted by the client.
652 client, err := InternalNewClient(
653 imanager.InternalNew(naming.FixedRoutingID(0xcccccccccccccccc)),
Asim Shankar263c73b2015-03-19 18:31:26 -0700654 ns)
Asim Shankarb547ea92015-02-17 18:49:45 -0800655 if err != nil {
656 t.Fatal(err)
657 }
658 defer client.Close()
Todd Wangad492042015-04-17 15:58:40 -0700659 ctx, _ = v23.WithPrincipal(ctx, pclient)
Todd Wang8fa38762015-03-25 14:04:59 -0700660 if _, err := client.StartCall(ctx, "mountpoint/server", "Closure", nil); verror.ErrorID(err) != verror.ErrNotTrusted.ID {
Asim Shankarb547ea92015-02-17 18:49:45 -0800661 t.Errorf("Got error %v (errorid=%v), want errorid=%v", err, verror.ErrorID(err), verror.ErrNotTrusted.ID)
662 }
663 // But the RPC should succeed if the client explicitly
664 // decided to skip server authorization.
Asim Shankar263c73b2015-03-19 18:31:26 -0700665 if _, err := client.StartCall(ctx, "mountpoint/server", "Closure", nil, options.SkipServerEndpointAuthorization{}); err != nil {
Asim Shankarb547ea92015-02-17 18:49:45 -0800666 t.Errorf("Unexpected error(%v) when skipping server authorization", err)
667 }
668}
669
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800670type websocketMode bool
671type closeSendMode bool
672
673const (
674 useWebsocket websocketMode = true
675 noWebsocket websocketMode = false
676
677 closeSend closeSendMode = true
678 noCloseSend closeSendMode = false
679)
680
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700681func TestRPC(t *testing.T) {
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800682 testRPC(t, closeSend, noWebsocket)
683}
684
685func TestRPCWithWebsocket(t *testing.T) {
686 testRPC(t, closeSend, useWebsocket)
Tilak Sharma0c766112014-05-20 17:47:27 -0700687}
688
689// TestCloseSendOnFinish tests that Finish informs the server that no more
690// inputs will be sent by the client if CloseSend has not already done so.
691func TestRPCCloseSendOnFinish(t *testing.T) {
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800692 testRPC(t, noCloseSend, noWebsocket)
Tilak Sharma0c766112014-05-20 17:47:27 -0700693}
694
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800695func TestRPCCloseSendOnFinishWithWebsocket(t *testing.T) {
696 testRPC(t, noCloseSend, useWebsocket)
697}
698
699func testRPC(t *testing.T, shouldCloseSend closeSendMode, shouldUseWebsocket websocketMode) {
Asim Shankar263c73b2015-03-19 18:31:26 -0700700 ctx, shutdown := initForTest()
701 defer shutdown()
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700702 type v []interface{}
703 type testcase struct {
704 name string
705 method string
706 args v
707 streamArgs v
708 startErr error
709 results v
710 finishErr error
711 }
Asim Shankar8f05c222014-10-06 22:08:19 -0700712 var (
713 tests = []testcase{
714 {"mountpoint/server/suffix", "Closure", nil, nil, nil, nil, nil},
Todd Wange77f9952015-02-18 13:20:50 -0800715 {"mountpoint/server/suffix", "Error", nil, nil, nil, nil, errMethod},
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700716
Asim Shankar8f05c222014-10-06 22:08:19 -0700717 {"mountpoint/server/suffix", "Echo", v{"foo"}, nil, nil, v{`method:"Echo",suffix:"suffix",arg:"foo"`}, nil},
718 {"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 -0700719
Asim Shankar8f05c222014-10-06 22:08:19 -0700720 {"mountpoint/server/suffix", "EchoUser", v{"foo", userType("bar")}, nil, nil, v{`method:"EchoUser",suffix:"suffix",arg:"foo"`, userType("bar")}, nil},
721 {"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 -0800722 {"mountpoint/server/suffix", "Stream", v{"foo"}, v{userType("bar"), userType("baz")}, nil, v{`method:"Stream",suffix:"suffix",arg:"foo" bar baz`}, nil},
723 {"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 -0700724 {"mountpoint/server/suffix", "EchoBlessings", nil, nil, nil, v{"[server]", "[client]"}, nil},
Todd Wange77f9952015-02-18 13:20:50 -0800725 {"mountpoint/server/suffix", "EchoAndError", v{"bugs bunny"}, nil, nil, v{`method:"EchoAndError",suffix:"suffix",arg:"bugs bunny"`}, nil},
726 {"mountpoint/server/suffix", "EchoAndError", v{"error"}, nil, nil, nil, errMethod},
Matt Rosencrantz88be1182015-04-27 13:45:43 -0700727 {"mountpoint/server/suffix", "EchoLang", nil, nil, nil, v{"foolang"}, nil},
Asim Shankar8f05c222014-10-06 22:08:19 -0700728 }
729 name = func(t testcase) string {
730 return fmt.Sprintf("%s.%s(%v)", t.name, t.method, t.args)
731 }
732
Asim Shankar263c73b2015-03-19 18:31:26 -0700733 pclient, pserver = newClientServerPrincipals()
734 b = createBundleWS(t, ctx, pserver, &testServer{}, shouldUseWebsocket)
Asim Shankar8f05c222014-10-06 22:08:19 -0700735 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700736 defer b.cleanup(t, ctx)
Todd Wangad492042015-04-17 15:58:40 -0700737 ctx, _ = v23.WithPrincipal(ctx, pclient)
Matt Rosencrantz88be1182015-04-27 13:45:43 -0700738 ctx = i18n.WithLangID(ctx, "foolang")
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700739 for _, test := range tests {
740 vlog.VI(1).Infof("%s client.StartCall", name(test))
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800741 vname := test.name
742 if shouldUseWebsocket {
743 var err error
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700744 vname, err = fakeWSName(ctx, b.ns, vname)
Shyam Jayaramandbae76b2014-11-17 12:51:29 -0800745 if err != nil && err != test.startErr {
746 t.Errorf(`%s ns.Resolve got error "%v", want "%v"`, name(test), err, test.startErr)
747 continue
748 }
749 }
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700750 call, err := b.client.StartCall(ctx, vname, test.method, test.args)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700751 if err != test.startErr {
752 t.Errorf(`%s client.StartCall got error "%v", want "%v"`, name(test), err, test.startErr)
753 continue
754 }
755 for _, sarg := range test.streamArgs {
756 vlog.VI(1).Infof("%s client.Send(%v)", name(test), sarg)
757 if err := call.Send(sarg); err != nil {
758 t.Errorf(`%s call.Send(%v) got unexpected error "%v"`, name(test), sarg, err)
759 }
760 var u userType
761 if err := call.Recv(&u); err != nil {
762 t.Errorf(`%s call.Recv(%v) got unexpected error "%v"`, name(test), sarg, err)
763 }
764 if !reflect.DeepEqual(u, sarg) {
765 t.Errorf("%s call.Recv got value %v, want %v", name(test), u, sarg)
766 }
767 }
Tilak Sharma0c766112014-05-20 17:47:27 -0700768 if shouldCloseSend {
769 vlog.VI(1).Infof("%s call.CloseSend", name(test))
Asim Shankar062d4222014-08-18 11:14:42 -0700770 // When the method does not involve streaming
771 // arguments, the server gets all the arguments in
772 // StartCall and then sends a response without
773 // (unnecessarily) waiting for a CloseSend message from
774 // the client. If the server responds before the
775 // CloseSend call is made at the client, the CloseSend
776 // call will fail. Thus, only check for errors on
777 // CloseSend if there are streaming arguments to begin
778 // with (i.e., only if the server is expected to wait
779 // for the CloseSend notification).
780 if err := call.CloseSend(); err != nil && len(test.streamArgs) > 0 {
Tilak Sharma0c766112014-05-20 17:47:27 -0700781 t.Errorf(`%s call.CloseSend got unexpected error "%v"`, name(test), err)
782 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700783 }
784 vlog.VI(1).Infof("%s client.Finish", name(test))
785 results := makeResultPtrs(test.results)
786 err = call.Finish(results...)
Todd Wange77f9952015-02-18 13:20:50 -0800787 if got, want := err, test.finishErr; (got == nil) != (want == nil) {
788 t.Errorf(`%s call.Finish got error "%v", want "%v'`, name(test), got, want)
Todd Wang8fa38762015-03-25 14:04:59 -0700789 } else if want != nil && verror.ErrorID(got) != verror.ErrorID(want) {
Todd Wange77f9952015-02-18 13:20:50 -0800790 t.Errorf(`%s call.Finish got error "%v", want "%v"`, name(test), got, want)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700791 }
792 checkResultPtrs(t, name(test), results, test.results)
793 }
794}
795
Ken Ashcraft2b8309a2014-09-09 10:44:43 -0700796func TestMultipleFinish(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700797 ctx, shutdown := initForTest()
798 defer shutdown()
Ken Ashcraft2b8309a2014-09-09 10:44:43 -0700799 type v []interface{}
Asim Shankar263c73b2015-03-19 18:31:26 -0700800 var (
801 pclient, pserver = newClientServerPrincipals()
802 b = createBundle(t, ctx, pserver, &testServer{})
803 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700804 defer b.cleanup(t, ctx)
Todd Wangad492042015-04-17 15:58:40 -0700805 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700806 call, err := b.client.StartCall(ctx, "mountpoint/server/suffix", "Echo", v{"foo"})
Ken Ashcraft2b8309a2014-09-09 10:44:43 -0700807 if err != nil {
808 t.Fatalf(`client.StartCall got error "%v"`, err)
809 }
810 var results string
811 err = call.Finish(&results)
812 if err != nil {
813 t.Fatalf(`call.Finish got error "%v"`, err)
814 }
815 // Calling Finish a second time should result in a useful error.
Jiri Simsa074bf362015-02-17 09:29:45 -0800816 if err = call.Finish(&results); !matchesErrorPattern(err, verror.ErrBadState, "Finish has already been called") {
817 t.Fatalf(`got "%v", want "%v"`, err, verror.ErrBadState)
Ken Ashcraft2b8309a2014-09-09 10:44:43 -0700818 }
819}
820
Ankurdda16492015-04-07 12:35:42 -0700821// granter implements rpc.Granter.
822//
823// It returns the specified (security.Blessings, error) pair if either the
824// blessing or the error is specified. Otherwise it returns a blessing
825// derived from the local blessings of the current call.
Asim Shankarb54d7642014-06-05 13:08:04 -0700826type granter struct {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700827 rpc.CallOpt
Asim Shankar8f05c222014-10-06 22:08:19 -0700828 b security.Blessings
Asim Shankarb54d7642014-06-05 13:08:04 -0700829 err error
830}
831
Todd Wang4264e4b2015-04-16 22:43:40 -0700832func (g granter) Grant(ctx *context.T, call security.Call) (security.Blessings, error) {
Ankurdda16492015-04-07 12:35:42 -0700833 if !g.b.IsZero() || g.err != nil {
834 return g.b, g.err
835 }
Ankurdda16492015-04-07 12:35:42 -0700836 return call.LocalPrincipal().Bless(call.RemoteBlessings().PublicKey(), call.LocalBlessings(), "blessed", security.UnconstrainedUse())
837}
Asim Shankarb54d7642014-06-05 13:08:04 -0700838
Asim Shankar8f05c222014-10-06 22:08:19 -0700839func TestGranter(t *testing.T) {
840 var (
Asim Shankar263c73b2015-03-19 18:31:26 -0700841 pclient, pserver = newClientServerPrincipals()
842 ctx, shutdown = initForTest()
843 b = createBundle(t, ctx, pserver, &testServer{})
Asim Shankar8f05c222014-10-06 22:08:19 -0700844 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700845 defer shutdown()
846 defer b.cleanup(t, ctx)
847
Todd Wangad492042015-04-17 15:58:40 -0700848 ctx, _ = v23.WithPrincipal(ctx, pclient)
Asim Shankarb54d7642014-06-05 13:08:04 -0700849 tests := []struct {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700850 granter rpc.Granter
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800851 startErrID, finishErrID verror.IDAction
Asim Shankarb54d7642014-06-05 13:08:04 -0700852 blessing, starterr, finisherr string
853 }{
Asim Shankar2bf7b1e2015-02-27 00:45:12 -0800854 {blessing: ""},
Asim Shankarb18a44f2014-10-21 20:25:07 -0700855 {granter: granter{b: bless(pclient, pserver, "blessed")}, blessing: "client/blessed"},
Jiri Simsa074bf362015-02-17 09:29:45 -0800856 {granter: granter{err: errors.New("hell no")}, startErrID: verror.ErrNotTrusted, starterr: "hell no"},
Ankurdda16492015-04-07 12:35:42 -0700857 {granter: granter{}, blessing: "client/blessed"},
Jiri Simsa074bf362015-02-17 09:29:45 -0800858 {granter: granter{b: pclient.BlessingStore().Default()}, finishErrID: verror.ErrNoAccess, finisherr: "blessing granted not bound to this server"},
Asim Shankarb54d7642014-06-05 13:08:04 -0700859 }
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800860 for i, test := range tests {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700861 call, err := b.client.StartCall(ctx, "mountpoint/server/suffix", "EchoGrantedBlessings", []interface{}{"argument"}, test.granter)
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800862 if !matchesErrorPattern(err, test.startErrID, test.starterr) {
863 t.Errorf("%d: %+v: StartCall returned error %v", i, test, err)
Asim Shankarb54d7642014-06-05 13:08:04 -0700864 }
865 if err != nil {
866 continue
867 }
868 var result, blessing string
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800869 if err = call.Finish(&result, &blessing); !matchesErrorPattern(err, test.finishErrID, test.finisherr) {
Asim Shankarb54d7642014-06-05 13:08:04 -0700870 t.Errorf("%+v: Finish returned error %v", test, err)
871 }
872 if err != nil {
873 continue
874 }
875 if result != "argument" || blessing != test.blessing {
876 t.Errorf("%+v: Got (%q, %q)", test, result, blessing)
877 }
878 }
879}
880
Asim Shankarf4864f42014-11-25 18:53:05 -0800881// dischargeTestServer implements the discharge service. Always fails to
882// issue a discharge, but records the impetus and traceid of the RPC call.
883type dischargeTestServer struct {
884 p security.Principal
885 impetus []security.DischargeImpetus
Benjamin Prosnitzc97fe192015-02-03 10:33:25 -0800886 traceid []uniqueid.Id
Asim Shankara94e5072014-08-19 18:18:36 -0700887}
888
Todd Wang54feabe2015-04-15 23:38:26 -0700889func (s *dischargeTestServer) Discharge(ctx *context.T, _ rpc.ServerCall, cav security.Caveat, impetus security.DischargeImpetus) (security.Discharge, error) {
Asim Shankarc8cfcf12014-11-20 12:26:58 -0800890 s.impetus = append(s.impetus, impetus)
Todd Wang54feabe2015-04-15 23:38:26 -0700891 s.traceid = append(s.traceid, vtrace.GetSpan(ctx).Trace())
Asim Shankar08642822015-03-02 21:21:09 -0800892 return security.Discharge{}, fmt.Errorf("discharges not issued")
Asim Shankara94e5072014-08-19 18:18:36 -0700893}
894
Benjamin Prosnitzc97fe192015-02-03 10:33:25 -0800895func (s *dischargeTestServer) Release() ([]security.DischargeImpetus, []uniqueid.Id) {
Asim Shankarf4864f42014-11-25 18:53:05 -0800896 impetus, traceid := s.impetus, s.traceid
897 s.impetus, s.traceid = nil, nil
898 return impetus, traceid
Asim Shankarc8cfcf12014-11-20 12:26:58 -0800899}
900
Asim Shankarf4864f42014-11-25 18:53:05 -0800901func TestDischargeImpetusAndContextPropagation(t *testing.T) {
Asim Shankar263c73b2015-03-19 18:31:26 -0700902 ctx, shutdown := initForTest()
903 defer shutdown()
Asim Shankara94e5072014-08-19 18:18:36 -0700904 var (
Asim Shankar4a698282015-03-21 21:59:18 -0700905 pserver = testutil.NewPrincipal("server")
906 pdischarger = testutil.NewPrincipal("discharger")
907 pclient = testutil.NewPrincipal("client")
Asim Shankar8f05c222014-10-06 22:08:19 -0700908 sm = imanager.InternalNew(naming.FixedRoutingID(0x555555555))
909 ns = tnaming.NewSimpleNamespace()
Asim Shankara94e5072014-08-19 18:18:36 -0700910
Asim Shankar263c73b2015-03-19 18:31:26 -0700911 // Setup the client so that it shares a blessing with a third-party caveat with the server.
912 setClientBlessings = func(req security.ThirdPartyRequirements) security.Principal {
Asim Shankar7283dd82015-02-03 19:35:58 -0800913 cav, err := security.NewPublicKeyCaveat(pdischarger.PublicKey(), "mountpoint/discharger", req, security.UnconstrainedUse())
Asim Shankara94e5072014-08-19 18:18:36 -0700914 if err != nil {
Asim Shankar8f05c222014-10-06 22:08:19 -0700915 t.Fatalf("Failed to create ThirdPartyCaveat(%+v): %v", req, err)
Asim Shankara94e5072014-08-19 18:18:36 -0700916 }
Asim Shankarf4864f42014-11-25 18:53:05 -0800917 b, err := pclient.BlessSelf("client_for_server", cav)
Asim Shankar8f05c222014-10-06 22:08:19 -0700918 if err != nil {
919 t.Fatalf("BlessSelf failed: %v", err)
920 }
Asim Shankar8f05c222014-10-06 22:08:19 -0700921 pclient.BlessingStore().Set(b, "server")
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700922 return pclient
Asim Shankara94e5072014-08-19 18:18:36 -0700923 }
924 )
Asim Shankarf4864f42014-11-25 18:53:05 -0800925 // Initialize the client principal.
926 // It trusts both the application server and the discharger.
927 pclient.AddToRoots(pserver.BlessingStore().Default())
928 pclient.AddToRoots(pdischarger.BlessingStore().Default())
Asim Shankarf4864f42014-11-25 18:53:05 -0800929
930 // Setup the discharge server.
931 var tester dischargeTestServer
Suharsh Sivakumar59c423c2015-03-11 14:06:03 -0700932 dischargeServer, err := testInternalNewServer(ctx, sm, ns, pdischarger)
Asim Shankara94e5072014-08-19 18:18:36 -0700933 if err != nil {
934 t.Fatal(err)
935 }
Asim Shankarf4864f42014-11-25 18:53:05 -0800936 defer dischargeServer.Stop()
937 if _, err := dischargeServer.Listen(listenSpec); err != nil {
938 t.Fatal(err)
939 }
940 if err := dischargeServer.Serve("mountpoint/discharger", &tester, &testServerAuthorizer{}); err != nil {
Asim Shankara94e5072014-08-19 18:18:36 -0700941 t.Fatal(err)
942 }
943
Asim Shankarf4864f42014-11-25 18:53:05 -0800944 // Setup the application server.
Suharsh Sivakumar59c423c2015-03-11 14:06:03 -0700945 appServer, err := testInternalNewServer(ctx, sm, ns, pserver)
Asim Shankarf4864f42014-11-25 18:53:05 -0800946 if err != nil {
947 t.Fatal(err)
948 }
949 defer appServer.Stop()
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800950 eps, err := appServer.Listen(listenSpec)
Asim Shankarf4864f42014-11-25 18:53:05 -0800951 if err != nil {
952 t.Fatal(err)
953 }
954 // TODO(bjornick,cnicolaou,ashankar): This is a hack to workaround the
955 // fact that a single Listen on the "tcp" protocol followed by a call
956 // to Serve(<name>, ...) transparently creates two endpoints (one for
957 // tcp, one for websockets) and maps both to <name> via a mount.
958 // Because all endpoints to a name are tried in a parallel, this
959 // transparency makes this test hard to follow (many discharge fetch
960 // attempts are made - one for VIF authentication, one for VC
961 // authentication and one for the actual RPC - and having them be made
962 // to two different endpoints in parallel leads to a lot of
963 // non-determinism). The last plan of record known by the author of
964 // this comment was to stop this sly creation of two endpoints and
965 // require that they be done explicitly. When that happens, this hack
966 // can go away, but till then, this workaround allows the test to be
967 // more predictable by ensuring there is only one VIF/VC/Flow to the
968 // server.
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -0800969 object := naming.JoinAddressName(eps[0].String(), "object") // instead of "mountpoint/object"
Asim Shankarf4864f42014-11-25 18:53:05 -0800970 if err := appServer.Serve("mountpoint/object", &testServer{}, &testServerAuthorizer{}); err != nil {
971 t.Fatal(err)
972 }
Asim Shankara94e5072014-08-19 18:18:36 -0700973 tests := []struct {
974 Requirements security.ThirdPartyRequirements
975 Impetus security.DischargeImpetus
976 }{
977 { // No requirements, no impetus
978 Requirements: security.ThirdPartyRequirements{},
979 Impetus: security.DischargeImpetus{},
980 },
981 { // Require everything
982 Requirements: security.ThirdPartyRequirements{ReportServer: true, ReportMethod: true, ReportArguments: true},
Todd Wangb31da592015-02-20 12:50:39 -0800983 Impetus: security.DischargeImpetus{Server: []security.BlessingPattern{"server"}, Method: "Method", Arguments: []*vdl.Value{vdl.StringValue("argument")}},
Asim Shankara94e5072014-08-19 18:18:36 -0700984 },
985 { // Require only the method name
986 Requirements: security.ThirdPartyRequirements{ReportMethod: true},
987 Impetus: security.DischargeImpetus{Method: "Method"},
988 },
989 }
990
Ankur50a5f392015-02-27 18:46:30 -0800991 for _, test := range tests {
Asim Shankar263c73b2015-03-19 18:31:26 -0700992 pclient := setClientBlessings(test.Requirements)
Todd Wangad492042015-04-17 15:58:40 -0700993 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -0700994 client, err := InternalNewClient(sm, ns)
Asim Shankara94e5072014-08-19 18:18:36 -0700995 if err != nil {
996 t.Fatalf("InternalNewClient(%+v) failed: %v", test.Requirements, err)
997 }
998 defer client.Close()
Matt Rosencrantz5f98d942015-01-08 13:48:30 -0800999 tid := vtrace.GetSpan(ctx).Trace()
Asim Shankara94e5072014-08-19 18:18:36 -07001000 // 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 -08001001 if _, err := client.StartCall(ctx, object, "Method", []interface{}{"argument"}); err != nil {
Asim Shankara94e5072014-08-19 18:18:36 -07001002 t.Errorf("StartCall(%+v) failed: %v", test.Requirements, err)
1003 continue
1004 }
Asim Shankarf4864f42014-11-25 18:53:05 -08001005 impetus, traceid := tester.Release()
Ankur50a5f392015-02-27 18:46:30 -08001006 // There should have been exactly 1 attempt to fetch discharges when making
1007 // the RPC to the remote object.
1008 if len(impetus) != 1 || len(traceid) != 1 {
1009 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 -08001010 continue
1011 }
1012 // VC creation does not have any "impetus", it is established without
1013 // knowledge of the context of the RPC. So ignore that.
1014 //
1015 // TODO(ashankar): Should the impetus of the RPC that initiated the
1016 // VIF/VC creation be propagated?
1017 if got, want := impetus[len(impetus)-1], test.Impetus; !reflect.DeepEqual(got, want) {
1018 t.Errorf("Test %+v: Got impetus %v, want %v", test.Requirements, got, want)
1019 }
1020 // But the context used for all of this should be the same
1021 // (thereby allowing debug traces to link VIF/VC creation with
1022 // the RPC that initiated them).
1023 for idx, got := range traceid {
1024 if !reflect.DeepEqual(got, tid) {
1025 t.Errorf("Test %+v: %d - Got trace id %q, want %q", test.Requirements, idx, hex.EncodeToString(got[:]), hex.EncodeToString(tid[:]))
1026 }
Asim Shankara94e5072014-08-19 18:18:36 -07001027 }
1028 }
1029}
1030
Ankure49a86a2014-11-11 18:52:43 -08001031func TestRPCClientAuthorization(t *testing.T) {
1032 type v []interface{}
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001033 var (
Asim Shankar8f05c222014-10-06 22:08:19 -07001034 // Principals
Asim Shankar4a698282015-03-21 21:59:18 -07001035 pclient, pserver = testutil.NewPrincipal("client"), testutil.NewPrincipal("server")
1036 pdischarger = testutil.NewPrincipal("discharger")
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001037
Asim Shankar8f05c222014-10-06 22:08:19 -07001038 now = time.Now()
1039
Ankure49a86a2014-11-11 18:52:43 -08001040 serverName = "mountpoint/server"
1041 dischargeServerName = "mountpoint/dischargeserver"
1042
Asim Shankar8f05c222014-10-06 22:08:19 -07001043 // Caveats on blessings to the client: First-party caveats
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001044 cavOnlyEcho = mkCaveat(security.NewMethodCaveat("Echo"))
1045 cavExpired = mkCaveat(security.NewExpiryCaveat(now.Add(-1 * time.Second)))
Asim Shankar8f05c222014-10-06 22:08:19 -07001046 // Caveats on blessings to the client: Third-party caveats
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001047 cavTPValid = mkThirdPartyCaveat(pdischarger.PublicKey(), dischargeServerName, mkCaveat(security.NewExpiryCaveat(now.Add(24*time.Hour))))
1048 cavTPExpired = mkThirdPartyCaveat(pdischarger.PublicKey(), dischargeServerName, mkCaveat(security.NewExpiryCaveat(now.Add(-1*time.Second))))
Asim Shankar8f05c222014-10-06 22:08:19 -07001049
1050 // Client blessings that will be tested.
1051 bServerClientOnlyEcho = bless(pserver, pclient, "onlyecho", cavOnlyEcho)
1052 bServerClientExpired = bless(pserver, pclient, "expired", cavExpired)
1053 bServerClientTPValid = bless(pserver, pclient, "dischargeable_third_party_caveat", cavTPValid)
1054 bServerClientTPExpired = bless(pserver, pclient, "expired_third_party_caveat", cavTPExpired)
1055 bClient = pclient.BlessingStore().Default()
1056 bRandom, _ = pclient.BlessSelf("random")
Ankure49a86a2014-11-11 18:52:43 -08001057
1058 mgr = imanager.InternalNew(naming.FixedRoutingID(0x1111111))
1059 ns = tnaming.NewSimpleNamespace()
1060 tests = []struct {
1061 blessings security.Blessings // Blessings used by the client
1062 name string // object name on which the method is invoked
1063 method string
1064 args v
1065 results v
1066 authorized bool // Whether or not the RPC should be authorized by the server.
1067 }{
1068 // There are three different authorization policies (security.Authorizer implementations)
1069 // used by the server, depending on the suffix (see testServerDisp.Lookup):
1070 // - nilAuth suffix: the default authorization policy (only delegates of or delegators of the server can call RPCs)
Benjamin Prosnitzb60efb92015-03-11 17:47:43 -07001071 // - aclAuth suffix: the AccessList only allows blessings matching the patterns "server" or "client"
Ankure49a86a2014-11-11 18:52:43 -08001072 // - other suffixes: testServerAuthorizer allows any principal to call any method except "Unauthorized"
1073
1074 // Expired blessings should fail nilAuth and aclAuth (which care about names), but should succeed on
1075 // other suffixes (which allow all blessings), unless calling the Unauthorized method.
1076 {bServerClientExpired, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, false},
1077 {bServerClientExpired, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, false},
1078 {bServerClientExpired, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1079 {bServerClientExpired, "mountpoint/server/suffix", "Unauthorized", nil, v{""}, false},
1080
1081 // Same for blessings that should fail to obtain a discharge for the third party caveat.
1082 {bServerClientTPExpired, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, false},
1083 {bServerClientTPExpired, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, false},
1084 {bServerClientTPExpired, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1085 {bServerClientTPExpired, "mountpoint/server/suffix", "Unauthorized", nil, v{""}, false},
1086
1087 // The "server/client" blessing (with MethodCaveat("Echo")) should satisfy all authorization policies
1088 // when "Echo" is called.
1089 {bServerClientOnlyEcho, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, true},
1090 {bServerClientOnlyEcho, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, true},
1091 {bServerClientOnlyEcho, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1092
1093 // The "server/client" blessing (with MethodCaveat("Echo")) should satisfy no authorization policy
1094 // when any other method is invoked, except for the testServerAuthorizer policy (which will
1095 // not recognize the blessing "server/onlyecho", but it would authorize anyone anyway).
1096 {bServerClientOnlyEcho, "mountpoint/server/nilAuth", "Closure", nil, nil, false},
1097 {bServerClientOnlyEcho, "mountpoint/server/aclAuth", "Closure", nil, nil, false},
1098 {bServerClientOnlyEcho, "mountpoint/server/suffix", "Closure", nil, nil, true},
1099
1100 // The "client" blessing doesn't satisfy the default authorization policy, but does satisfy
Benjamin Prosnitzb60efb92015-03-11 17:47:43 -07001101 // the AccessList and the testServerAuthorizer policy.
Ankure49a86a2014-11-11 18:52:43 -08001102 {bClient, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, false},
1103 {bClient, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, true},
1104 {bClient, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1105 {bClient, "mountpoint/server/suffix", "Unauthorized", nil, v{""}, false},
1106
Benjamin Prosnitzb60efb92015-03-11 17:47:43 -07001107 // The "random" blessing does not satisfy either the default policy or the AccessList, but does
Ankure49a86a2014-11-11 18:52:43 -08001108 // satisfy testServerAuthorizer.
1109 {bRandom, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, false},
1110 {bRandom, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, false},
1111 {bRandom, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1112 {bRandom, "mountpoint/server/suffix", "Unauthorized", nil, v{""}, false},
1113
1114 // The "server/dischargeable_third_party_caveat" blessing satisfies all policies.
1115 // (the discharges should be fetched).
1116 {bServerClientTPValid, "mountpoint/server/nilAuth", "Echo", v{"foo"}, v{""}, true},
1117 {bServerClientTPValid, "mountpoint/server/aclAuth", "Echo", v{"foo"}, v{""}, true},
1118 {bServerClientTPValid, "mountpoint/server/suffix", "Echo", v{"foo"}, v{""}, true},
1119 {bServerClientTPValid, "mountpoint/server/suffix", "Unauthorized", nil, v{""}, false},
1120 }
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001121 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001122
1123 ctx, shutdown := initForTest()
1124 defer shutdown()
Ankure49a86a2014-11-11 18:52:43 -08001125 // Start the main server.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001126 _, server := startServer(t, ctx, pserver, mgr, ns, serverName, testServerDisp{&testServer{}})
1127 defer stopServer(t, ctx, server, ns, serverName)
Ankure49a86a2014-11-11 18:52:43 -08001128
1129 // Start the discharge server.
Asim Shankar149b4972015-04-23 13:29:58 -07001130 _, dischargeServer := startServer(t, ctx, pdischarger, mgr, ns, dischargeServerName, testutil.LeafDispatcher(&dischargeServer{}, security.AllowEveryone()))
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001131 defer stopServer(t, ctx, dischargeServer, ns, dischargeServerName)
Ankure49a86a2014-11-11 18:52:43 -08001132
Ankur78b8b2a2015-02-04 20:16:28 -08001133 // The server should recognize the client principal as an authority on "client" and "random" blessings.
Asim Shankar8f05c222014-10-06 22:08:19 -07001134 pserver.AddToRoots(bClient)
1135 pserver.AddToRoots(bRandom)
Ankure49a86a2014-11-11 18:52:43 -08001136 // And the client needs to recognize the server's and discharger's blessings to decide which of its
1137 // own blessings to share.
Asim Shankar8f05c222014-10-06 22:08:19 -07001138 pclient.AddToRoots(pserver.BlessingStore().Default())
Ankuredd74ee2015-03-04 16:38:45 -08001139 pclient.AddToRoots(pdischarger.BlessingStore().Default())
1140 // Set a blessing on the client's blessing store to be presented to the discharge server.
1141 pclient.BlessingStore().Set(pclient.BlessingStore().Default(), "discharger")
Asim Shankar4a698282015-03-21 21:59:18 -07001142 // testutil.NewPrincipal sets up a principal that shares blessings with all servers, undo that.
Asim Shankar2bf7b1e2015-02-27 00:45:12 -08001143 pclient.BlessingStore().Set(security.Blessings{}, security.AllPrincipals)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001144
Ankuredd74ee2015-03-04 16:38:45 -08001145 for i, test := range tests {
1146 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 -07001147 client, err := InternalNewClient(mgr, ns)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001148 if err != nil {
1149 t.Fatalf("InternalNewClient failed: %v", err)
1150 }
1151 defer client.Close()
Ankure49a86a2014-11-11 18:52:43 -08001152
Asim Shankar8f05c222014-10-06 22:08:19 -07001153 pclient.BlessingStore().Set(test.blessings, "server")
Todd Wangad492042015-04-17 15:58:40 -07001154 ctx, _ := v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001155 err = client.Call(ctx, test.name, test.method, test.args, makeResultPtrs(test.results))
Asim Shankar8f05c222014-10-06 22:08:19 -07001156 if err != nil && test.authorized {
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001157 t.Errorf(`%s client.Call got error: "%v", wanted the RPC to succeed`, name, err)
Asim Shankar8f05c222014-10-06 22:08:19 -07001158 } else if err == nil && !test.authorized {
1159 t.Errorf("%s call.Finish succeeded, expected authorization failure", name)
Todd Wang8fa38762015-03-25 14:04:59 -07001160 } else if !test.authorized && verror.ErrorID(err) != verror.ErrNoAccess.ID {
Jiri Simsa074bf362015-02-17 09:29:45 -08001161 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 -07001162 }
1163 }
1164}
1165
Asim Shankar263c73b2015-03-19 18:31:26 -07001166// singleBlessingStore implements security.BlessingStore. It is a
Ankurb905dae2015-03-04 12:38:20 -08001167// BlessingStore that marks the last blessing that was set on it as
1168// shareable with any peer. It does not care about the public key that
1169// blessing being set is bound to.
Asim Shankar263c73b2015-03-19 18:31:26 -07001170type singleBlessingStore struct {
Ankurb905dae2015-03-04 12:38:20 -08001171 b security.Blessings
1172}
1173
Asim Shankar263c73b2015-03-19 18:31:26 -07001174func (s *singleBlessingStore) Set(b security.Blessings, _ security.BlessingPattern) (security.Blessings, error) {
Ankurb905dae2015-03-04 12:38:20 -08001175 s.b = b
1176 return security.Blessings{}, nil
1177}
Asim Shankar263c73b2015-03-19 18:31:26 -07001178func (s *singleBlessingStore) ForPeer(...string) security.Blessings {
Ankurb905dae2015-03-04 12:38:20 -08001179 return s.b
1180}
Asim Shankar263c73b2015-03-19 18:31:26 -07001181func (*singleBlessingStore) SetDefault(b security.Blessings) error {
Ankurb905dae2015-03-04 12:38:20 -08001182 return nil
1183}
Asim Shankar263c73b2015-03-19 18:31:26 -07001184func (*singleBlessingStore) Default() security.Blessings {
Ankurb905dae2015-03-04 12:38:20 -08001185 return security.Blessings{}
1186}
Asim Shankar263c73b2015-03-19 18:31:26 -07001187func (*singleBlessingStore) PublicKey() security.PublicKey {
Ankurb905dae2015-03-04 12:38:20 -08001188 return nil
1189}
Asim Shankar263c73b2015-03-19 18:31:26 -07001190func (*singleBlessingStore) DebugString() string {
Ankurb905dae2015-03-04 12:38:20 -08001191 return ""
1192}
Asim Shankar263c73b2015-03-19 18:31:26 -07001193func (*singleBlessingStore) PeerBlessings() map[security.BlessingPattern]security.Blessings {
Ankurb905dae2015-03-04 12:38:20 -08001194 return nil
1195}
Suharsh Sivakumard7d4e222015-06-22 11:10:44 -07001196func (*singleBlessingStore) CacheDischarge(security.Discharge, security.Caveat, security.DischargeImpetus) {
1197 return
1198}
1199func (*singleBlessingStore) ClearDischarges(...security.Discharge) {
1200 return
1201}
1202func (*singleBlessingStore) Discharge(security.Caveat, security.DischargeImpetus) security.Discharge {
1203 return security.Discharge{}
1204}
Ankurb905dae2015-03-04 12:38:20 -08001205
Asim Shankar263c73b2015-03-19 18:31:26 -07001206// singleBlessingPrincipal implements security.Principal. It is a wrapper over
Ankurb905dae2015-03-04 12:38:20 -08001207// a security.Principal that intercepts all invocations on the
Asim Shankar263c73b2015-03-19 18:31:26 -07001208// principal's BlessingStore and serves them via a singleBlessingStore.
1209type singleBlessingPrincipal struct {
Ankurb905dae2015-03-04 12:38:20 -08001210 security.Principal
Asim Shankar263c73b2015-03-19 18:31:26 -07001211 b singleBlessingStore
Ankurb905dae2015-03-04 12:38:20 -08001212}
1213
Asim Shankar263c73b2015-03-19 18:31:26 -07001214func (p *singleBlessingPrincipal) BlessingStore() security.BlessingStore {
Ankurb905dae2015-03-04 12:38:20 -08001215 return &p.b
1216}
1217
1218func TestRPCClientBlessingsPublicKey(t *testing.T) {
Asim Shankar263c73b2015-03-19 18:31:26 -07001219 ctx, shutdown := initForTest()
1220 defer shutdown()
Ankurb905dae2015-03-04 12:38:20 -08001221 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001222 pprovider, pserver = testutil.NewPrincipal("root"), testutil.NewPrincipal("server")
1223 pclient = &singleBlessingPrincipal{Principal: testutil.NewPrincipal("client")}
Ankurb905dae2015-03-04 12:38:20 -08001224
1225 bserver = bless(pprovider, pserver, "server")
1226 bclient = bless(pprovider, pclient, "client")
Asim Shankar4a698282015-03-21 21:59:18 -07001227 bvictim = bless(pprovider, testutil.NewPrincipal("victim"), "victim")
Ankurb905dae2015-03-04 12:38:20 -08001228 )
Ankurb905dae2015-03-04 12:38:20 -08001229 // Make the client and server trust blessings from pprovider.
1230 pclient.AddToRoots(pprovider.BlessingStore().Default())
1231 pserver.AddToRoots(pprovider.BlessingStore().Default())
1232
Asim Shankar263c73b2015-03-19 18:31:26 -07001233 // Make the server present bserver to all clients and start the server.
Ankurb905dae2015-03-04 12:38:20 -08001234 pserver.BlessingStore().SetDefault(bserver)
Asim Shankar263c73b2015-03-19 18:31:26 -07001235 b := createBundle(t, ctx, pserver, &testServer{})
1236 defer b.cleanup(t, ctx)
1237
Todd Wangad492042015-04-17 15:58:40 -07001238 ctx, _ = v23.WithPrincipal(ctx, pclient)
Ankurb905dae2015-03-04 12:38:20 -08001239 tests := []struct {
1240 blessings security.Blessings
1241 errID verror.IDAction
1242 err string
1243 }{
1244 {blessings: bclient},
1245 // server disallows clients from authenticating with blessings not bound to
1246 // the client principal's public key
1247 {blessings: bvictim, errID: verror.ErrNoAccess, err: "bound to a different public key"},
Ankurb905dae2015-03-04 12:38:20 -08001248 {blessings: bserver, errID: verror.ErrNoAccess, err: "bound to a different public key"},
1249 }
1250 for i, test := range tests {
1251 name := fmt.Sprintf("%d: Client RPCing with blessings %v", i, test.blessings)
Ankurb905dae2015-03-04 12:38:20 -08001252 pclient.BlessingStore().Set(test.blessings, "root")
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001253 if err := b.client.Call(ctx, "mountpoint/server/suffix", "Closure", nil, nil); !matchesErrorPattern(err, test.errID, test.err) {
1254 t.Errorf("%v: client.Call returned error %v", name, err)
Ankurb905dae2015-03-04 12:38:20 -08001255 continue
1256 }
1257 }
1258}
1259
Ankuredd74ee2015-03-04 16:38:45 -08001260func TestServerLocalBlessings(t *testing.T) {
Asim Shankar263c73b2015-03-19 18:31:26 -07001261 ctx, shutdown := initForTest()
1262 defer shutdown()
Ankuredd74ee2015-03-04 16:38:45 -08001263 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001264 pprovider, pclient, pserver = testutil.NewPrincipal("root"), testutil.NewPrincipal("client"), testutil.NewPrincipal("server")
Ankuredd74ee2015-03-04 16:38:45 -08001265 pdischarger = pprovider
1266
1267 mgr = imanager.InternalNew(naming.FixedRoutingID(0x1111111))
1268 ns = tnaming.NewSimpleNamespace()
1269
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001270 tpCav = mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/dischargeserver", mkCaveat(security.NewExpiryCaveat(time.Now().Add(time.Hour))))
Ankuredd74ee2015-03-04 16:38:45 -08001271
1272 bserver = bless(pprovider, pserver, "server", tpCav)
1273 bclient = bless(pprovider, pclient, "client")
1274 )
Ankuredd74ee2015-03-04 16:38:45 -08001275 // Make the client and server principals trust root certificates from
1276 // pprovider.
1277 pclient.AddToRoots(pprovider.BlessingStore().Default())
1278 pserver.AddToRoots(pprovider.BlessingStore().Default())
1279
1280 // Make the server present bserver to all clients.
1281 pserver.BlessingStore().SetDefault(bserver)
1282
Asim Shankar7171a252015-03-07 14:41:40 -08001283 // Start the server and the discharger.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001284 _, server := startServer(t, ctx, pserver, mgr, ns, "mountpoint/server", testServerDisp{&testServer{}})
1285 defer stopServer(t, ctx, server, ns, "mountpoint/server")
Asim Shankar7171a252015-03-07 14:41:40 -08001286
Asim Shankar149b4972015-04-23 13:29:58 -07001287 _, dischargeServer := startServer(t, ctx, pdischarger, mgr, ns, "mountpoint/dischargeserver", testutil.LeafDispatcher(&dischargeServer{}, security.AllowEveryone()))
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001288 defer stopServer(t, ctx, dischargeServer, ns, "mountpoint/dischargeserver")
Asim Shankar7171a252015-03-07 14:41:40 -08001289
Ankuredd74ee2015-03-04 16:38:45 -08001290 // Make the client present bclient to all servers that are blessed
1291 // by pprovider.
1292 pclient.BlessingStore().Set(bclient, "root")
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001293 client, err := InternalNewClient(mgr, ns)
Ankuredd74ee2015-03-04 16:38:45 -08001294 if err != nil {
1295 t.Fatalf("InternalNewClient failed: %v", err)
1296 }
1297 defer client.Close()
1298
Todd Wangad492042015-04-17 15:58:40 -07001299 ctx, _ = v23.WithPrincipal(ctx, pclient)
Ankuredd74ee2015-03-04 16:38:45 -08001300 var gotServer, gotClient string
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001301 if err := client.Call(ctx, "mountpoint/server/suffix", "EchoBlessings", nil, []interface{}{&gotServer, &gotClient}); err != nil {
Ankuredd74ee2015-03-04 16:38:45 -08001302 t.Fatalf("Finish failed: %v", err)
1303 }
1304 if wantServer, wantClient := "[root/server]", "[root/client]"; gotServer != wantServer || gotClient != wantClient {
1305 t.Fatalf("EchoBlessings: got %v, %v want %v, %v", gotServer, gotClient, wantServer, wantClient)
1306 }
1307}
1308
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001309func TestDischargePurgeFromCache(t *testing.T) {
Asim Shankar263c73b2015-03-19 18:31:26 -07001310 ctx, shutdown := initForTest()
1311 defer shutdown()
1312
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001313 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001314 pserver = testutil.NewPrincipal("server")
Asim Shankar8f05c222014-10-06 22:08:19 -07001315 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 -07001316 pclient = testutil.NewPrincipal("client")
Asim Shankar8f05c222014-10-06 22:08:19 -07001317 // Client is blessed with a third-party caveat. The discharger service issues discharges with a fakeTimeCaveat.
1318 // This blessing is presented to "server".
1319 bclient = bless(pserver, pclient, "client", mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/server/discharger", security.UnconstrainedUse()))
Asim Shankar263c73b2015-03-19 18:31:26 -07001320
1321 b = createBundle(t, ctx, pserver, &testServer{})
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001322 )
Asim Shankar263c73b2015-03-19 18:31:26 -07001323 defer b.cleanup(t, ctx)
Asim Shankar8f05c222014-10-06 22:08:19 -07001324 // Setup the client to recognize the server's blessing and present bclient to it.
1325 pclient.AddToRoots(pserver.BlessingStore().Default())
1326 pclient.BlessingStore().Set(bclient, "server")
1327
Suharsh Sivakumar1b6683e2014-12-30 13:00:38 -08001328 var err error
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001329 if b.client, err = InternalNewClient(b.sm, b.ns); err != nil {
Ankure49a86a2014-11-11 18:52:43 -08001330 t.Fatalf("InternalNewClient failed: %v", err)
1331 }
Todd Wangad492042015-04-17 15:58:40 -07001332 ctx, _ = v23.WithPrincipal(ctx, pclient)
Mike Burrowsdc6b3602015-02-05 15:52:12 -08001333 call := func() error {
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001334 var got string
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001335 if err := b.client.Call(ctx, "mountpoint/server/aclAuth", "Echo", []interface{}{"batman"}, []interface{}{&got}); err != nil {
Asim Shankar263c73b2015-03-19 18:31:26 -07001336 return err
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001337 }
Asim Shankar8f05c222014-10-06 22:08:19 -07001338 if want := `method:"Echo",suffix:"aclAuth",arg:"batman"`; got != want {
Jiri Simsa074bf362015-02-17 09:29:45 -08001339 return verror.Convert(verror.ErrBadArg, nil, fmt.Errorf("Got [%v] want [%v]", got, want))
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001340 }
1341 return nil
1342 }
1343
1344 // First call should succeed
1345 if err := call(); err != nil {
1346 t.Fatal(err)
1347 }
1348 // Advance virtual clock, which will invalidate the discharge
1349 clock.Advance(1)
Jiri Simsa074bf362015-02-17 09:29:45 -08001350 if err, want := call(), "not authorized"; !matchesErrorPattern(err, verror.ErrNoAccess, want) {
Asim Shankar8f05c222014-10-06 22:08:19 -07001351 t.Errorf("Got error [%v] wanted to match pattern %q", err, want)
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001352 }
1353 // But retrying will succeed since the discharge should be purged from cache and refreshed
1354 if err := call(); err != nil {
1355 t.Fatal(err)
1356 }
1357}
1358
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001359type cancelTestServer struct {
1360 started chan struct{}
1361 cancelled chan struct{}
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001362 t *testing.T
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001363}
1364
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001365func newCancelTestServer(t *testing.T) *cancelTestServer {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001366 return &cancelTestServer{
1367 started: make(chan struct{}),
1368 cancelled: make(chan struct{}),
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001369 t: t,
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001370 }
1371}
1372
Todd Wang54feabe2015-04-15 23:38:26 -07001373func (s *cancelTestServer) CancelStreamReader(ctx *context.T, call rpc.StreamServerCall) error {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001374 close(s.started)
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001375 var b []byte
1376 if err := call.Recv(&b); err != io.EOF {
1377 s.t.Errorf("Got error %v, want io.EOF", err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001378 }
Todd Wang54feabe2015-04-15 23:38:26 -07001379 <-ctx.Done()
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001380 close(s.cancelled)
1381 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001382}
1383
1384// CancelStreamIgnorer doesn't read from it's input stream so all it's
Matt Rosencrantz137b8d22014-08-18 09:56:15 -07001385// buffers fill. The intention is to show that call.Done() is closed
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001386// even when the stream is stalled.
Todd Wang54feabe2015-04-15 23:38:26 -07001387func (s *cancelTestServer) CancelStreamIgnorer(ctx *context.T, _ rpc.StreamServerCall) error {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001388 close(s.started)
Todd Wang54feabe2015-04-15 23:38:26 -07001389 <-ctx.Done()
Matt Rosencrantzbae08212014-10-03 08:04:17 -07001390 close(s.cancelled)
1391 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001392}
1393
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001394func waitForCancel(t *testing.T, ts *cancelTestServer, cancel context.CancelFunc) {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001395 <-ts.started
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001396 cancel()
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001397 <-ts.cancelled
1398}
1399
1400// TestCancel tests cancellation while the server is reading from a stream.
1401func TestCancel(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001402 ctx, shutdown := initForTest()
1403 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -07001404 var (
1405 ts = newCancelTestServer(t)
1406 pclient, pserver = newClientServerPrincipals()
1407 b = createBundle(t, ctx, pserver, ts)
1408 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001409 defer b.cleanup(t, ctx)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001410
Todd Wangad492042015-04-17 15:58:40 -07001411 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001412 ctx, cancel := context.WithCancel(ctx)
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001413 _, err := b.client.StartCall(ctx, "mountpoint/server/suffix", "CancelStreamReader", []interface{}{})
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001414 if err != nil {
1415 t.Fatalf("Start call failed: %v", err)
1416 }
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001417 waitForCancel(t, ts, cancel)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001418}
1419
1420// TestCancelWithFullBuffers tests that even if the writer has filled the buffers and
1421// the server is not reading that the cancel message gets through.
1422func TestCancelWithFullBuffers(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001423 ctx, shutdown := initForTest()
1424 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -07001425 var (
1426 ts = newCancelTestServer(t)
1427 pclient, pserver = newClientServerPrincipals()
1428 b = createBundle(t, ctx, pserver, ts)
1429 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001430 defer b.cleanup(t, ctx)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001431
Todd Wangad492042015-04-17 15:58:40 -07001432 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001433 ctx, cancel := context.WithCancel(ctx)
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001434 call, err := b.client.StartCall(ctx, "mountpoint/server/suffix", "CancelStreamIgnorer", []interface{}{})
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001435 if err != nil {
1436 t.Fatalf("Start call failed: %v", err)
1437 }
1438 // Fill up all the write buffers to ensure that cancelling works even when the stream
1439 // is blocked.
1440 call.Send(make([]byte, vc.MaxSharedBytes))
1441 call.Send(make([]byte, vc.DefaultBytesBufferedPerFlow))
1442
Matt Rosencrantz9346b412014-12-18 15:59:19 -08001443 waitForCancel(t, ts, cancel)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001444}
1445
1446type streamRecvInGoroutineServer struct{ c chan error }
1447
Todd Wang54feabe2015-04-15 23:38:26 -07001448func (s *streamRecvInGoroutineServer) RecvInGoroutine(_ *context.T, call rpc.StreamServerCall) error {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001449 // Spawn a goroutine to read streaming data from the client.
1450 go func() {
1451 var i interface{}
1452 for {
1453 err := call.Recv(&i)
1454 if err != nil {
1455 s.c <- err
1456 return
1457 }
1458 }
1459 }()
1460 // Imagine the server did some processing here and now that it is done,
1461 // it does not care to see what else the client has to say.
1462 return nil
1463}
1464
1465func TestStreamReadTerminatedByServer(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001466 ctx, shutdown := initForTest()
1467 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -07001468 var (
1469 pclient, pserver = newClientServerPrincipals()
1470 s = &streamRecvInGoroutineServer{c: make(chan error, 1)}
1471 b = createBundle(t, ctx, pserver, s)
1472 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001473 defer b.cleanup(t, ctx)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001474
Todd Wangad492042015-04-17 15:58:40 -07001475 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001476 call, err := b.client.StartCall(ctx, "mountpoint/server/suffix", "RecvInGoroutine", []interface{}{})
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001477 if err != nil {
1478 t.Fatalf("StartCall failed: %v", err)
1479 }
1480
1481 c := make(chan error, 1)
1482 go func() {
1483 for i := 0; true; i++ {
1484 if err := call.Send(i); err != nil {
1485 c <- err
1486 return
1487 }
1488 }
1489 }()
1490
1491 // The goroutine at the server executing "Recv" should have terminated
1492 // with EOF.
1493 if err := <-s.c; err != io.EOF {
1494 t.Errorf("Got %v at server, want io.EOF", err)
1495 }
1496 // The client Send should have failed since the RPC has been
1497 // terminated.
1498 if err := <-c; err == nil {
1499 t.Errorf("Client Send should fail as the server should have closed the flow")
1500 }
1501}
1502
1503// TestConnectWithIncompatibleServers tests that clients ignore incompatible endpoints.
1504func TestConnectWithIncompatibleServers(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001505 ctx, shutdown := initForTest()
1506 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -07001507 var (
1508 pclient, pserver = newClientServerPrincipals()
1509 b = createBundle(t, ctx, pserver, &testServer{})
1510 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001511 defer b.cleanup(t, ctx)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001512
1513 // Publish some incompatible endpoints.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001514 publisher := publisher.New(ctx, b.ns, publishPeriod)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001515 defer publisher.WaitForStop()
1516 defer publisher.Stop()
Robin Thellend89e95232015-03-24 13:48:48 -07001517 publisher.AddName("incompatible", false, false)
1518 publisher.AddServer("/@2@tcp@localhost:10000@@1000000@2000000@@")
1519 publisher.AddServer("/@2@tcp@localhost:10001@@2000000@3000000@@")
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001520
Todd Wangad492042015-04-17 15:58:40 -07001521 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001522 _, err := b.client.StartCall(ctx, "incompatible/suffix", "Echo", []interface{}{"foo"}, options.NoRetry{})
Todd Wang8fa38762015-03-25 14:04:59 -07001523 if verror.ErrorID(err) != verror.ErrNoServers.ID {
Asim Shankara036a0f2015-05-08 11:22:54 -07001524 t.Errorf("Expected error %v, found: %v", verror.ErrNoServers, err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001525 }
1526
1527 // Now add a server with a compatible endpoint and try again.
Robin Thellend89e95232015-03-24 13:48:48 -07001528 publisher.AddServer("/" + b.ep.String())
1529 publisher.AddName("incompatible", false, false)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001530
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001531 call, err := b.client.StartCall(ctx, "incompatible/suffix", "Echo", []interface{}{"foo"})
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001532 if err != nil {
Asim Shankar3a8a7e22014-05-12 18:01:44 -07001533 t.Fatal(err)
1534 }
1535 var result string
1536 if err = call.Finish(&result); err != nil {
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001537 t.Errorf("Unexpected error finishing call %v", err)
1538 }
Asim Shankar3a8a7e22014-05-12 18:01:44 -07001539 expected := `method:"Echo",suffix:"suffix",arg:"foo"`
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001540 if result != expected {
1541 t.Errorf("Wrong result returned. Got %s, wanted %s", result, expected)
1542 }
1543}
1544
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001545func TestPreferredAddress(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001546 ctx, shutdown := initForTest()
1547 defer shutdown()
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001548 sm := imanager.InternalNew(naming.FixedRoutingID(0x555555555))
1549 defer sm.Shutdown()
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001550 ns := tnaming.NewSimpleNamespace()
James Ring318c3fa2015-06-17 11:27:23 -07001551 pa := netstate.AddressChooserFunc(func(string, []net.Addr) ([]net.Addr, error) {
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -07001552 return []net.Addr{netstate.NewNetAddr("tcp", "1.1.1.1")}, nil
James Ring318c3fa2015-06-17 11:27:23 -07001553 })
Asim Shankar4a698282015-03-21 21:59:18 -07001554 server, err := testInternalNewServer(ctx, sm, ns, testutil.NewPrincipal("server"))
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001555 if err != nil {
1556 t.Errorf("InternalNewServer failed: %v", err)
1557 }
1558 defer server.Stop()
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -08001559
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001560 spec := rpc.ListenSpec{
1561 Addrs: rpc.ListenAddrs{{"tcp", ":0"}},
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -08001562 AddressChooser: pa,
1563 }
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -08001564 eps, err := server.Listen(spec)
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -08001565 if err != nil {
1566 t.Errorf("unexpected error: %s", err)
1567 }
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -08001568 iep := eps[0].(*inaming.Endpoint)
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001569 host, _, err := net.SplitHostPort(iep.Address)
1570 if err != nil {
1571 t.Errorf("unexpected error: %s", err)
1572 }
1573 if got, want := host, "1.1.1.1"; got != want {
1574 t.Errorf("got %q, want %q", got, want)
1575 }
1576 // Won't override the specified address.
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -08001577 eps, err = server.Listen(listenSpec)
1578 iep = eps[0].(*inaming.Endpoint)
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001579 host, _, err = net.SplitHostPort(iep.Address)
1580 if err != nil {
1581 t.Errorf("unexpected error: %s", err)
1582 }
1583 if got, want := host, "127.0.0.1"; got != want {
1584 t.Errorf("got %q, want %q", got, want)
1585 }
1586}
1587
1588func TestPreferredAddressErrors(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001589 ctx, shutdown := initForTest()
1590 defer shutdown()
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001591 sm := imanager.InternalNew(naming.FixedRoutingID(0x555555555))
1592 defer sm.Shutdown()
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001593 ns := tnaming.NewSimpleNamespace()
James Ring318c3fa2015-06-17 11:27:23 -07001594 paerr := netstate.AddressChooserFunc(func(_ string, a []net.Addr) ([]net.Addr, error) {
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001595 return nil, fmt.Errorf("oops")
James Ring318c3fa2015-06-17 11:27:23 -07001596 })
Asim Shankar4a698282015-03-21 21:59:18 -07001597 server, err := testInternalNewServer(ctx, sm, ns, testutil.NewPrincipal("server"))
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001598 if err != nil {
1599 t.Errorf("InternalNewServer failed: %v", err)
1600 }
1601 defer server.Stop()
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001602 spec := rpc.ListenSpec{
1603 Addrs: rpc.ListenAddrs{{"tcp", ":0"}},
Cosmos Nicolaouae8dd212014-12-13 23:43:08 -08001604 AddressChooser: paerr,
1605 }
Cosmos Nicolaou28dabfc2014-12-15 22:51:07 -08001606 eps, err := server.Listen(spec)
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -07001607
1608 if got, want := len(eps), 0; got != want {
1609 t.Errorf("got %q, want %q", got, want)
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001610 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -07001611 status := server.Status()
1612 if got, want := len(status.Errors), 1; got != want {
1613 t.Errorf("got %q, want %q", got, want)
Cosmos Nicolaoud6c3c9c2014-09-30 15:42:53 -07001614 }
Cosmos Nicolaouaa87e292015-04-21 22:15:50 -07001615 if got, want := status.Errors[0].Error(), "oops"; got != want {
1616 t.Errorf("got %q, want %q", got, want)
Cosmos Nicolaoubae615a2014-08-27 23:32:31 -07001617 }
1618}
1619
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001620func TestSecurityNone(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001621 ctx, shutdown := initForTest()
1622 defer shutdown()
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001623 sm := imanager.InternalNew(naming.FixedRoutingID(0x66666666))
1624 defer sm.Shutdown()
1625 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -07001626 server, err := testInternalNewServer(ctx, sm, ns, nil, options.SecurityNone)
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001627 if err != nil {
1628 t.Fatalf("InternalNewServer failed: %v", err)
1629 }
1630 if _, err = server.Listen(listenSpec); err != nil {
1631 t.Fatalf("server.Listen failed: %v", err)
1632 }
1633 disp := &testServerDisp{&testServer{}}
Cosmos Nicolaou92dba582014-11-05 17:24:10 -08001634 if err := server.ServeDispatcher("mp/server", disp); err != nil {
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001635 t.Fatalf("server.Serve failed: %v", err)
1636 }
Suharsh Sivakumarae774a52015-01-09 14:26:32 -08001637 client, err := InternalNewClient(sm, ns)
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001638 if err != nil {
1639 t.Fatalf("InternalNewClient failed: %v", err)
1640 }
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -07001641 // When using SecurityNone, all authorization checks should be skipped, so
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001642 // unauthorized methods should be callable.
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001643 var got string
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001644 if err := client.Call(ctx, "mp/server", "Unauthorized", nil, []interface{}{&got}, options.SecurityNone); err != nil {
1645 t.Fatalf("client.Call failed: %v", err)
Suharsh Sivakumarcd743f72014-10-27 10:03:42 -07001646 }
1647 if want := "UnauthorizedResult"; got != want {
1648 t.Errorf("got (%v), want (%v)", got, want)
1649 }
1650}
1651
Suharsh Sivakumar0ed10c22015-04-06 12:55:55 -07001652func TestNoPrincipal(t *testing.T) {
1653 ctx, shutdown := initForTest()
1654 defer shutdown()
1655 sm := imanager.InternalNew(naming.FixedRoutingID(0x66666666))
1656 defer sm.Shutdown()
1657 ns := tnaming.NewSimpleNamespace()
1658 server, err := testInternalNewServer(ctx, sm, ns, testutil.NewPrincipal("server"))
1659 if err != nil {
1660 t.Fatalf("InternalNewServer failed: %v", err)
1661 }
1662 if _, err = server.Listen(listenSpec); err != nil {
1663 t.Fatalf("server.Listen failed: %v", err)
1664 }
1665 disp := &testServerDisp{&testServer{}}
1666 if err := server.ServeDispatcher("mp/server", disp); err != nil {
1667 t.Fatalf("server.Serve failed: %v", err)
1668 }
1669 client, err := InternalNewClient(sm, ns)
1670 if err != nil {
1671 t.Fatalf("InternalNewClient failed: %v", err)
1672 }
1673
1674 // A call should fail if the principal in the ctx is nil and SecurityNone is not specified.
Todd Wangad492042015-04-17 15:58:40 -07001675 ctx, err = v23.WithPrincipal(ctx, nil)
Suharsh Sivakumar0ed10c22015-04-06 12:55:55 -07001676 if err != nil {
1677 t.Fatalf("failed to set principal: %v", err)
1678 }
1679 _, err = client.StartCall(ctx, "mp/server", "Echo", []interface{}{"foo"})
1680 if err == nil || verror.ErrorID(err) != errNoPrincipal.ID {
1681 t.Fatalf("Expected errNoPrincipal, got %v", err)
1682 }
1683}
1684
Matt Rosencrantz321a51d2014-10-30 10:37:56 -07001685func TestCallWithNilContext(t *testing.T) {
1686 sm := imanager.InternalNew(naming.FixedRoutingID(0x66666666))
1687 defer sm.Shutdown()
1688 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumarae774a52015-01-09 14:26:32 -08001689 client, err := InternalNewClient(sm, ns)
Matt Rosencrantz321a51d2014-10-30 10:37:56 -07001690 if err != nil {
1691 t.Fatalf("InternalNewClient failed: %v", err)
1692 }
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -07001693 call, err := client.StartCall(nil, "foo", "bar", []interface{}{}, options.SecurityNone)
Matt Rosencrantz321a51d2014-10-30 10:37:56 -07001694 if call != nil {
1695 t.Errorf("Expected nil interface got: %#v", call)
1696 }
Todd Wang8fa38762015-03-25 14:04:59 -07001697 if verror.ErrorID(err) != verror.ErrBadArg.ID {
Suharsh Sivakumar0ed10c22015-04-06 12:55:55 -07001698 t.Errorf("Expected a BadArg error, got: %s", err.Error())
Matt Rosencrantz321a51d2014-10-30 10:37:56 -07001699 }
1700}
1701
Asim Shankara5b60b22014-11-06 15:37:07 -08001702func TestServerBlessingsOpt(t *testing.T) {
1703 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001704 pserver = testutil.NewPrincipal("server")
1705 pclient = testutil.NewPrincipal("client")
Asim Shankara5b60b22014-11-06 15:37:07 -08001706 batman, _ = pserver.BlessSelf("batman")
1707 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001708 ctx, shutdown := initForTest()
1709 defer shutdown()
Asim Shankar7171a252015-03-07 14:41:40 -08001710 // Client and server recognize the servers blessings
1711 for _, p := range []security.Principal{pserver, pclient} {
1712 if err := p.AddToRoots(pserver.BlessingStore().Default()); err != nil {
1713 t.Fatal(err)
1714 }
1715 if err := p.AddToRoots(batman); err != nil {
1716 t.Fatal(err)
1717 }
Asim Shankara5b60b22014-11-06 15:37:07 -08001718 }
1719 // Start a server that uses the ServerBlessings option to configure itself
1720 // to act as batman (as opposed to using the default blessing).
1721 ns := tnaming.NewSimpleNamespace()
Asim Shankara5b60b22014-11-06 15:37:07 -08001722
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001723 defer runServer(t, ctx, ns, pserver, "mountpoint/batman", &testServer{}, options.ServerBlessings{batman}).Shutdown()
1724 defer runServer(t, ctx, ns, pserver, "mountpoint/default", &testServer{}).Shutdown()
Asim Shankara5b60b22014-11-06 15:37:07 -08001725
Asim Shankarb547ea92015-02-17 18:49:45 -08001726 // And finally, make an RPC and see that the client sees "batman"
Asim Shankara5b60b22014-11-06 15:37:07 -08001727 runClient := func(server string) ([]string, error) {
1728 smc := imanager.InternalNew(naming.FixedRoutingID(0xc))
1729 defer smc.Shutdown()
1730 client, err := InternalNewClient(
1731 smc,
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001732 ns)
Asim Shankara5b60b22014-11-06 15:37:07 -08001733 if err != nil {
1734 return nil, err
1735 }
1736 defer client.Close()
Todd Wangad492042015-04-17 15:58:40 -07001737 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001738 call, err := client.StartCall(ctx, server, "Closure", nil)
Asim Shankara5b60b22014-11-06 15:37:07 -08001739 if err != nil {
1740 return nil, err
1741 }
1742 blessings, _ := call.RemoteBlessings()
1743 return blessings, nil
1744 }
1745
1746 // When talking to mountpoint/batman, should see "batman"
1747 // When talking to mountpoint/default, should see "server"
1748 if got, err := runClient("mountpoint/batman"); err != nil || len(got) != 1 || got[0] != "batman" {
1749 t.Errorf("Got (%v, %v) wanted 'batman'", got, err)
1750 }
1751 if got, err := runClient("mountpoint/default"); err != nil || len(got) != 1 || got[0] != "server" {
1752 t.Errorf("Got (%v, %v) wanted 'server'", got, err)
1753 }
1754}
1755
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001756func TestNoDischargesOpt(t *testing.T) {
1757 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001758 pdischarger = testutil.NewPrincipal("discharger")
1759 pserver = testutil.NewPrincipal("server")
1760 pclient = testutil.NewPrincipal("client")
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001761 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001762 ctx, shutdown := initForTest()
1763 defer shutdown()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001764 // Make the client recognize all server blessings
1765 if err := pclient.AddToRoots(pserver.BlessingStore().Default()); err != nil {
1766 t.Fatal(err)
1767 }
1768 if err := pclient.AddToRoots(pdischarger.BlessingStore().Default()); err != nil {
1769 t.Fatal(err)
1770 }
1771
1772 // Bless the client with a ThirdPartyCaveat.
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001773 tpcav := mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/discharger", mkCaveat(security.NewExpiryCaveat(time.Now().Add(time.Hour))))
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001774 blessings, err := pserver.Bless(pclient.PublicKey(), pserver.BlessingStore().Default(), "tpcav", tpcav)
1775 if err != nil {
1776 t.Fatalf("failed to create Blessings: %v", err)
1777 }
1778 if _, err = pclient.BlessingStore().Set(blessings, "server"); err != nil {
1779 t.Fatalf("failed to set blessings: %v", err)
1780 }
1781
1782 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001783
1784 // Setup the disharger and test server.
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001785 discharger := &dischargeServer{}
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001786 defer runServer(t, ctx, ns, pdischarger, "mountpoint/discharger", discharger).Shutdown()
1787 defer runServer(t, ctx, ns, pserver, "mountpoint/testServer", &testServer{}).Shutdown()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001788
1789 runClient := func(noDischarges bool) {
1790 rid, err := naming.NewRoutingID()
1791 if err != nil {
1792 t.Fatal(err)
1793 }
1794 smc := imanager.InternalNew(rid)
1795 defer smc.Shutdown()
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001796 client, err := InternalNewClient(smc, ns)
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001797 if err != nil {
1798 t.Fatalf("failed to create client: %v", err)
1799 }
1800 defer client.Close()
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001801 var opts []rpc.CallOpt
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001802 if noDischarges {
Ankur50a5f392015-02-27 18:46:30 -08001803 opts = append(opts, NoDischarges{})
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001804 }
Todd Wangad492042015-04-17 15:58:40 -07001805 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001806 if _, err = client.StartCall(ctx, "mountpoint/testServer", "Closure", nil, opts...); err != nil {
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001807 t.Fatalf("failed to StartCall: %v", err)
1808 }
1809 }
1810
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001811 // Test that when the NoDischarges option is set, dischargeServer does not get called.
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001812 if runClient(true); discharger.called {
1813 t.Errorf("did not expect discharger to be called")
1814 }
1815 discharger.called = false
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001816 // Test that when the Nodischarges option is not set, dischargeServer does get called.
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001817 if runClient(false); !discharger.called {
1818 t.Errorf("expected discharger to be called")
1819 }
1820}
1821
1822func TestNoImplicitDischargeFetching(t *testing.T) {
1823 // This test ensures that discharge clients only fetch discharges for the specified tp caveats and not its own.
1824 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001825 pdischarger1 = testutil.NewPrincipal("discharger1")
1826 pdischarger2 = testutil.NewPrincipal("discharger2")
1827 pdischargeClient = testutil.NewPrincipal("dischargeClient")
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001828 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001829 ctx, shutdown := initForTest()
1830 defer shutdown()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001831 // Bless the client with a ThirdPartyCaveat from discharger1.
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001832 tpcav1 := mkThirdPartyCaveat(pdischarger1.PublicKey(), "mountpoint/discharger1", mkCaveat(security.NewExpiryCaveat(time.Now().Add(time.Hour))))
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001833 blessings, err := pdischarger1.Bless(pdischargeClient.PublicKey(), pdischarger1.BlessingStore().Default(), "tpcav1", tpcav1)
1834 if err != nil {
1835 t.Fatalf("failed to create Blessings: %v", err)
1836 }
1837 if err = pdischargeClient.BlessingStore().SetDefault(blessings); err != nil {
1838 t.Fatalf("failed to set blessings: %v", err)
1839 }
Asim Shankar263c73b2015-03-19 18:31:26 -07001840 // The client will only talk to the discharge services if it recognizes them.
1841 pdischargeClient.AddToRoots(pdischarger1.BlessingStore().Default())
1842 pdischargeClient.AddToRoots(pdischarger2.BlessingStore().Default())
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001843
1844 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001845
1846 // Setup the disharger and test server.
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08001847 discharger1 := &dischargeServer{}
1848 discharger2 := &dischargeServer{}
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001849 defer runServer(t, ctx, ns, pdischarger1, "mountpoint/discharger1", discharger1).Shutdown()
1850 defer runServer(t, ctx, ns, pdischarger2, "mountpoint/discharger2", discharger2).Shutdown()
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001851
1852 rid, err := naming.NewRoutingID()
1853 if err != nil {
1854 t.Fatal(err)
1855 }
1856 sm := imanager.InternalNew(rid)
Suharsh Sivakumar1b6683e2014-12-30 13:00:38 -08001857
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001858 c, err := InternalNewClient(sm, ns)
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001859 if err != nil {
Suharsh Sivakumar1b6683e2014-12-30 13:00:38 -08001860 t.Fatalf("failed to create client: %v", err)
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001861 }
Suharsh Sivakumar1b6683e2014-12-30 13:00:38 -08001862 dc := c.(*client).dc
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001863 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 -08001864 if err != nil {
1865 t.Error(err)
1866 }
Todd Wangad492042015-04-17 15:58:40 -07001867 ctx, _ = v23.WithPrincipal(ctx, pdischargeClient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001868 dc.PrepareDischarges(ctx, []security.Caveat{tpcav2}, security.DischargeImpetus{})
Suharsh Sivakumar11316872014-11-25 15:57:00 -08001869
1870 // Ensure that discharger1 was not called and discharger2 was called.
1871 if discharger1.called {
1872 t.Errorf("discharge for caveat on discharge client should not have been fetched.")
1873 }
1874 if !discharger2.called {
1875 t.Errorf("discharge for caveat passed to PrepareDischarges should have been fetched.")
1876 }
1877}
1878
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001879// TestBlessingsCache tests that the VCCache is used to sucessfully used to cache duplicate
1880// calls blessings.
1881func TestBlessingsCache(t *testing.T) {
1882 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001883 pserver = testutil.NewPrincipal("server")
1884 pclient = testutil.NewPrincipal("client")
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001885 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001886 ctx, shutdown := initForTest()
1887 defer shutdown()
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001888 // Make the client recognize all server blessings
1889 if err := pclient.AddToRoots(pserver.BlessingStore().Default()); err != nil {
1890 t.Fatal(err)
1891 }
1892
1893 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001894
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001895 serverSM := runServer(t, ctx, ns, pserver, "mountpoint/testServer", &testServer{})
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001896 defer serverSM.Shutdown()
Suharsh Sivakumar0902b7f2015-02-27 19:06:41 -08001897 rid := serverSM.RoutingID()
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001898
Todd Wangad492042015-04-17 15:58:40 -07001899 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001900
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001901 newClient := func() rpc.Client {
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001902 rid, err := naming.NewRoutingID()
1903 if err != nil {
1904 t.Fatal(err)
1905 }
1906 smc := imanager.InternalNew(rid)
1907 defer smc.Shutdown()
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001908 client, err := InternalNewClient(smc, ns)
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001909 if err != nil {
1910 t.Fatalf("failed to create client: %v", err)
1911 }
1912 return client
1913 }
1914
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001915 runClient := func(client rpc.Client) {
Suharsh Sivakumar1abd5a82015-04-10 00:24:14 -07001916 if err := client.Call(ctx, "mountpoint/testServer", "Closure", nil, nil); err != nil {
1917 t.Fatalf("failed to Call: %v", err)
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001918 }
1919 }
1920
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07001921 cachePrefix := naming.Join("rpc", "server", "routing-id", rid.String(), "security", "blessings", "cache")
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001922 cacheHits, err := stats.GetStatsObject(naming.Join(cachePrefix, "hits"))
1923 if err != nil {
1924 t.Fatal(err)
1925 }
1926 cacheAttempts, err := stats.GetStatsObject(naming.Join(cachePrefix, "attempts"))
1927 if err != nil {
1928 t.Fatal(err)
1929 }
1930
1931 // Check that the blessings cache is not used on the first call.
1932 clientA := newClient()
1933 runClient(clientA)
1934 if gotAttempts, gotHits := cacheAttempts.Value().(int64), cacheHits.Value().(int64); gotAttempts != 1 || gotHits != 0 {
1935 t.Errorf("got cacheAttempts(%v), cacheHits(%v), expected cacheAttempts(1), cacheHits(0)", gotAttempts, gotHits)
1936 }
1937 // Check that the cache is hit on the second call with the same blessings.
1938 runClient(clientA)
1939 if gotAttempts, gotHits := cacheAttempts.Value().(int64), cacheHits.Value().(int64); gotAttempts != 2 || gotHits != 1 {
1940 t.Errorf("got cacheAttempts(%v), cacheHits(%v), expected cacheAttempts(2), cacheHits(1)", gotAttempts, gotHits)
1941 }
1942 clientA.Close()
1943 // Check that the cache is not used with a different client.
1944 clientB := newClient()
1945 runClient(clientB)
1946 if gotAttempts, gotHits := cacheAttempts.Value().(int64), cacheHits.Value().(int64); gotAttempts != 3 || gotHits != 1 {
1947 t.Errorf("got cacheAttempts(%v), cacheHits(%v), expected cacheAttempts(3), cacheHits(1)", gotAttempts, gotHits)
1948 }
1949 // clientB changes its blessings, the cache should not be used.
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07001950 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 -08001951 if err != nil {
1952 t.Fatalf("failed to create Blessings: %v", err)
1953 }
1954 if _, err = pclient.BlessingStore().Set(blessings, "server"); err != nil {
1955 t.Fatalf("failed to set blessings: %v", err)
1956 }
1957 runClient(clientB)
1958 if gotAttempts, gotHits := cacheAttempts.Value().(int64), cacheHits.Value().(int64); gotAttempts != 4 || gotHits != 1 {
1959 t.Errorf("got cacheAttempts(%v), cacheHits(%v), expected cacheAttempts(4), cacheHits(1)", gotAttempts, gotHits)
1960 }
1961 clientB.Close()
1962}
1963
Asim Shankar7283dd82015-02-03 19:35:58 -08001964var fakeTimeCaveat = security.CaveatDescriptor{
1965 Id: uniqueid.Id{0x18, 0xba, 0x6f, 0x84, 0xd5, 0xec, 0xdb, 0x9b, 0xf2, 0x32, 0x19, 0x5b, 0x53, 0x92, 0x80, 0x0},
1966 ParamType: vdl.TypeOf(int64(0)),
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001967}
Suharsh Sivakumar9d17e4a2015-02-02 22:42:16 -08001968
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001969func TestServerPublicKeyOpt(t *testing.T) {
1970 var (
Asim Shankar4a698282015-03-21 21:59:18 -07001971 pserver = testutil.NewPrincipal("server")
1972 pother = testutil.NewPrincipal("other")
1973 pclient = testutil.NewPrincipal("client")
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001974 )
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001975 ctx, shutdown := initForTest()
1976 defer shutdown()
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001977 ns := tnaming.NewSimpleNamespace()
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001978 mountName := "mountpoint/default"
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001979
1980 // Start a server with pserver.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001981 defer runServer(t, ctx, ns, pserver, mountName, &testServer{}).Shutdown()
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001982
1983 smc := imanager.InternalNew(naming.FixedRoutingID(0xc))
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07001984 client, err := InternalNewClient(smc, ns)
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001985 if err != nil {
1986 t.Fatal(err)
1987 }
1988 defer smc.Shutdown()
1989 defer client.Close()
1990
Todd Wangad492042015-04-17 15:58:40 -07001991 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001992 // The call should succeed when the server presents the same public as the opt...
Asim Shankar263c73b2015-03-19 18:31:26 -07001993 if _, err = client.StartCall(ctx, mountName, "Closure", nil, options.SkipServerEndpointAuthorization{}, options.ServerPublicKey{pserver.PublicKey()}); err != nil {
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001994 t.Errorf("Expected call to succeed but got %v", err)
1995 }
1996 // ...but fail if they differ.
Todd Wang8fa38762015-03-25 14:04:59 -07001997 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 -08001998 t.Errorf("got %v, want %v", verror.ErrorID(err), verror.ErrNotTrusted.ID)
Suharsh Sivakumara8633b02015-02-14 17:08:07 -08001999 }
2000}
2001
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002002type expiryDischarger struct {
2003 called bool
2004}
2005
Todd Wang4264e4b2015-04-16 22:43:40 -07002006func (ed *expiryDischarger) Discharge(ctx *context.T, call rpc.StreamServerCall, cav security.Caveat, _ security.DischargeImpetus) (security.Discharge, error) {
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002007 tp := cav.ThirdPartyDetails()
2008 if tp == nil {
Asim Shankar08642822015-03-02 21:21:09 -08002009 return security.Discharge{}, fmt.Errorf("discharger: %v does not represent a third-party caveat", cav)
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002010 }
Todd Wang4264e4b2015-04-16 22:43:40 -07002011 if err := tp.Dischargeable(ctx, call.Security()); err != nil {
Asim Shankar08642822015-03-02 21:21:09 -08002012 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 -08002013 }
2014 expDur := 10 * time.Millisecond
2015 if ed.called {
2016 expDur = time.Second
2017 }
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07002018 expiry, err := security.NewExpiryCaveat(time.Now().Add(expDur))
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002019 if err != nil {
Asim Shankar08642822015-03-02 21:21:09 -08002020 return security.Discharge{}, fmt.Errorf("failed to create an expiration on the discharge: %v", err)
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002021 }
Todd Wang4264e4b2015-04-16 22:43:40 -07002022 d, err := call.Security().LocalPrincipal().MintDischarge(cav, expiry)
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002023 if err != nil {
Asim Shankar08642822015-03-02 21:21:09 -08002024 return security.Discharge{}, err
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002025 }
2026 ed.called = true
Asim Shankar08642822015-03-02 21:21:09 -08002027 return d, nil
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002028}
2029
2030func TestDischargeClientFetchExpiredDischarges(t *testing.T) {
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07002031 ctx, shutdown := initForTest()
2032 defer shutdown()
Asim Shankar263c73b2015-03-19 18:31:26 -07002033 var (
2034 pclient, pdischarger = newClientServerPrincipals()
Suharsh Sivakumar60b78e92015-04-23 21:36:49 -07002035 tpcav = mkThirdPartyCaveat(pdischarger.PublicKey(), "mountpoint/discharger", mkCaveat(security.NewExpiryCaveat(time.Now().Add(time.Hour))))
Asim Shankar263c73b2015-03-19 18:31:26 -07002036 ns = tnaming.NewSimpleNamespace()
2037 discharger = &expiryDischarger{}
2038 )
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002039
2040 // Setup the disharge server.
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -07002041 defer runServer(t, ctx, ns, pdischarger, "mountpoint/discharger", discharger).Shutdown()
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002042
2043 // Create a discharge client.
2044 rid, err := naming.NewRoutingID()
2045 if err != nil {
2046 t.Fatal(err)
2047 }
2048 smc := imanager.InternalNew(rid)
2049 defer smc.Shutdown()
2050 client, err := InternalNewClient(smc, ns)
2051 if err != nil {
2052 t.Fatalf("failed to create client: %v", err)
2053 }
2054 defer client.Close()
Todd Wangad492042015-04-17 15:58:40 -07002055 ctx, _ = v23.WithPrincipal(ctx, pclient)
Suharsh Sivakumar08918582015-03-03 15:16:36 -08002056 dc := InternalNewDischargeClient(ctx, client, 0)
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002057
2058 // Fetch discharges for tpcav.
Asim Shankar263c73b2015-03-19 18:31:26 -07002059 dis := dc.PrepareDischarges(ctx, []security.Caveat{tpcav}, security.DischargeImpetus{})[0]
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002060 // Check that the discharges is not yet expired, but is expired after 100 milliseconds.
2061 expiry := dis.Expiry()
2062 // The discharge should expire.
2063 select {
2064 case <-time.After(time.Now().Sub(expiry)):
2065 break
2066 case <-time.After(time.Second):
2067 t.Fatalf("discharge didn't expire within a second")
2068 }
2069 // Preparing Discharges again to get fresh discharges.
2070 now := time.Now()
Asim Shankar263c73b2015-03-19 18:31:26 -07002071 dis = dc.PrepareDischarges(ctx, []security.Caveat{tpcav}, security.DischargeImpetus{})[0]
Suharsh Sivakumarcd07e252015-02-28 01:04:26 -08002072 if expiry = dis.Expiry(); expiry.Before(now) {
2073 t.Fatalf("discharge has expired %v, but should be fresh", dis)
2074 }
2075}
2076
Asim Shankar263c73b2015-03-19 18:31:26 -07002077// newClientServerPrincipals creates a pair of principals and sets them up to
2078// recognize each others default blessings.
2079//
2080// If the client does not recognize the blessings presented by the server,
2081// then it will not even send it the request.
2082//
2083// If the server does not recognize the blessings presented by the client,
2084// it is likely to deny access (unless the server authorizes all principals).
2085func newClientServerPrincipals() (client, server security.Principal) {
Asim Shankar4a698282015-03-21 21:59:18 -07002086 client = testutil.NewPrincipal("client")
2087 server = testutil.NewPrincipal("server")
Asim Shankar263c73b2015-03-19 18:31:26 -07002088 client.AddToRoots(server.BlessingStore().Default())
2089 server.AddToRoots(client.BlessingStore().Default())
2090 return
2091}
2092
Suharsh Sivakumard19c95d2015-02-19 14:44:50 -08002093func init() {
Suharsh Sivakumar7e93ce52015-05-07 17:46:13 -07002094 rpc.RegisterUnknownProtocol("wsh", websocket.HybridDial, websocket.HybridResolve, websocket.HybridListener)
Todd Wang4264e4b2015-04-16 22:43:40 -07002095 security.RegisterCaveatValidator(fakeTimeCaveat, func(_ *context.T, _ security.Call, t int64) error {
Suharsh Sivakumar8a0adbb2015-03-06 13:16:34 -08002096 if now := clock.Now(); now > t {
Asim Shankar7283dd82015-02-03 19:35:58 -08002097 return fmt.Errorf("fakeTimeCaveat expired: now=%d > then=%d", now, t)
2098 }
2099 return nil
2100 })
Suharsh Sivakumar9d17e4a2015-02-02 22:42:16 -08002101}