Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 67 additions & 10 deletions examples/grpc_gnmi_client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ package main

import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net"
"path/filepath"
"strings"
"time"

gnmi "github.com/openconfig/gnmi/proto/gnmi"
Expand All @@ -14,13 +17,57 @@ import (
"github.com/universal-tool-calling-protocol/go-utcp/src/repository"

"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)

type UnifiedServer struct {
grpcpb.UnimplementedUTCPServiceServer
gnmi.UnimplementedGNMIServer
}

const (
user = "alice"
pass = "secret"
)

func authFromContext(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return fmt.Errorf("missing metadata")
}
vals := md.Get("authorization")
if len(vals) == 0 {
return fmt.Errorf("unauthorized")
}
parts := strings.SplitN(vals[0], " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Basic") {
return fmt.Errorf("unauthorized")
}
decoded, err := base64.StdEncoding.DecodeString(parts[1])
if err != nil {
return fmt.Errorf("unauthorized")
}
up := strings.SplitN(string(decoded), ":", 2)
if len(up) != 2 || up[0] != user || up[1] != pass {
return fmt.Errorf("unauthorized")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returning a generic fmt.Errorf here causes gRPC to translate the error to status code "Unknown", so the client cannot properly detect an authentication failure. Use status.Error(codes.Unauthenticated, …) instead to return the correct gRPC status code.

Prompt for AI agents
Address the following comment on examples/grpc_gnmi_client/main.go at line 38:

<comment>Returning a generic fmt.Errorf here causes gRPC to translate the error to status code &quot;Unknown&quot;, so the client cannot properly detect an authentication failure. Use status.Error(codes.Unauthenticated, …) instead to return the correct gRPC status code.</comment>

<file context>
@@ -14,18 +14,43 @@ import (
 	&quot;github.com/universal-tool-calling-protocol/go-utcp/src/repository&quot;
 
 	&quot;google.golang.org/grpc&quot;
+	&quot;google.golang.org/grpc/metadata&quot;
 )
 
 type UnifiedServer struct {
 	grpcpb.UnimplementedUTCPServiceServer
 	gnmi.UnimplementedGNMIServer
</file context>

}
return nil
}

func unaryAuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
if err := authFromContext(ctx); err != nil {
return nil, err
}
return handler(ctx, req)
}

func streamAuthInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if err := authFromContext(ss.Context()); err != nil {
return err
}
return handler(srv, ss)
}

func (s *UnifiedServer) Capabilities(ctx context.Context, req *gnmi.CapabilityRequest) (*gnmi.CapabilityResponse, error) {
return &gnmi.CapabilityResponse{}, nil
}
Expand Down Expand Up @@ -65,10 +112,12 @@ func (s *UnifiedServer) CallToolStream(req *grpcpb.ToolCallRequest, stream grpcp

// Create a mock update response
update := map[string]interface{}{
"timestamp": time.Now().UnixNano(),
"path": args["path"],
"value": fmt.Sprintf("mock_value_%d", counter),
"mode": args["mode"],
"timestamp": time.Now().UnixNano(),
"path": args["path"],
"value": fmt.Sprintf("mock_value_%d", counter),
"mode": args["mode"],
"sub_mode": args["sub_mode"],
"sample_interval_ns": args["sample_interval_ns"],
}

updateJson, err := json.Marshal(update)
Expand Down Expand Up @@ -121,8 +170,11 @@ func (s *UnifiedServer) Subscribe(stream gnmi.GNMI_SubscribeServer) error {
Update: &gnmi.Notification{
Timestamp: time.Now().UnixNano(),
Update: []*gnmi.Update{{
Path: &gnmi.Path{Element: []string{"interfaces", "interface", "eth0"}},
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_StringVal{StringVal: state}},
Path: &gnmi.Path{Elem: []*gnmi.PathElem{
{Name: "interfaces"},
{Name: "interface", Key: map[string]string{"name": "eth0"}},
}},
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_StringVal{StringVal: state}},
}},
},
},
Expand Down Expand Up @@ -203,7 +255,10 @@ func startGNMIServer(addr string) *grpc.Server {
if err != nil {
log.Fatalf("listen: %v", err)
}
srv := grpc.NewServer()
srv := grpc.NewServer(
grpc.UnaryInterceptor(unaryAuthInterceptor),
grpc.StreamInterceptor(streamAuthInterceptor),
)
gnmi.RegisterGNMIServer(srv, &UnifiedServer{})
grpcpb.RegisterUTCPServiceServer(srv, &UnifiedServer{})
go srv.Serve(lis)
Expand All @@ -217,7 +272,7 @@ func main() {

ctx := context.Background()
repo := repository.NewInMemoryToolRepository()
cfg := &utcp.UtcpClientConfig{ProvidersFilePath: "provider.json"}
cfg := &utcp.UtcpClientConfig{ProvidersFilePath: filepath.Join("examples", "grpc_gnmi_client", "provider.json")}
client, err := utcp.NewUTCPClient(ctx, cfg, repo, nil)
if err != nil {
log.Fatalf("client error: %v", err)
Expand All @@ -229,8 +284,10 @@ func main() {
}

stream, err := client.CallToolStream(ctx, "gnmi.gnmi_subscribe", map[string]any{
"path": "/interfaces/interface/eth0",
"mode": "STREAM",
"path": "/interfaces/interface[name=eth0]",
"mode": "STREAM",
"sub_mode": "SAMPLE",
"sample_interval_ns": 500000000,
})
if err != nil {
log.Fatalf("call stream: %v", err)
Expand Down
7 changes: 6 additions & 1 deletion examples/grpc_gnmi_client/provider.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
"host": "127.0.0.1",
"port": 9339,
"service_name": "gnmi.gNMI",
"method_name": "Subscribe"
"method_name": "Subscribe",
"auth": {
"auth_type": "basic",
"username": "alice",
"password": "secret"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hard-coded plaintext credential exposes a real-looking password in the repository and risks accidental leakage; replace with a placeholder or environment substitution.

Prompt for AI agents
Address the following comment on examples/grpc_gnmi_client/provider.json at line 13:

<comment>Hard-coded plaintext credential exposes a real-looking password in the repository and risks accidental leakage; replace with a placeholder or environment substitution.</comment>

<file context>
@@ -6,7 +6,12 @@
       &quot;host&quot;: &quot;127.0.0.1&quot;,
       &quot;port&quot;: 9339,
       &quot;service_name&quot;: &quot;gnmi.gNMI&quot;,
-      &quot;method_name&quot;: &quot;Subscribe&quot;
+      &quot;method_name&quot;: &quot;Subscribe&quot;,
+      &quot;auth&quot;: {
+        &quot;auth_type&quot;: &quot;basic&quot;,
+        &quot;username&quot;: &quot;alice&quot;,
+        &quot;password&quot;: &quot;secret&quot;
</file context>
Suggested change
"password": "secret"
"password": "${GNMI_PASSWORD}"

}
}
]
}
76 changes: 67 additions & 9 deletions examples/grpc_gnmi_transport/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,72 @@ package main

import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net"
"strings"
"time"

gnmi "github.com/openconfig/gnmi/proto/gnmi"
auth "github.com/universal-tool-calling-protocol/go-utcp/src/auth"
"github.com/universal-tool-calling-protocol/go-utcp/src/grpcpb"
. "github.com/universal-tool-calling-protocol/go-utcp/src/providers/base"
providers "github.com/universal-tool-calling-protocol/go-utcp/src/providers/grpc"
transports "github.com/universal-tool-calling-protocol/go-utcp/src/transports/grpc"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)

type UnifiedServer struct {
gnmi.UnimplementedGNMIServer
grpcpb.UnimplementedUTCPServiceServer
}

const (
user = "alice"
pass = "secret"
)

func authFromContext(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return fmt.Errorf("missing metadata")
}
vals := md.Get("authorization")
if len(vals) == 0 {
return fmt.Errorf("unauthorized")
}
parts := strings.SplitN(vals[0], " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Basic") {
return fmt.Errorf("unauthorized")
}
decoded, err := base64.StdEncoding.DecodeString(parts[1])
if err != nil {
return fmt.Errorf("unauthorized")
}
up := strings.SplitN(string(decoded), ":", 2)
if len(up) != 2 || up[0] != user || up[1] != pass {
return fmt.Errorf("unauthorized")
}
return nil
}

func unaryAuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
if err := authFromContext(ctx); err != nil {
return nil, err
}
return handler(ctx, req)
}

func streamAuthInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if err := authFromContext(ss.Context()); err != nil {
return err
}
return handler(srv, ss)
}

func (s *UnifiedServer) CallTool(ctx context.Context, req *grpcpb.ToolCallRequest) (*grpcpb.ToolCallResponse, error) {
// Simple implementation - could be expanded based on tool name
return &grpcpb.ToolCallResponse{
Expand Down Expand Up @@ -52,10 +99,12 @@ func (s *UnifiedServer) CallToolStream(req *grpcpb.ToolCallRequest, stream grpcp

// Create a mock update response
update := map[string]interface{}{
"timestamp": time.Now().UnixNano(),
"path": args["path"],
"value": fmt.Sprintf("mock_value_%d", counter),
"mode": args["mode"],
"timestamp": time.Now().UnixNano(),
"path": args["path"],
"value": fmt.Sprintf("mock_value_%d", counter),
"mode": args["mode"],
"sub_mode": args["sub_mode"],
"sample_interval_ns": args["sample_interval_ns"],
}

updateJson, err := json.Marshal(update)
Expand Down Expand Up @@ -97,14 +146,19 @@ func (s *UnifiedServer) GetManual(ctx context.Context, e *grpcpb.Empty) (*grpcpb
}

func (s *UnifiedServer) Subscribe(stream gnmi.GNMI_SubscribeServer) error {
ctx := stream.Context()

if _, err := stream.Recv(); err != nil {
return err
}
resp := &gnmi.SubscribeResponse{
Response: &gnmi.SubscribeResponse_Update{
Update: &gnmi.Notification{Update: []*gnmi.Update{{
Path: &gnmi.Path{Element: []string{"interfaces", "interface", "eth0"}},
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_StringVal{StringVal: "UP"}},
Path: &gnmi.Path{Elem: []*gnmi.PathElem{
{Name: "interfaces"},
{Name: "interface", Key: map[string]string{"name": "eth0"}},
}},
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_StringVal{StringVal: "UP"}},
}}},
},
}
Expand All @@ -116,7 +170,10 @@ func startGNMIServer(addr string) *grpc.Server {
if err != nil {
log.Fatalf("listen: %v", err)
}
srv := grpc.NewServer()
srv := grpc.NewServer(
grpc.UnaryInterceptor(unaryAuthInterceptor),
grpc.StreamInterceptor(streamAuthInterceptor),
)
gnmi.RegisterGNMIServer(srv, &UnifiedServer{})
grpcpb.RegisterUTCPServiceServer(srv, &UnifiedServer{})
go srv.Serve(lis)
Expand All @@ -130,14 +187,15 @@ func main() {

logger := func(format string, args ...interface{}) { log.Printf(format, args...) }
tr := transports.NewGRPCClientTransport(logger)
prov := &providers.GRPCProvider{BaseProvider: BaseProvider{Name: "g", ProviderType: ProviderGRPC}, Host: "127.0.0.1", Port: 9339, ServiceName: "gnmi.gNMI", MethodName: "Subscribe"}
var a auth.Auth = auth.NewBasicAuth(user, pass)
prov := &providers.GRPCProvider{BaseProvider: BaseProvider{Name: "g", ProviderType: ProviderGRPC}, Host: "127.0.0.1", Port: 9339, ServiceName: "gnmi.gNMI", MethodName: "Subscribe", Auth: &a}

ctx := context.Background()
if _, err := tr.RegisterToolProvider(ctx, prov); err != nil {
log.Fatalf("register: %v", err)
}

stream, err := tr.CallToolStream(ctx, "gnmi_subscribe", map[string]any{"path": "/interfaces/interface/eth0", "mode": "STREAM"}, prov)
stream, err := tr.CallToolStream(ctx, "gnmi_subscribe", map[string]any{"path": "/interfaces/interface[name=eth0]", "mode": "STREAM", "sub_mode": "SAMPLE", "sample_interval_ns": 500000000}, prov)
if err != nil {
log.Fatalf("call stream: %v", err)
}
Expand Down
Loading
Loading