// UnaryServerInterceptor is a GRPC interceptor that checks whether the
// request is authorized by the included macaroons.
328117
func (svc *Service) UnaryServerInterceptor(
	permissionMap map[string][]bakery.Op) grpc.UnaryServerInterceptor {

	return func(ctx context.Context, req interface{},
		info *grpc.UnaryServerInfo,
		handler grpc.UnaryHandler) (interface{}, error) {

		if _, ok := permissionMap[info.FullMethod]; !ok {
			return nil, fmt.Errorf("%s: unknown permissions "+
				"required for method", info.FullMethod)
		}

		err := svc.ValidateMacaroon(ctx, permissionMap[info.FullMethod])
		if err != nil {
			return nil, err
		}

		return handler(ctx, req)
	}
}
1298187
func UserAgentUnaryServerInterceptor(clientName, constraintStr string) grpc.UnaryServerInterceptor {
	userAgentEnforcer := newUserAgentEnforcer(clientName, constraintStr)
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		if err := userAgentEnforcer(ctx); err != nil {
			return nil, err
		}
		return handler(ctx, req)
	}
}
1161257
func interceptors() []grpc.ServerOption {
	interceptors := &serverInterceptorBuilder{}

	if *GRPCAuth != "" {
		log.Infof("enabling auth plugin %v", *GRPCAuth)
		pluginInitializer := GetAuthenticator(*GRPCAuth)
		authPluginImpl, err := pluginInitializer()
		if err != nil {
			log.Fatalf("Failed to load auth plugin: %v", err)
		}
		authPlugin = authPluginImpl
		interceptors.Add(authenticatingStreamInterceptor, authenticatingUnaryInterceptor)
	}

	if *grpccommon.EnableGRPCPrometheus {
		interceptors.Add(grpc_prometheus.StreamServerInterceptor, grpc_prometheus.UnaryServerInterceptor)
	}

	trace.AddGrpcServerOptions(interceptors.Add)

	return interceptors.Build()
}
151810
func (s *RemoteEnforcer) InitEnforcer(req rpcwrapper.Request, resp *rpcwrapper.Response) error {

	zap.L().Debug("Configuring remote enforcer")

	if !s.rpcHandle.CheckValidity(&req, s.rpcSecret) {
		resp.Status = fmt.Sprintf("init message authentication failed")
		return fmt.Errorf(resp.Status)
	}

	cmdLock.Lock()
	defer cmdLock.Unlock()

	payload, ok := req.Payload.(rpcwrapper.InitRequestPayload)
	if !ok {
		resp.Status = fmt.Sprintf("invalid request payload")
		return fmt.Errorf(resp.Status)
	}

	if s.supervisor != nil || s.enforcer != nil {
		resp.Status = fmt.Sprintf("remote enforcer is already initialized")
		return fmt.Errorf(resp.Status)
	}

	var err error

	defer func() {
		if err != nil {
			s.cleanup()
		}
	}()

	if err = s.setupEnforcer(&payload); err != nil {
		resp.Status = err.Error()
		return fmt.Errorf(resp.Status)
	}

	if err = s.setupSupervisor(&payload); err != nil {
		resp.Status = err.Error()
		return fmt.Errorf(resp.Status)
	}

	if err = s.enforcer.Run(s.ctx); err != nil {
		resp.Status = err.Error()
		return fmt.Errorf(resp.Status)
	}

	if err = s.statsClient.Run(s.ctx); err != nil {
		resp.Status = err.Error()
		return fmt.Errorf(resp.Status)
	}

	if err = s.supervisor.Run(s.ctx); err != nil {
		resp.Status = err.Error()
		return fmt.Errorf(resp.Status)
	}

	if err = s.debugClient.Run(s.ctx); err != nil {
		resp.Status = "DebugClient" + err.Error()
		return fmt.Errorf(resp.Status)
	}

	resp.Status = ""

	return nil
}
444335
func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor {
	o := evaluateOptions(opts)
	return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
		defer func() {
			if r := recover(); r != nil {
				err = recoverFrom(stream.Context(), r, o.recoveryHandlerFunc)
			}
		}()

		return handler(srv, stream)
	}
}
930204
func (eu ServerErrorUnwrapper) UnwrapError(arg interface{}) (appError error, dispatchError error) {
	s, ok := arg.(*keybase1.Status)
	if !ok {
		return nil, errors.New("Error converting arg to keybase1.Status object in ServerErrorUnwrapper.UnwrapError")
	}

	if s == nil || s.Code == 0 {
		return nil, nil
	}

	switch s.Code {
	case StatusCodeServerError:
		appError = ServerError{errors.New(s.Desc)}
		break
	case StatusCodeServerErrorBadRequest:
		appError = ServerErrorBadRequest{Reason: s.Desc}
		break
	case StatusCodeServerErrorConflictRevision:
		appError = ServerErrorConflictRevision{Desc: s.Desc}
		break
	case StatusCodeServerErrorConflictPrevRoot:
		appError = ServerErrorConflictPrevRoot{Desc: s.Desc}
		break
	case StatusCodeServerErrorConflictDiskUsage:
		appError = ServerErrorConflictDiskUsage{Desc: s.Desc}
		break
	case StatusCodeServerErrorLocked:
		appError = ServerErrorLocked{}
		break
	case StatusCodeServerErrorUnauthorized:
		appError = ServerErrorUnauthorized{}
		break
	case StatusCodeServerErrorThrottle:
		var suggestedRetryIn *time.Duration
		for _, kv := range s.Fields {
			if kv.Key == "suggestedRetryInMS" {
				if ms, err := strconv.Atoi(kv.Value); err != nil {
					d := time.Duration(ms) * time.Millisecond
					suggestedRetryIn = &d
				}
				break
			}
		}
		appError = ServerErrorThrottle{
			Err:              errors.New(s.Desc),
			SuggestedRetryIn: suggestedRetryIn,
		}
		break
	case StatusCodeServerErrorConditionFailed:
		shouldThrottle := false
		for _, kv := range s.Fields {
			if kv.Key == "ShouldThrottle" {
				shouldThrottle, _ = strconv.ParseBool(kv.Value)
				break
			}
		}
		appError = ServerErrorConditionFailed{
			Err:            errors.New(s.Desc),
			ShouldThrottle: shouldThrottle,
		}
		break
	case StatusCodeServerErrorWriteAccess:
		appError = ServerErrorWriteAccess{}
		break
	case StatusCodeServerErrorConflictFolderMapping:
		appError = ServerErrorConflictFolderMapping{Desc: s.Desc}
		break
	case StatusCodeServerErrorTooManyFoldersCreated:
		err := ServerErrorTooManyFoldersCreated{}
		for _, f := range s.Fields {
			switch f.Key {
			case "Limit":
				err.Limit, _ = strconv.ParseUint(f.Value, 10, 64)
			case "Created":
				err.Created, _ = strconv.ParseUint(f.Value, 10, 64)
			}
		}
		appError = err
		break
	case StatusCodeServerErrorCannotReadFinalizedTLF:
		appError = ServerErrorCannotReadFinalizedTLF{}
		break
	case StatusCodeServerErrorLockConflict:
		appError = ServerErrorLockConflict{}
		break
	case StatusCodeServerErrorClassicTLFDoesNotExist:
		appError = ServerErrorClassicTLFDoesNotExist{}
		break
	case StatusCodeServerErrorMissingFolderHandle:
		appError = ServerErrorMissingFolderHandle{}
		break
	default:
		ase := libkb.AppStatusError{
			Code:   s.Code,
			Name:   s.Name,
			Desc:   s.Desc,
			Fields: make(map[string]string),
		}
		for _, f := range s.Fields {
			ase.Fields[f.Key] = f.Value
		}
		appError = ase
	}

	return appError, nil
}
1163553
func (o Middleware) PublisherMsgInterceptor(serviceName string, next pubsub.PublishHandler) pubsub.PublishHandler {
	return func(ctx context.Context, topic string, m *pubsub.Msg) error {
		var user string
		audit, ok := ctx.Value("x-audit-user").(string)
		if ok && audit != "" {
			user = audit
		}

		md, ok := metadata.FromIncomingContext(ctx)
		if ok {
			if len(md["x-audit-user"]) > 0 {
				user = md["x-audit-user"][0]
			}
		}

		m.Metadata["x-audit-user"] = user
		return next(ctx, topic, m)
	}
}
450259
func (o Middleware) SubscribeInterceptor(opts pubsub.HandlerOptions, next pubsub.MsgHandler) pubsub.MsgHandler {
	return func(ctx context.Context, m pubsub.Msg) error {
		var tracer = o.Tracer
		if tracer == nil {
			tracer = opentracing.GlobalTracer()
		}

		spanContext, err := tracer.Extract(
			opentracing.TextMap,
			opentracing.TextMapCarrier(m.Metadata))

		if err != nil && err != opentracing.ErrSpanContextNotFound {
			return next(ctx, m)
		}

		handlerSpan := tracer.StartSpan(
			opts.Name,
			consumerOption{clientContext: spanContext},
			pubsubTag,
		)
		defer handlerSpan.Finish()

		ctx = opentracing.ContextWithSpan(ctx, handlerSpan)
		err = next(ctx, m)

		if err != nil {
			handlerSpan.SetTag("error", "true")
			handlerSpan.SetTag("stack", err.Error())
		}

		return err
	}
}
1201324
func ChainUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor {
	n := len(interceptors)

	if n > 1 {
		lastI := n - 1
		return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
			var (
				chainHandler grpc.UnaryInvoker
				curI         int
			)

			chainHandler = func(currentCtx context.Context, currentMethod string, currentReq, currentRepl interface{}, currentConn *grpc.ClientConn, currentOpts ...grpc.CallOption) error {
				if curI == lastI {
					return invoker(currentCtx, currentMethod, currentReq, currentRepl, currentConn, currentOpts...)
				}
				curI++
				err := interceptors[curI](currentCtx, currentMethod, currentReq, currentRepl, currentConn, chainHandler, currentOpts...)
				curI--
				return err
			}

			return interceptors[0](ctx, method, req, reply, cc, chainHandler, opts...)
		}
	}

	if n == 1 {
		return interceptors[0]
	}

	// n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil.
	return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		return invoker(ctx, method, req, reply, cc, opts...)
	}
}
523343
func (collector *serverInterceptorBuilder) Build() []grpc.ServerOption {
	log.Infof("Building interceptors with %d unary interceptors and %d stream interceptors", len(collector.unaryInterceptors), len(collector.streamInterceptors))
	switch len(collector.unaryInterceptors) + len(collector.streamInterceptors) {
	case 0:
		return []grpc.ServerOption{}
	default:
		return []grpc.ServerOption{
			grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(collector.unaryInterceptors...)),
			grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(collector.streamInterceptors...)),
		}
	}
}
638239
func UnaryServerInterceptor(logger *zap.Logger, opts ...Option) grpc.UnaryServerInterceptor {
	o := evaluateServerOpt(opts)
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		startTime := time.Now()

		newCtx := newLoggerForCall(ctx, logger, info.FullMethod, startTime)

		resp, err := handler(newCtx, req)
		if !o.shouldLog(info.FullMethod, err) {
			return resp, err
		}
		code := o.codeFunc(err)
		level := o.levelFunc(code)

		// re-extract logger from newCtx, as it may have extra fields that changed in the holder.
		ctx_zap.Extract(newCtx).Check(level, "finished unary call with code "+code.String()).Write(
			zap.Error(err),
			zap.String("grpc.code", code.String()),
			o.durationFunc(time.Since(startTime)),
		)

		return resp, err
	}
}
31055
func ContextClientInterceptor() grpc.UnaryClientInterceptor {
	return func(
		ctx context.Context,
		method string,
		req, resp interface{},
		cc *grpc.ClientConn,
		invoker grpc.UnaryInvoker,
		opts ...grpc.CallOption,
	) error {
		pairs := make([]string, 0)

		if md, ok := metadata.FromIncomingContext(ctx); ok {
			for key, values := range md {
				if strings.HasPrefix(strings.ToLower(key), "l5d") {
					for _, value := range values {
						pairs = append(pairs, key, value)
					}
				}

				if strings.HasPrefix(strings.ToLower(key), "x-") {
					for _, value := range values {
						pairs = append(pairs, key, value)
					}
				}
			}
		}

		ctx = metadata.AppendToOutgoingContext(ctx, pairs...)
		return invoker(ctx, method, req, resp, cc, opts...)
	}
}
1149872
func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor {
	o := evaluateOptions(opts)
	return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
		newCtx := newTagsForCtx(stream.Context())
		if o.requestFieldsFunc == nil {
			// Short-circuit, don't do the expensive bit of allocating a wrappedStream.
			wrappedStream := grpc_middleware.WrapServerStream(stream)
			wrappedStream.WrappedContext = newCtx
			return handler(srv, wrappedStream)
		}
		wrapped := &wrappedStream{stream, info, o, newCtx, true}
		err := handler(srv, wrapped)
		return err
	}
}
385130
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor {
	o := evaluateOptions(opts)
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		if o.filterOutFunc != nil && !o.filterOutFunc(ctx, info.FullMethod) {
			return handler(ctx, req)
		}
		newCtx, serverSpan := newServerSpanFromInbound(ctx, o.tracer, info.FullMethod)
		resp, err := handler(newCtx, req)
		finishServerSpan(ctx, serverSpan, err)
		return resp, err
	}
}
749689
func RPCUnmonitor(m *monitor.Monitor) interface{} {
	return func(endpoint string) (bool, error) {
		if i, n := m.NodeByName(endpoint); i != -1 {
			m.Unmonitor(n)
			return true, nil
		}
		return false, errors.New("Cannot find node with that name")
	}
}
293151
func (s *ProxyInfo) initRemoteEnforcer(contextID string) error {

	resp := &rpcwrapper.Response{}

	request := &rpcwrapper.Request{
		Payload: &rpcwrapper.InitRequestPayload{
			FqConfig:               s.filterQueue,
			MutualAuth:             s.mutualAuth,
			Validity:               s.validity,
			ServerID:               s.serverID,
			ExternalIPCacheTimeout: s.ExternalIPCacheTimeout,
			PacketLogs:             s.packetLogs,
			Secrets:                s.Secrets.PublicSecrets(),
			Configuration:          s.cfg,
		},
	}

	return s.rpchdl.RemoteCall(contextID, remoteenforcer.InitEnforcer, request, resp)
}
760610
func (o Middleware) PublisherMsgInterceptor(serviceName string, next pubsub.PublishHandler) pubsub.PublishHandler {
	return func(ctx context.Context, topic string, m *pubsub.Msg) error {
		start := time.Now()
		err := next(ctx, topic, m)
		elapsed := time.Now().Sub(start)

		fields := logrus.Fields{
			"component": "pubsub",
			"topic":     topic,
			"duration":  elapsed,
			"metadata":  m.Metadata,
		}

		if err != nil {
			de, ok := err.(errors.DropboxError)
			if ok {
				fields["err"] = de.GetMessage()
			} else {
				fields["err"] = err
			}
		}

		logrus.WithFields(fields).Debug("Published PubSub Msg")
		return err
	}
}