Kubernetes Lesson 36 of 70

Lesson 36 of 70 · 8 min read · Updated

Sharing a Gateway Across Namespaces: ReferenceGrant and GRPCRoute for .NET gRPC

PedalShare now has four teams behind one Gateway: stations, rides, pricing and fleet. This last lesson of the series covers two things that come up once several teams share an entry point. First, a team's route sends traffic to another team's Service, which the Gateway API allows only with a ReferenceGrant. Second, the fleet team exposes a .NET gRPC service through the same Gateway with a GRPCRoute.

Technical Requirements

  1. The gateway-lab cluster with NGINX Gateway Fabric 2.8.1, the public Gateway with its https listener and cert-manager wildcard certificate (HTTPS lesson), and the rides and pricing apps
  2. grpcurl 1.9+ (brew install grpcurl)
  3. scripts/port-forward.sh running (NGF on localhost:8080 and localhost:8443) and ca.crt from the HTTPS lesson
  4. Sample repository: Fcakiroglu16/dotnetacademy, branch gateway-api-referencegrant-grpcroute

Core Concepts

Two kinds of cross-namespace trust

The Gateway API uses two different handshakes. Both sides must agree in each case:

ReferenceWho pointsWho agreesHow
Route to GatewayRoute parentRefsGateway ownerallowedRoutes on the listener
Route to a Service in another namespaceRoute backendRefsService ownerReferenceGrant in the Service's namespace
Gateway to a TLS Secret in another namespaceListener certificateRefsSecret ownerReferenceGrant in the Secret's namespace

Without that second handshake, anyone who can create a route could send Gateway traffic to any Service in the cluster.

ReferenceGrant

A ReferenceGrant lives in the namespace of the target. It lists who may refer (from: group, kind, namespace) and what they may refer to (to: group, kind and an optional name). It is one-way and narrow: a grant for pricing-api-v1 does not cover pricing-api-v2, and a grant for HTTPRoutes does not cover GRPCRoutes. Delete the grant, and the reference stops working.

ReferenceGrant reached v1 in Gateway API v1.5.

GRPCRoute

gRPC runs over HTTP/2, and its path is always /<package.Service>/<Method>. A GRPCRoute matches on those names instead of paths:

MatchSupport
Exact with service and methodCore
Exact with method onlyImplementation-specific
RegularExpressionImplementation-specific
headers (gRPC metadata)Core for Exact

To attach a GRPCRoute to an HTTPS listener, the Gateway negotiates HTTP/2 with clients through ALPN. To the Pods, it speaks cleartext HTTP/2 (h2c). The Service port declares this with appProtocol: kubernetes.io/h2c.

Hands-On: Kubernetes Commands

kubectl get referencegrant -A
kubectl get grpcroute -A
kubectl get gateway public -n pedalshare-infra -o jsonpath=\
'{range .status.listeners[*]}{.name}: {.supportedKinds[*].kind}{"\n"}{end}'

NGF's listeners accept both kinds of route:

http: HTTPRoute GRPCRoute
https: HTTPRoute GRPCRoute

grpcurl needs the lab CA and the hostname that the listener and the certificate cover:

alias fleet='grpcurl -cacert ca.crt -authority fleet.pedalshare.local'
fleet localhost:8443 list

Step-by-Step Example

Step 1: A route to another team's Service

The rides app shows a fare next to each ride. Instead of copying the pricing API, the rides team routes /fares on its own hostname to the pricing team's Service:

k8s/07-referencegrant-grpcroute/01-rides-fare-route.yaml

# The rides team shows the fare next to a ride. The backend belongs to the pricing team,
# in another namespace, so this reference needs the pricing team's permission.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: ride-fares
namespace: pedalshare-rides
spec:
parentRefs:
- name: public
namespace: pedalshare-infra
sectionName: http
hostnames:
- rides.pedalshare.local
rules:
- matches:
- path: {type: PathPrefix, value: /fares}
backendRefs:
- name: pricing-api-v1
namespace: pedalshare-pricing
port: 80
$ kubectl apply -f k8s/07-referencegrant-grpcroute/01-rides-fare-route.yaml
$ kubectl get httproute ride-fares -n pedalshare-rides -o jsonpath=\
'{range .status.parents[*].conditions[*]}{.type}={.status} {.reason}: {.message}{"\n"}{end}'
Accepted=True Accepted: The Route is accepted
ResolvedRefs=False RefNotPermitted: spec.rules[0].backendRefs[0].namespace: Forbidden:
Backend ref to Service pedalshare-pricing/pricing-api-v1 not permitted by any ReferenceGrant

$ curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: rides.pedalshare.local' 'localhost:8080/fares/quote?minutes=25'
500

The Gateway accepted the route, because the rides namespace is allowed on the listener. It refused the backend, because the pricing team has not agreed.

Step 2: The pricing team grants access

k8s/07-referencegrant-grpcroute/02-referencegrant.yaml

# Created by the pricing team, in its own namespace: HTTPRoutes from pedalshare-rides
# may send traffic to the pricing-api-v1 Service. Nothing else is allowed.
apiVersion: gateway.networking.k8s.io/v1
kind: ReferenceGrant
metadata:
name: rides-to-pricing
namespace: pedalshare-pricing
spec:
from:
- group: gateway.networking.k8s.io
kind: HTTPRoute
namespace: pedalshare-rides
to:
- group: ""
kind: Service
name: pricing-api-v1
$ kubectl apply -f k8s/07-referencegrant-grpcroute/02-referencegrant.yaml
$ kubectl get httproute ride-fares -n pedalshare-rides -o jsonpath=...
Accepted=True Accepted
ResolvedRefs=True ResolvedRefs

$ curl -s -H 'Host: rides.pedalshare.local' 'localhost:8080/fares/quote?minutes=25'
{"service":"pricing-api","version":"v1","pod":"pricing-api-v1-7f6cd85f4b-s42d6",...}

The grant names one Service. If the rides team points the route at pricing-api-v2, the status goes back to ResolvedRefs=False RefNotPermitted. If the pricing team deletes the grant, the next request returns 500 again. Access is controlled by the team that owns the backend.

Step 3: Deploy the gRPC service

The fleet service is an ASP.NET Core gRPC app with two RPCs, ReportPing and GetBikeStatus, plus server reflection. Kestrel listens with HTTP/2 only, without TLS, because the Gateway terminates TLS:

src/PedalShare.Telemetry/Program.cs

using Microsoft.AspNetCore.Server.Kestrel.Core;
using PedalShare.Telemetry;

var builder = WebApplication.CreateBuilder(args);

// Plain-text HTTP/2 (h2c): the Gateway terminates TLS, the pod speaks cleartext gRPC.
builder.WebHost.ConfigureKestrel(k =>
k.ListenAnyIP(8080, o => o.Protocols = HttpProtocols.Http2));

builder.Services.AddGrpc();
builder.Services.AddGrpcReflection();
builder.Services.AddSingleton<BikeStore>();

var app = builder.Build();
app.MapGrpcService<FleetTelemetryService>();
app.MapGrpcReflectionService();
app.Run();

src/PedalShare.Telemetry/Protos/telemetry.proto

package pedalshare.telemetry.v1;

// Bikes report their battery and position; the fleet team reads a bike's last state.
service FleetTelemetry {
rpc ReportPing (BikePing) returns (PingAck);
rpc GetBikeStatus (BikeStatusRequest) returns (BikeStatus);
}

The Service declares the protocol on its port:

k8s/apps/fleet-telemetry.yaml

apiVersion: v1
kind: Service
metadata:
name: fleet-telemetry
namespace: pedalshare-fleet
spec:
selector: {app: fleet-telemetry}
ports:
- port: 80
targetPort: 8080
appProtocol: kubernetes.io/h2c # the port speaks cleartext HTTP/2 (gRPC without TLS)
kubectl apply -f k8s/apps/fleet-telemetry.yaml

Step 4: The GRPCRoute

The route attaches to the https listener, whose wildcard certificate already covers fleet.pedalshare.local. Each rule lists exact service and method pairs:

k8s/07-referencegrant-grpcroute/03-grpcroute.yaml

# gRPC over the HTTPS listener (TLS + HTTP/2 via ALPN). Rules match gRPC service and method names.
# Core support is an Exact match with both service and method, so every method is listed.
apiVersion: gateway.networking.k8s.io/v1
kind: GRPCRoute
metadata:
name: fleet-telemetry
namespace: pedalshare-fleet
spec:
parentRefs:
- name: public
namespace: pedalshare-infra
sectionName: https
hostnames:
- fleet.pedalshare.local
rules:
# Bikes report pings; the fleet dashboard reads a bike's last state.
- matches:
- method: {service: pedalshare.telemetry.v1.FleetTelemetry, method: ReportPing}
- method: {service: pedalshare.telemetry.v1.FleetTelemetry, method: GetBikeStatus}
backendRefs:
- {name: fleet-telemetry, port: 80}
# Server reflection, so tools like grpcurl can list services without the .proto file.
- matches:
- method: {service: grpc.reflection.v1.ServerReflection, method: ServerReflectionInfo}
- method: {service: grpc.reflection.v1alpha.ServerReflection, method: ServerReflectionInfo}
backendRefs:
- {name: fleet-telemetry, port: 80}
$ kubectl apply -f k8s/07-referencegrant-grpcroute/03-grpcroute.yaml
$ kubectl get grpcroute fleet-telemetry -n pedalshare-fleet -o jsonpath=...
Accepted=True Accepted: The Route is accepted
ResolvedRefs=True ResolvedRefs: All references are resolved

Call it through the Gateway:

$ fleet localhost:8443 list
grpc.reflection.v1.ServerReflection
grpc.reflection.v1alpha.ServerReflection
pedalshare.telemetry.v1.FleetTelemetry

$ fleet -d '{"bike_id":"bike-1207","battery_percent":64,"latitude":41.04,"longitude":29.0}' \
localhost:8443 pedalshare.telemetry.v1.FleetTelemetry/ReportPing
{
"accepted": true,
"handled_by": "fleet-telemetry-b9cd7bb49-dqp4f"
}

$ fleet -d '{"bike_id":"bike-1207"}' localhost:8443 pedalshare.telemetry.v1.FleetTelemetry/GetBikeStatus
{
"bike_id": "bike-1207",
"battery_percent": 64,
"handled_by": "fleet-telemetry-b9cd7bb49-dqp4f"
}

gRPC status codes from the service reach the client unchanged:

$ fleet -d '{"bike_id":"bike-9999"}' localhost:8443 pedalshare.telemetry.v1.FleetTelemetry/GetBikeStatus
ERROR:
Code: NotFound
Message: bike bike-9999 has not reported

$ fleet -d '{"bike_id":"x","battery_percent":140}' localhost:8443 pedalshare.telemetry.v1.FleetTelemetry/ReportPing
ERROR:
Code: InvalidArgument
Message: battery_percent must be 0-100

Step 5: A match that is not portable

The first version of this route matched on the service name only, which looks shorter. NGF 2.8.1 rejects it:

k8s/07-referencegrant-grpcroute/invalid-service-only-match.yaml

# Rejected by NGINX Gateway Fabric 2.8.1: a match with a service but no method is not Core support.
apiVersion: gateway.networking.k8s.io/v1
kind: GRPCRoute
metadata:
name: fleet-telemetry-service-only
namespace: pedalshare-fleet
spec:
parentRefs:
- name: public
namespace: pedalshare-infra
sectionName: https
hostnames:
- fleet-legacy.pedalshare.local
rules:
- matches:
- method: {service: pedalshare.telemetry.v1.FleetTelemetry}
backendRefs:
- {name: fleet-telemetry, port: 80}
$ kubectl apply -f k8s/07-referencegrant-grpcroute/invalid-service-only-match.yaml
$ kubectl get grpcroute fleet-telemetry-service-only -n pedalshare-fleet -o jsonpath=...
Accepted=False UnsupportedValue: All rules are invalid:
spec.rules[0].matches[0].method.method: Required value: method is required

The API server accepts this YAML, but only an exact service and method pair is Core support. Other implementations may accept a service-only match, but a route that relies on it is not portable. List every method instead.

Results

CheckResult
HTTPRoute in pedalshare-rides to a Service in pedalshare-pricing, no grantResolvedRefs=False RefNotPermitted, requests return 500
Same route after the ReferenceGrantResolvedRefs=True, 200 from pricing-api v1
Route pointed at pricing-api-v2 (not in the grant)RefNotPermitted
Grant deletedRequests return 500 again
GRPCRoute on the https listenerAccepted=True, grpcurl list, ReportPing and GetBikeStatus work
gRPC errors (NotFound, InvalidArgument)Reach the client unchanged
Service-only method match on NGF 2.8.1Accepted=False UnsupportedValue

Summary

  1. Routes attach to a Gateway only if the listener's allowedRoutes lets them, and they reach another namespace's Service only if that namespace has a ReferenceGrant. In each case, the owner of the target decides.
  2. A ReferenceGrant is narrow: one direction, specific kinds, and optionally one named object. Deleting it revokes access right away.
  3. GRPCRoute routes on gRPC service and method names. On an HTTPS listener, the Gateway speaks HTTP/2 with clients and h2c with Pods that declare appProtocol: kubernetes.io/h2c.
  4. Use exact service and method pairs for portable GRPCRoutes, and check Accepted after each apply.

This completes the Gateway API series. The PedalShare edge now has two implementations to choose from (NGINX Gateway Fabric and Traefik), HTTP and HTTPS listeners with automatic certificates, header and weight-based routing, and safe sharing between teams. Remove the lab with scripts/cluster-down.sh.