コード例 #1
0
ファイル: client.go プロジェクト: polvi/rolo
func NewRoloClient(idToken jose.JWT, tls bool, addr, serverHostOverride, trustedCaFile string) (*RoloClient, error) {
	var opts []grpc.DialOption
	creds := grpcoidc.NewOIDCAccess(&idToken)
	opts = append(opts, grpc.WithPerRPCCredentials(creds))
	if tls {
		var sn string
		if serverHostOverride != "" {
			sn = serverHostOverride
		}
		var creds credentials.TransportAuthenticator
		if trustedCaFile != "" {
			var err error
			creds, err = credentials.NewClientTLSFromFile(trustedCaFile, sn)
			if err != nil {
				return nil, err
			}
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
	}
	conn, err := grpc.Dial(addr, opts...)
	if err != nil {
		return nil, err
	}
	return &RoloClient{
		grpcClient: pb.NewRoloClient(conn),
	}, nil
}
コード例 #2
0
func (c *Client) dial(endpoint string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
	opts := c.dialSetupOpts(endpoint, dopts...)
	host := getHost(endpoint)
	if c.Username != "" && c.Password != "" {
		// use dial options without dopts to avoid reusing the client balancer
		auth, err := newAuthenticator(host, c.dialSetupOpts(endpoint))
		if err != nil {
			return nil, err
		}
		defer auth.close()

		resp, err := auth.authenticate(c.ctx, c.Username, c.Password)
		if err != nil {
			return nil, err
		}
		opts = append(opts, grpc.WithPerRPCCredentials(authTokenCredential{token: resp.Token}))
	}

	// add metrics options
	opts = append(opts, grpc.WithUnaryInterceptor(prometheus.UnaryClientInterceptor))
	opts = append(opts, grpc.WithStreamInterceptor(prometheus.StreamClientInterceptor))

	conn, err := grpc.Dial(host, opts...)
	if err != nil {
		return nil, err
	}
	return conn, nil
}
コード例 #3
0
ファイル: grpc.go プロジェクト: albertito/remoteu2f
func GRPCClient(addr, token, caFile string) (*RemoteU2FClient, error) {
	var err error
	var tCreds credentials.TransportCredentials
	if caFile == "" {
		tCreds = credentials.NewClientTLSFromCert(nil, "")
	} else {
		tCreds, err = credentials.NewClientTLSFromFile(caFile, "")
		if err != nil {
			return nil, fmt.Errorf("error reading CA file: %s", err)
		}
	}

	t := oauth2.Token{
		AccessToken: token,
		TokenType:   "Bearer",
	}
	rpcCreds := oauth.NewOauthAccess(&t)

	conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(tCreds),
		grpc.WithPerRPCCredentials(rpcCreds),
		grpc.WithBlock(),
		grpc.WithTimeout(30*time.Second))
	if err != nil {
		return nil, fmt.Errorf("error connecting to server: %s", err)
	}

	c := pb.NewRemoteU2FClient(conn)
	return &RemoteU2FClient{c}, nil
}
コード例 #4
0
ファイル: dial.go プロジェクト: otsimo/watch
// DialGRPC returns a GRPC connection for use communicating with a Google cloud
// service, configured with the given ClientOptions.
func DialGRPC(ctx context.Context, opt ...cloud.ClientOption) (*grpc.ClientConn, error) {
	var o opts.DialOpt
	for _, opt := range opt {
		opt.Resolve(&o)
	}
	if o.HTTPClient != nil {
		return nil, errors.New("unsupported HTTP base transport specified")
	}
	if o.GRPCClient != nil {
		return o.GRPCClient, nil
	}
	if o.TokenSource == nil {
		var err error
		o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
		if err != nil {
			return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
		}
	}
	grpcOpts := []grpc.DialOption{
		grpc.WithPerRPCCredentials(oauth.TokenSource{o.TokenSource}),
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
	}
	grpcOpts = append(grpcOpts, o.GRPCDialOpts...)
	if o.UserAgent != "" {
		grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
	}
	return grpc.Dial(o.Endpoint, grpcOpts...)
}
コード例 #5
0
ファイル: dial.go プロジェクト: Ropes/pubbing
// DialGRPC returns a GRPC connection for use communicating with a Google cloud
// service, configured with the given ClientOptions.
func DialGRPC(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {
	var o internal.DialSettings
	for _, opt := range opts {
		opt.Apply(&o)
	}
	if o.HTTPClient != nil {
		return nil, errors.New("unsupported HTTP client specified")
	}
	if o.GRPCConn != nil {
		return o.GRPCConn, nil
	}
	if o.TokenSource == nil {
		var err error
		o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
		if err != nil {
			return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
		}
	}
	grpcOpts := []grpc.DialOption{
		grpc.WithPerRPCCredentials(oauth.TokenSource{o.TokenSource}),
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
	}
	if appengineDialerHook != nil {
		// Use the Socket API on App Engine.
		grpcOpts = append(grpcOpts, appengineDialerHook(ctx))
	}
	grpcOpts = append(grpcOpts, o.GRPCDialOpts...)
	if o.UserAgent != "" {
		grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
	}
	return grpc.Dial(o.Endpoint, grpcOpts...)
}
コード例 #6
0
ファイル: end2end_test.go プロジェクト: johnmccawley/origin
func TestCredentialsMisuse(t *testing.T) {
	creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com")
	if err != nil {
		t.Fatalf("Failed to create credentials %v", err)
	}
	// Two conflicting credential configurations
	if _, err := grpc.Dial("Non-Existent.Server:80", grpc.WithTransportCredentials(creds), grpc.WithTimeout(time.Millisecond), grpc.WithBlock(), grpc.WithInsecure()); err != grpc.ErrCredentialsMisuse {
		t.Fatalf("grpc.Dial(_, _) = _, %v, want _, %v", err, grpc.ErrCredentialsMisuse)
	}
	// security info on insecure connection
	if _, err := grpc.Dial("Non-Existent.Server:80", grpc.WithPerRPCCredentials(creds), grpc.WithTimeout(time.Millisecond), grpc.WithBlock(), grpc.WithInsecure()); err != grpc.ErrCredentialsMisuse {
		t.Fatalf("grpc.Dial(_, _) = _, %v, want _, %v", err, grpc.ErrCredentialsMisuse)
	}
}
コード例 #7
0
func main() {
	var (
		caCert     = flag.String("ca-cert", withConfigDir("ca.pem"), "Trusted CA certificate.")
		serverAddr = flag.String("server-addr", "127.0.0.1:7900", "Hello service address.")
		tlsCert    = flag.String("tls-cert", withConfigDir("cert.pem"), "TLS server certificate.")
		tlsKey     = flag.String("tls-key", withConfigDir("key.pem"), "TLS server key.")
		token      = flag.String("token", withConfigDir(".token"), "Path to JWT auth token.")
	)
	flag.Parse()

	cert, err := tls.LoadX509KeyPair(*tlsCert, *tlsKey)
	if err != nil {
		log.Fatal(err)
	}

	rawCACert, err := ioutil.ReadFile(*caCert)
	if err != nil {
		log.Fatal(err)
	}
	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM(rawCACert)

	creds := credentials.NewTLS(&tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      caCertPool,
	})

	jwtCreds, err := jwt.NewFromTokenFile(*token)
	if err != nil {
		log.Fatal(err)
	}

	conn, err := grpc.Dial(*serverAddr,
		grpc.WithTransportCredentials(creds),
		grpc.WithPerRPCCredentials(jwtCreds))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	c := pb.NewHelloClient(conn)
	message, err := c.Say(context.Background(), &pb.Request{"Kelsey"})
	if err != nil {
		log.Fatal(err)
	}

	log.Println(message.Message)
}
コード例 #8
0
ファイル: client.go プロジェクト: DanielKrawisz/bmagent
// NewClient creates a new RPC connection to bmd.
func NewClient(cfg *ClientConfig, msg, broadcast, getpubkey func(counter uint64, msg []byte)) (*Client, error) {

	opts := []grpc.DialOption{
		grpc.WithPerRPCCredentials(
			pb.NewBasicAuthCredentials(cfg.Username, cfg.Password)),
		grpc.WithTimeout(cfg.Timeout)}

	if !cfg.DisableTLS {
		creds, err := credentials.NewClientTLSFromFile(cfg.CAFile, "")
		if err != nil {
			return nil, fmt.Errorf("Failed to create TLS credentials %v", err)
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
	}

	conn, err := grpc.Dial(cfg.ConnectTo, opts...)

	if err != nil {
		return nil, fmt.Errorf("Failed to dial: %v", err)
	}
	bmd := pb.NewBmdClient(conn)

	// Verify credentials.
	_, err = bmd.GetIdentity(context.Background(), &pb.GetIdentityRequest{
		Address: "InvalidAddress",
	})
	code := grpc.Code(err)
	if code == codes.Unauthenticated || code == codes.PermissionDenied {
		return nil, errors.New("authentication failure; invalid username/password")
	} else if code != codes.InvalidArgument {
		return nil, fmt.Errorf("Unexpected error verifying credentials: %v", err)
	}

	return &Client{
		bmd:           bmd,
		conn:          conn,
		quit:          make(chan struct{}),
		started:       false,
		msgFunc:       msg,
		broadcastFunc: broadcast,
		getpubkeyFunc: getpubkey,
	}, nil
}
コード例 #9
0
ファイル: grpc.go プロジェクト: otsimo/otsimoctl
func connectRegistry(c *Config) {
	var opts []grpc.DialOption
	jwtCreds := newOauthAccess(c)

	if discoveryServices.UseTls {
		auth := credentials.NewClientTLSFromCert(nil, getServerName(discoveryServices.RegistryGrpc))
		opts = append(opts, grpc.WithTransportCredentials(auth))
	} else {
		jwtCreds.RequireTLS = false
		opts = append(opts, grpc.WithInsecure())
	}
	opts = append(opts, grpc.WithPerRPCCredentials(&jwtCreds))

	registryConn, err := grpc.Dial(discoveryServices.RegistryGrpc, opts...)
	if err != nil {
		logrus.Fatalf("grpc.go: Error while connection to registry service %v\n", err)
	}
	registryClient = pb.NewRegistryServiceClient(registryConn)
}
コード例 #10
0
ファイル: dial.go プロジェクト: vburenin/firempq
func DialGRPC(ctx context.Context, opts ...ClientOption) (*grpc.ClientConn, error) {
	settings := &ClientSettings{}
	clientOptions(opts).Resolve(settings)

	if settings.Connection != nil {
		return settings.Connection, nil
	}
	var dialOpts = settings.DialOptions
	if len(dialOpts) == 0 {
		tokenSource, err := google.DefaultTokenSource(ctx, settings.Scopes...)
		if err != nil {
			return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
		}
		dialOpts = []grpc.DialOption{
			grpc.WithPerRPCCredentials(oauth.TokenSource{TokenSource: tokenSource}),
			grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		}
	}
	return grpc.Dial(settings.Endpoint, dialOpts...)
}
コード例 #11
0
ファイル: main.go プロジェクト: otsimo/listener
func connect() {
	var opts []grpc.DialOption
	jwtCreds := NewOauthAccess(config())
	if len(cafile) > 0 {
		auth, err := credentials.NewClientTLSFromFile(cafile, "")
		if err != nil {
			panic(err)
		} else {
			opts = append(opts, grpc.WithTransportCredentials(auth))
		}
	} else {
		jwtCreds.RequireTLS = false
		opts = append(opts, grpc.WithInsecure())
	}
	opts = append(opts, grpc.WithPerRPCCredentials(&jwtCreds))
	conn, err := grpc.Dial(remoteUrl, opts...)

	if err != nil {
		log.Fatalf("main.go: Error while connection to catalog service %v\n", err)
	}
	client = apipb.NewListenerServiceClient(conn)
}
コード例 #12
0
ファイル: accounts.go プロジェクト: otsimo/accounts
func (c *OtsimoAccounts) ConnectToServices(dexServiceUrl, apiServiceUrl string) {
	jwtCreds := NewOauthAccess(c.tm)

	var opts []grpc.DialOption
	if c.roots != nil {
		opts = append(opts, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(c.roots, "")))
	} else {
		jwtCreds.RequireTLS = false
		opts = append(opts, grpc.WithInsecure())
	}
	opts = append(opts, grpc.WithPerRPCCredentials(&jwtCreds))
	conn, err := grpc.Dial(dexServiceUrl, opts...)
	if err != nil {
		log.Fatalf("Error while connection to dex service %v\n", err)
	}
	c.Dex = pb.NewDexServiceClient(conn)

	apiConn, err := grpc.Dial(apiServiceUrl, opts...)
	if err != nil {
		log.Fatalf("Error while connection to api service %v\n", err)
	}
	c.Api = apipb.NewApiServiceClient(apiConn)
}
コード例 #13
0
ファイル: option.go プロジェクト: rizzles/convert
// DialGRPC returns a GRPC connection for use communicating with a Google cloud
// service, configured with the given ClientOptions. Most developers should
// call the relevant NewClient method for the target service rather than
// invoking DialGRPC directly.
func DialGRPC(ctx context.Context, opt ...ClientOption) (*grpc.ClientConn, error) {
	var o dialOpt
	for _, opt := range opt {
		opt.resolve(&o)
	}
	if o.httpClient != nil {
		return nil, errors.New("unsupported HTTP base transport specified")
	}
	if o.grpcClient != nil {
		return o.grpcClient, nil
	}
	if o.tokenSource == nil {
		var err error
		o.tokenSource, err = google.DefaultTokenSource(ctx, o.scopes...)
		if err != nil {
			return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
		}
	}
	grpcOpts := []grpc.DialOption{
		grpc.WithPerRPCCredentials(credentials.TokenSource{o.tokenSource}),
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
	}
	return grpc.Dial(o.endpoint, grpcOpts...)
}
コード例 #14
0
ファイル: client.go プロジェクト: gameduell/kythe
func main() {
	flag.Parse()
	serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort))
	var opts []grpc.DialOption
	if *useTLS {
		var sn string
		if *tlsServerName != "" {
			sn = *tlsServerName
		}
		var creds credentials.TransportAuthenticator
		if *caFile != "" {
			var err error
			creds, err = credentials.NewClientTLSFromFile(*caFile, sn)
			if err != nil {
				log.Fatalf("Failed to create TLS credentials %v", err)
			}
		} else {
			creds = credentials.NewClientTLSFromCert(nil, sn)
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
		if *testCase == "compute_engine_creds" {
			opts = append(opts, grpc.WithPerRPCCredentials(credentials.NewComputeEngine()))
		} else if *testCase == "service_account_creds" {
			jwtCreds, err := credentials.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope)
			if err != nil {
				log.Fatalf("Failed to create JWT credentials: %v", err)
			}
			opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
		}
	}
	conn, err := grpc.Dial(serverAddr, opts...)
	if err != nil {
		log.Fatalf("Fail to dial: %v", err)
	}
	defer conn.Close()
	tc := testpb.NewTestServiceClient(conn)
	switch *testCase {
	case "empty_unary":
		doEmptyUnaryCall(tc)
	case "large_unary":
		doLargeUnaryCall(tc)
	case "client_streaming":
		doClientStreaming(tc)
	case "server_streaming":
		doServerStreaming(tc)
	case "ping_pong":
		doPingPong(tc)
	case "compute_engine_creds":
		if !*useTLS {
			log.Fatalf("TLS is not enabled. TLS is required to execute compute_engine_creds test case.")
		}
		doComputeEngineCreds(tc)
	case "service_account_creds":
		if !*useTLS {
			log.Fatalf("TLS is not enabled. TLS is required to execute service_account_creds test case.")
		}
		doServiceAccountCreds(tc)
	default:
		log.Fatal("Unsupported test case: ", *testCase)
	}
}
コード例 #15
0
ファイル: main.go プロジェクト: openconfig/reference
func main() {
	flag.Parse()
	q := ParseQuery(*queryFlag, *delimiter)
	if len(q.Queries) == 0 {
		log.Fatal("--query must be set")
	}
	q.Target = *targetFlag
	if *tlsFlag {
		var sn string
		if *serverHostOverride != "" {
			sn = *serverHostOverride
		} else {
			sn = q.Target
		}
		var creds credentials.TransportCredentials
		if *caFile != "" {
			var err error
			creds, err = credentials.NewClientTLSFromFile(*caFile, sn)
			if err != nil {
				log.Fatalf("Failed to create TLS credentials %v\n", err)
			}
		} else {
			creds = credentials.NewTLS(&tls.Config{
				ServerName:         sn,
				InsecureSkipVerify: true,
			})
		}
		q.DialOptions = append(q.DialOptions, grpc.WithTransportCredentials(creds))
	} else {
		q.DialOptions = append(q.DialOptions, grpc.WithInsecure())
	}
	if *user != "" {
		pc := credential.NewPassCred(*user, *passwd, true)
		q.DialOptions = append(q.DialOptions, grpc.WithPerRPCCredentials(pc))
	}
	if *outfile != "" {
		f, err := os.Create(*outfile)
		var fMu sync.Mutex
		if err != nil {
			log.Fatalf("Failed to open file %s: %s", *outfile, err)
		}
		cfg.Display = func(b []byte) {
			fMu.Lock()
			defer fMu.Unlock()
			n := make([]byte, len(b)+1)
			n[copy(n, b)] = byte('\n')
			f.Write(n)
		}
	}
	switch {
	case q.Update != nil:
		if err := query.Update(context.Background(), q, &cfg); err != nil {
			log.Infof("query.Update failed for query %v %v: %s\n", cfg, q, err)
		}
	case len(q.Queries) > 0 && *subscribe:
		cfg.Once = *subscribeOnce
		if err := query.DisplayStream(context.Background(), q, &cfg); err != nil {
			log.Infof("query.DisplayStream failed for query %v %v: %s\n", cfg, q, err)
		}
	default:
		if err := query.Display(context.Background(), q, &cfg); err != nil {
			log.Infof("query.Display failed for query %v %v: %s\n", cfg, q, err)
		}
	}
}
コード例 #16
0
ファイル: client.go プロジェクト: tamird/grpc-go
func main() {
	flag.Parse()
	serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort))
	var opts []grpc.DialOption
	if *useTLS {
		var sn string
		if *tlsServerName != "" {
			sn = *tlsServerName
		}
		var creds credentials.TransportCredentials
		if *testCA {
			var err error
			creds, err = credentials.NewClientTLSFromFile(testCAFile, sn)
			if err != nil {
				grpclog.Fatalf("Failed to create TLS credentials %v", err)
			}
		} else {
			creds = credentials.NewClientTLSFromCert(nil, sn)
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
		if *testCase == "compute_engine_creds" {
			opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewComputeEngine()))
		} else if *testCase == "service_account_creds" {
			jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope)
			if err != nil {
				grpclog.Fatalf("Failed to create JWT credentials: %v", err)
			}
			opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
		} else if *testCase == "jwt_token_creds" {
			jwtCreds, err := oauth.NewJWTAccessFromFile(*serviceAccountKeyFile)
			if err != nil {
				grpclog.Fatalf("Failed to create JWT credentials: %v", err)
			}
			opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
		} else if *testCase == "oauth2_auth_token" {
			opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewOauthAccess(interop.GetToken(*serviceAccountKeyFile, *oauthScope))))
		}
	} else {
		opts = append(opts, grpc.WithInsecure())
	}
	conn, err := grpc.Dial(serverAddr, opts...)
	if err != nil {
		grpclog.Fatalf("Fail to dial: %v", err)
	}
	defer conn.Close()
	tc := testpb.NewTestServiceClient(conn)
	switch *testCase {
	case "empty_unary":
		interop.DoEmptyUnaryCall(tc)
		grpclog.Println("EmptyUnaryCall done")
	case "large_unary":
		interop.DoLargeUnaryCall(tc)
		grpclog.Println("LargeUnaryCall done")
	case "client_streaming":
		interop.DoClientStreaming(tc)
		grpclog.Println("ClientStreaming done")
	case "server_streaming":
		interop.DoServerStreaming(tc)
		grpclog.Println("ServerStreaming done")
	case "ping_pong":
		interop.DoPingPong(tc)
		grpclog.Println("Pingpong done")
	case "empty_stream":
		interop.DoEmptyStream(tc)
		grpclog.Println("Emptystream done")
	case "timeout_on_sleeping_server":
		interop.DoTimeoutOnSleepingServer(tc)
		grpclog.Println("TimeoutOnSleepingServer done")
	case "compute_engine_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute compute_engine_creds test case.")
		}
		interop.DoComputeEngineCreds(tc, *defaultServiceAccount, *oauthScope)
		grpclog.Println("ComputeEngineCreds done")
	case "service_account_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute service_account_creds test case.")
		}
		interop.DoServiceAccountCreds(tc, *serviceAccountKeyFile, *oauthScope)
		grpclog.Println("ServiceAccountCreds done")
	case "jwt_token_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute jwt_token_creds test case.")
		}
		interop.DoJWTTokenCreds(tc, *serviceAccountKeyFile)
		grpclog.Println("JWTtokenCreds done")
	case "per_rpc_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute per_rpc_creds test case.")
		}
		interop.DoPerRPCCreds(tc, *serviceAccountKeyFile, *oauthScope)
		grpclog.Println("PerRPCCreds done")
	case "oauth2_auth_token":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute oauth2_auth_token test case.")
		}
		interop.DoOauth2TokenCreds(tc, *serviceAccountKeyFile, *oauthScope)
		grpclog.Println("Oauth2TokenCreds done")
	case "cancel_after_begin":
		interop.DoCancelAfterBegin(tc)
		grpclog.Println("CancelAfterBegin done")
	case "cancel_after_first_response":
		interop.DoCancelAfterFirstResponse(tc)
		grpclog.Println("CancelAfterFirstResponse done")
	case "status_code_and_message":
		interop.DoStatusCodeAndMessage(tc)
		grpclog.Println("StatusCodeAndMessage done")
	case "custom_metadata":
		interop.DoCustomMetadata(tc)
		grpclog.Println("CustomMetadata done")
	case "unimplemented_method":
		interop.DoUnimplementedMethod(conn)
		grpclog.Println("UnimplementedMethod done")
	case "unimplemented_service":
		interop.DoUnimplementedService(testpb.NewUnimplementedServiceClient(conn))
		grpclog.Println("UnimplementedService done")
	default:
		grpclog.Fatal("Unsupported test case: ", *testCase)
	}
}
コード例 #17
0
ファイル: client.go プロジェクト: XiangrongFan/etcd
// Dial establishes a connection for a given endpoint using the client's config
func (c *Client) Dial(endpoint string) (*grpc.ClientConn, error) {
	opts := []grpc.DialOption{
		grpc.WithBlock(),
		grpc.WithTimeout(c.cfg.DialTimeout),
	}

	proto := "tcp"
	creds := c.creds
	if url, uerr := url.Parse(endpoint); uerr == nil && strings.Contains(endpoint, "://") {
		switch url.Scheme {
		case "unix":
			proto = "unix"
		case "http":
			creds = nil
		case "https":
			if creds == nil {
				tlsconfig := &tls.Config{InsecureSkipVerify: true}
				emptyCreds := credentials.NewTLS(tlsconfig)
				creds = &emptyCreds
			}
		default:
			return nil, fmt.Errorf("unknown scheme %q for %q", url.Scheme, endpoint)
		}
		// strip scheme:// prefix since grpc dials by host
		endpoint = url.Host
	}
	f := func(a string, t time.Duration) (net.Conn, error) {
		select {
		case <-c.ctx.Done():
			return nil, c.ctx.Err()
		default:
		}
		return net.DialTimeout(proto, a, t)
	}
	opts = append(opts, grpc.WithDialer(f))

	if creds != nil {
		opts = append(opts, grpc.WithTransportCredentials(*creds))
	} else {
		opts = append(opts, grpc.WithInsecure())
	}

	if c.Username != "" && c.Password != "" {
		auth, err := newAuthenticator(endpoint, opts)
		if err != nil {
			return nil, err
		}
		defer auth.close()

		resp, err := auth.authenticate(c.ctx, c.Username, c.Password)
		if err != nil {
			return nil, err
		}

		opts = append(opts, grpc.WithPerRPCCredentials(authTokenCredential{token: resp.Token}))
	}

	conn, err := grpc.Dial(endpoint, opts...)
	if err != nil {
		return nil, err
	}
	return conn, nil
}
コード例 #18
0
		grpc.WithCodec(GRPCCodec),
	}

	grpcEndpoint := GRPCEndpoint(ctx)
	if grpcEndpoint.Scheme == "https" {
		creds := credentials.NewClientTLSFromCert(nil, "")
		if host, _, _ := net.SplitHostPort(grpcEndpoint.Host); host == "localhost" {
			creds = credentials.NewTLS(&tls.Config{InsecureSkipVerify: true})
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
	}

	// Use contextCredentials instead of directly using the cred
	// so that we can use different credentials for the same
	// connection (in the pool).
	opts = append(opts, grpc.WithPerRPCCredentials(contextCredentials{}))

	// Dial timeout is the lesser of the ctx deadline or
	// maxDialTimeout.
	var timeout time.Duration
	if d, ok := ctx.Deadline(); ok && time.Now().Add(maxDialTimeout).After(d) {
		timeout = d.Sub(time.Now())
	} else {
		timeout = maxDialTimeout
	}
	opts = append(opts, grpc.WithTimeout(timeout))

	conn, err := pooledGRPCDial(grpcEndpoint.Host, opts...)
	if err != nil {
		panic(err)
	}
コード例 #19
0
ファイル: init.go プロジェクト: elos/elos
func init() {
	UI = &cli.BasicUi{Writer: os.Stdout, Reader: os.Stdin}

	user, err := user.Current()
	if err != nil {
		UI.Error(err.Error())
		os.Exit(1)
	}

	configPath := path.Join(user.HomeDir, command.ConfigFileName)

	c, err := command.ParseConfigFile(configPath)
	if err != nil {
		UI.Error(err.Error())
		os.Exit(1)
	}

	Configuration = c

	var db olddata.DB
	var databaseError error

	if Configuration.DirectDB {
		if Configuration.DB != "" {
			db, databaseError = models.MongoDB(Configuration.DB)
		} else {
			databaseError = fmt.Errorf("No database listed")
		}
	} else {
		db = &gaia.DB{
			URL:      Configuration.Host,
			Username: Configuration.PublicCredential,
			Password: Configuration.PrivateCredential,
			Client:   new(http.Client),
		}
	}
	conn, err := grpc.Dial(
		"elos.pw:4444",
		grpc.WithPerRPCCredentials(
			auth.RawCredentials(
				Configuration.Credential.Public,
				Configuration.Credential.Private,
			),
		),
		grpc.WithInsecure(),
	)
	if err != nil {
		log.Fatal(err)
	}
	// don't close connection because we'd lose connection should
	// move declaration of dbc higher in scope TODO(nclandolfi)
	dbc := data.NewDBClient(conn)

	Commands = map[string]cli.CommandFactory{
		"habit": func() (cli.Command, error) {
			return &command.HabitCommand{
				UI:     UI,
				UserID: Configuration.UserID,
				DB:     db,
			}, databaseError
		},
		"people": func() (cli.Command, error) {
			return &command.PeopleCommand{
				UI:     UI,
				UserID: Configuration.UserID,
				DB:     db,
			}, databaseError
		},
		"setup": func() (cli.Command, error) {
			return &command.SetupCommand{
				UI:     UI,
				Config: Configuration,
			}, nil
		},
		"tag": func() (cli.Command, error) {
			return &command.TagCommand{
				UI:     UI,
				UserID: Configuration.UserID,
				DB:     db,
			}, databaseError
		},
		"stream": func() (cli.Command, error) {
			return &command.StreamCommand{
				UI:     UI,
				UserID: Configuration.UserID,
				DB:     db,
			}, databaseError
		},
		"todo": func() (cli.Command, error) {
			return &command.TodoCommand{
				UI:     UI,
				UserID: Configuration.Credential.OwnerID,
				DB:     data.DB(dbc),
			}, databaseError
		},
		"cal2": func() (cli.Command, error) {
			return &command.Cal2Command{
				UI:       UI,
				UserID:   Configuration.Credential.OwnerID,
				DBClient: dbc,
			}, nil
		},
		"records": func() (cli.Command, error) {
			return &command.RecordsCommand{
				UI:       UI,
				UserID:   Configuration.Credential.OwnerID,
				DBClient: dbc,
			}, nil
		},
	}
}
コード例 #20
0
ファイル: connect.go プロジェクト: otsimo/integration-tests
func connectClient(connect2registry, connect2catalog, connect2api bool) {

	discovery := os.Getenv("DEX_WORKER_ISSUER")

	cfg, err := oidc.FetchProviderConfig(http.DefaultClient, discovery)
	if err != nil {
		logrus.Fatalln("Unable to fetch provider configs")
	}

	ccfg := oidc.ClientConfig{
		ProviderConfig: cfg,
		Credentials:    cc,
	}

	//logrus.Printf("ccfg.Credentials: %+v",ccfg.Credentials)
	//logrus.Printf("ccfg.ProviderConfig: %+v",ccfg.ProviderConfig)

	myclient, err := oidc.NewClient(ccfg)
	if err != nil {
		logrus.Fatalf("Unable to create Client: %v", err)
	}

	tok, err := myclient.ClientCredsToken([]string{"openid"})
	if err != nil {
		logrus.Printf("Token: %+v ", tok)
		logrus.Errorf("Error: %+v", err)
		logrus.Fatalf("Unable to get token")
	}

	jwtCreds := NewOauthAccess(tok.Encode())
	//logrus.Println("got the jwtCreds")
	claims, err := tok.Claims()
	clientsub, _, _ = claims.StringClaim("sub")
	//logrus.Println("Get the clientsub", clientsub)

	if err != nil {
		logrus.Fatalln("unable to get getClientIdAndEmail", err)
	}

	if len(cafile) > 0 {
		auth, err := credentials.NewClientTLSFromFile(cafile, "")
		if err != nil {
			panic(err)
		} else {
			opts = append(opts, grpc.WithTransportCredentials(auth))
		}
	} else {
		jwtCreds.RequireTLS = false
		opts = append(opts, grpc.WithInsecure())
	}
	opts = append(opts, grpc.WithPerRPCCredentials(&jwtCreds))

	if connect2api {
		apiUrl = os.Getenv("OTSIMO_SERVICES_API_URL")
		if apiUrl == "" {
			panic("OTSIMO_SERVICES_API_URL must set")
		}
		apiConn, _ := grpc.Dial(apiUrl, opts...)
		apiClient = apipb.NewApiServiceClient(apiConn)
		/*
			if err != nil {
				logrus.Println("                   cannot dial                    ")
				logrus.Println(err)
			} else {
				logrus.Println("                   dialed                         ")
			}

			if apiClient == nil {
				logrus.Println("                   apiClient error               ")
			} else {
				logrus.Println("                   apiClient                  ")
			}
		*/
	}
	//------------------------------------------------------------------------------------------------------------------
	if connect2registry {
		registryUrl = os.Getenv("OTSIMOCTL_REGISTRY")
		if registryUrl == "" {
			panic("OTSIMOCTL_REGISTRY must set")
		}

		regConn, _ := grpc.Dial(registryUrl, opts...)
		registryClient = apipb.NewRegistryServiceClient(regConn)
		/*
			if err != nil {
				logrus.Println("                   cannot dial                    ")
				logrus.Println(err)
			} else {
				logrus.Println("                   dialed                         ")
			}

			if registryClient == nil {
				logrus.Println("                   catalogClt error               ")
			} else {
				logrus.Println("                   catalogClient                  ")
			}
		*/
	}
	//------------------------------------------------------------------------------------------------------------------
	if connect2catalog {
		catalogUrl = os.Getenv("OTSIMOCTL_CATALOG")
		if catalogUrl == "" {
			panic("OTSIMOCTL_CATALOG must set")
		}
		catConn, _ := grpc.Dial(catalogUrl, opts...)
		catalogClient = apipb.NewCatalogServiceClient(catConn)
		/*
			if err != nil {
				logrus.Println("                   cannot dial                    ")
				logrus.Println(err)
			} else {
				logrus.Println("                   dialed                         ")
			}

			if catalogClient == nil {
				logrus.Println("                   catalogClt error               ")
			} else {
				logrus.Println("                   catalogClient                  ")
			}
		*/
	}

}
コード例 #21
0
ファイル: client.go プロジェクト: aaijazi/grpc-go
func main() {
	flag.Parse()
	serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort))
	var opts []grpc.DialOption
	if *useTLS {
		var sn string
		if *tlsServerName != "" {
			sn = *tlsServerName
		}
		var creds credentials.TransportAuthenticator
		if *caFile != "" {
			var err error
			creds, err = credentials.NewClientTLSFromFile(*caFile, sn)
			if err != nil {
				grpclog.Fatalf("Failed to create TLS credentials %v", err)
			}
		} else {
			creds = credentials.NewClientTLSFromCert(nil, sn)
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
		if *testCase == "compute_engine_creds" {
			opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewComputeEngine()))
		} else if *testCase == "service_account_creds" {
			jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope)
			if err != nil {
				grpclog.Fatalf("Failed to create JWT credentials: %v", err)
			}
			opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
		} else if *testCase == "jwt_token_creds" {
			jwtCreds, err := oauth.NewJWTAccessFromFile(*serviceAccountKeyFile, "https://"+*serverHost+":"+string(*serverPort)+"/"+"TestService")
			if err != nil {
				grpclog.Fatalf("Failed to create JWT credentials: %v", err)
			}
			opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
		} else if *testCase == "oauth2_auth_token" {
			opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewOauthAccess(getToken())))
		}
	} else {
		opts = append(opts, grpc.WithInsecure())
	}
	conn, err := grpc.Dial(serverAddr, opts...)
	if err != nil {
		grpclog.Fatalf("Fail to dial: %v", err)
	}
	defer conn.Close()
	tc := testpb.NewTestServiceClient(conn)
	switch *testCase {
	case "empty_unary":
		doEmptyUnaryCall(tc)
	case "large_unary":
		doLargeUnaryCall(tc)
	case "client_streaming":
		doClientStreaming(tc)
	case "server_streaming":
		doServerStreaming(tc)
	case "ping_pong":
		doPingPong(tc)
	case "empty_stream":
		doEmptyStream(tc)
	case "timeout_on_sleeping_server":
		doTimeoutOnSleepingServer(tc)
	case "compute_engine_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute compute_engine_creds test case.")
		}
		doComputeEngineCreds(tc)
	case "service_account_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute service_account_creds test case.")
		}
		doServiceAccountCreds(tc)
	case "jwt_token_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute jwt_token_creds test case.")
		}
		doJWTTokenCreds(tc)
	case "per_rpc_creds":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute per_rpc_creds test case.")
		}
		doPerRPCCreds(tc)
	case "oauth2_auth_token":
		if !*useTLS {
			grpclog.Fatalf("TLS is not enabled. TLS is required to execute oauth2_auth_token test case.")
		}
		doOauth2TokenCreds(tc)
	case "cancel_after_begin":
		doCancelAfterBegin(tc)
	case "cancel_after_first_response":
		doCancelAfterFirstResponse(tc)
	default:
		grpclog.Fatal("Unsupported test case: ", *testCase)
	}
}
コード例 #22
0
ファイル: connect.go プロジェクト: otsimo/integration-tests
func connectUser(connect2registry, connect2catalog, connect2api bool) {
	accountsServiceUrl = os.Getenv("OTSIMOCTL_ACCOUNTS")
	if accountsServiceUrl == "" {
		panic("OTSIMOCTL_ACCOUNTS must set")
	}
	resp, err := http.PostForm(accountsServiceUrl+"/login", val)
	if err != nil {
		logrus.Fatalln("error while trying accountsServiceUrl", err)
	}

	dec := json.NewDecoder(resp.Body)
	asd := struct {
		Error        string `json:"error,omitempty"`
		AccessToken  string `json:"access_token,omitempty"`
		TokenType    string `json:"token_type,omitempty"`
		RefreshToken string `json:"refresh_token,omitempty"`
	}{
		AccessToken:  "",
		TokenType:    "",
		RefreshToken: "",
	}
	err = dec.Decode(&asd)
	if err != nil {
		logrus.Fatalln("unable to decode response body", err)
	}

	token := asd.AccessToken
	jwtCreds := NewOauthAccess(token)
	jwtToken, _ := jose.ParseJWT(token)

	usersub, _, err = getUserIdAndEmail(jwtToken)
	if err != nil {
		logrus.Fatalln("unable to get getUserIdAndEmail", err)
	}
	//logrus.Println("Get the usersub", usersub)

	if len(cafile) > 0 {
		auth, err := credentials.NewClientTLSFromFile(cafile, "")
		if err != nil {
			panic(err)
		} else {
			opts = append(opts, grpc.WithTransportCredentials(auth))
		}
	} else {
		jwtCreds.RequireTLS = false
		opts = append(opts, grpc.WithInsecure())
	}
	opts = append(opts, grpc.WithPerRPCCredentials(&jwtCreds))

	//-----------------------------------------------------------------------------------------------------------------
	if connect2registry {
		registryUrl = os.Getenv("OTSIMOCTL_REGISTRY")
		if registryUrl == "" {
			panic("OTSIMOCTL_REGISTRY must set")
		}

		regConn, _ := grpc.Dial(registryUrl, opts...)
		registryClient = apipb.NewRegistryServiceClient(regConn)
		/*
			if err != nil {
				logrus.Println("                   cannot dial                    ")
				logrus.Println(err)
			} else {
				logrus.Println("                   dialed                         ")
			}

			if registryClient == nil {
				logrus.Println("                   catalogClt error               ")
			} else {
				logrus.Println("                   catalogClient                  ")
			}
		*/
	}

	//------------------------------------------------------------------------------------------------------------------
	if connect2catalog {
		catalogUrl = os.Getenv("OTSIMOCTL_CATALOG")
		if catalogUrl == "" {
			panic("OTSIMOCTL_CATALOG must set")
		}
		catConn, _ := grpc.Dial(catalogUrl, opts...)
		catalogClient = apipb.NewCatalogServiceClient(catConn)
		/*
			if err != nil {
				logrus.Println("                   cannot dial                    ")
				logrus.Println(err)
			} else {
				logrus.Println("                   dialed                         ")
			}

			if catalogClient == nil {
				logrus.Println("                   catalogClt error               ")
			} else {
				logrus.Println("                   catalogClient                  ")
			}
		*/
	}

	//-----------------------------------------------------------------------------------------------------------------
	if connect2api {
		apiUrl = os.Getenv("OTSIMO_SERVICES_API_URL")
		if apiUrl == "" {
			panic("OTSIMO_SERVICES_API_URL must set")
		}
		apiConn, _ := grpc.Dial(apiUrl, opts...)
		apiClient = apipb.NewApiServiceClient(apiConn)
		/*
			if err != nil {
				logrus.Println("                   cannot dial                    ")
				logrus.Println(err)
			} else {
				logrus.Println("                   dialed                         ")
			}

			if apiClient == nil {
				logrus.Println("                   apiClient error               ")
			} else {
				logrus.Println("                   apiClient                  ")
			}
		*/
	}
}