2018-10-03 18:18:55 +00:00
|
|
|
package xds
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"sync/atomic"
|
2019-01-11 15:43:18 +00:00
|
|
|
"time"
|
2018-10-03 18:18:55 +00:00
|
|
|
|
2021-02-26 22:23:15 +00:00
|
|
|
envoy_discovery_v3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
|
2021-10-16 17:02:03 +00:00
|
|
|
middleware "github.com/grpc-ecosystem/go-grpc-middleware"
|
|
|
|
recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
|
2021-02-22 21:00:15 +00:00
|
|
|
|
2021-05-14 18:59:13 +00:00
|
|
|
"github.com/armon/go-metrics"
|
|
|
|
"github.com/armon/go-metrics/prometheus"
|
2020-01-28 23:50:41 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
2020-06-23 20:19:56 +00:00
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/codes"
|
|
|
|
"google.golang.org/grpc/credentials"
|
|
|
|
"google.golang.org/grpc/metadata"
|
|
|
|
"google.golang.org/grpc/status"
|
2020-12-23 17:50:28 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/consul/acl"
|
2021-10-16 17:02:03 +00:00
|
|
|
agentgrpc "github.com/hashicorp/consul/agent/grpc"
|
2020-12-23 17:50:28 +00:00
|
|
|
"github.com/hashicorp/consul/agent/proxycfg"
|
|
|
|
"github.com/hashicorp/consul/agent/structs"
|
|
|
|
"github.com/hashicorp/consul/tlsutil"
|
2018-10-03 18:18:55 +00:00
|
|
|
)
|
|
|
|
|
2021-05-14 18:59:13 +00:00
|
|
|
var StatsGauges = []prometheus.GaugeDefinition{
|
|
|
|
{
|
|
|
|
Name: []string{"xds", "server", "streams"},
|
|
|
|
Help: "Measures the number of active xDS streams handled by the server split by protocol version.",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2018-10-03 18:18:55 +00:00
|
|
|
// ADSStream is a shorter way of referring to this thing...
|
2021-02-26 22:23:15 +00:00
|
|
|
type ADSStream = envoy_discovery_v3.AggregatedDiscoveryService_StreamAggregatedResourcesServer
|
2018-10-03 18:18:55 +00:00
|
|
|
|
|
|
|
const (
|
2021-02-26 22:23:15 +00:00
|
|
|
// Resource types in xDS v3. These are copied from
|
|
|
|
// envoyproxy/go-control-plane/pkg/resource/v3/resource.go since we don't need any of
|
2018-10-03 18:18:55 +00:00
|
|
|
// the rest of that package.
|
2021-02-26 22:23:15 +00:00
|
|
|
apiTypePrefix = "type.googleapis.com/"
|
2018-10-03 18:18:55 +00:00
|
|
|
|
|
|
|
// EndpointType is the TypeURL for Endpoint discovery responses.
|
2021-10-28 01:51:35 +00:00
|
|
|
EndpointType = apiTypePrefix + "envoy.config.endpoint.v3.ClusterLoadAssignment"
|
2018-10-03 18:18:55 +00:00
|
|
|
|
|
|
|
// ClusterType is the TypeURL for Cluster discovery responses.
|
2021-10-28 01:51:35 +00:00
|
|
|
ClusterType = apiTypePrefix + "envoy.config.cluster.v3.Cluster"
|
2018-10-03 18:18:55 +00:00
|
|
|
|
|
|
|
// RouteType is the TypeURL for Route discovery responses.
|
2021-10-28 01:51:35 +00:00
|
|
|
RouteType = apiTypePrefix + "envoy.config.route.v3.RouteConfiguration"
|
2018-10-03 18:18:55 +00:00
|
|
|
|
|
|
|
// ListenerType is the TypeURL for Listener discovery responses.
|
2021-10-28 01:51:35 +00:00
|
|
|
ListenerType = apiTypePrefix + "envoy.config.listener.v3.Listener"
|
2018-10-03 18:18:55 +00:00
|
|
|
|
|
|
|
// PublicListenerName is the name we give the public listener in Envoy config.
|
|
|
|
PublicListenerName = "public_listener"
|
|
|
|
|
2021-04-12 15:35:14 +00:00
|
|
|
// OutboundListenerName is the name we give the outbound Envoy listener when transparent proxy mode is enabled.
|
2021-03-17 19:40:49 +00:00
|
|
|
OutboundListenerName = "outbound_listener"
|
|
|
|
|
2018-10-03 18:18:55 +00:00
|
|
|
// LocalAppClusterName is the name we give the local application "cluster" in
|
2019-04-29 16:27:57 +00:00
|
|
|
// Envoy config. Note that all cluster names may collide with service names
|
|
|
|
// since we want cluster names and service names to match to enable nice
|
|
|
|
// metrics correlation without massaging prefixes on cluster names.
|
|
|
|
//
|
|
|
|
// We should probably make this more unlikely to collide however changing it
|
|
|
|
// potentially breaks upgrade compatibility without restarting all Envoy's as
|
|
|
|
// it will no longer match their existing cluster name. Changing this will
|
|
|
|
// affect metrics output so could break dashboards (for local app traffic).
|
|
|
|
//
|
|
|
|
// We should probably just make it configurable if anyone actually has
|
|
|
|
// services named "local_app" in the future.
|
2018-10-03 18:18:55 +00:00
|
|
|
LocalAppClusterName = "local_app"
|
|
|
|
|
|
|
|
// LocalAgentClusterName is the name we give the local agent "cluster" in
|
2019-04-29 16:27:57 +00:00
|
|
|
// Envoy config. Note that all cluster names may collide with service names
|
|
|
|
// since we want cluster names and service names to match to enable nice
|
|
|
|
// metrics correlation without massaging prefixes on cluster names.
|
|
|
|
//
|
|
|
|
// We should probably make this more unlikely to collied however changing it
|
|
|
|
// potentially breaks upgrade compatibility without restarting all Envoy's as
|
|
|
|
// it will no longer match their existing cluster name. Changing this will
|
|
|
|
// affect metrics output so could break dashboards (for local agent traffic).
|
|
|
|
//
|
|
|
|
// We should probably just make it configurable if anyone actually has
|
|
|
|
// services named "local_agent" in the future.
|
2018-10-03 18:18:55 +00:00
|
|
|
LocalAgentClusterName = "local_agent"
|
2019-01-11 15:43:18 +00:00
|
|
|
|
2021-03-17 19:40:49 +00:00
|
|
|
// OriginalDestinationClusterName is the name we give to the passthrough
|
|
|
|
// cluster which redirects transparently-proxied requests to their original
|
2021-06-09 20:34:17 +00:00
|
|
|
// destination outside the mesh. This cluster prevents Consul from blocking
|
|
|
|
// connections to destinations outside of the catalog when in transparent
|
|
|
|
// proxy mode.
|
2021-03-17 19:40:49 +00:00
|
|
|
OriginalDestinationClusterName = "original-destination"
|
|
|
|
|
2019-01-11 15:43:18 +00:00
|
|
|
// DefaultAuthCheckFrequency is the default value for
|
|
|
|
// Server.AuthCheckFrequency to use when the zero value is provided.
|
|
|
|
DefaultAuthCheckFrequency = 5 * time.Minute
|
2018-10-03 18:18:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// ACLResolverFunc is a shim to resolve ACLs. Since ACL enforcement is so far
|
|
|
|
// entirely agent-local and all uses private methods this allows a simple shim
|
|
|
|
// to be written in the agent package to allow resolving without tightly
|
|
|
|
// coupling this to the agent.
|
2018-10-19 16:04:07 +00:00
|
|
|
type ACLResolverFunc func(id string) (acl.Authorizer, error)
|
2018-10-03 18:18:55 +00:00
|
|
|
|
2021-10-28 01:51:35 +00:00
|
|
|
// HTTPCheckFetcher is the interface the agent needs to expose
|
2019-09-26 02:55:52 +00:00
|
|
|
// for the xDS server to fetch a service's HTTP check definitions
|
|
|
|
type HTTPCheckFetcher interface {
|
2019-12-10 02:26:41 +00:00
|
|
|
ServiceHTTPBasedChecks(serviceID structs.ServiceID) []structs.CheckType
|
2019-09-26 02:55:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ConfigFetcher is the interface the agent needs to expose
|
|
|
|
// for the xDS server to fetch agent config, currently only one field is fetched
|
|
|
|
type ConfigFetcher interface {
|
|
|
|
AdvertiseAddrLAN() string
|
|
|
|
}
|
|
|
|
|
2018-10-03 18:18:55 +00:00
|
|
|
// ConfigManager is the interface xds.Server requires to consume proxy config
|
|
|
|
// updates. It's satisfied normally by the agent's proxycfg.Manager, but allows
|
|
|
|
// easier testing without several layers of mocked cache, local state and
|
|
|
|
// proxycfg.Manager.
|
|
|
|
type ConfigManager interface {
|
2020-01-24 15:04:58 +00:00
|
|
|
Watch(proxyID structs.ServiceID) (<-chan *proxycfg.ConfigSnapshot, proxycfg.CancelFunc)
|
2018-10-03 18:18:55 +00:00
|
|
|
}
|
|
|
|
|
2020-08-27 17:20:58 +00:00
|
|
|
// Server represents a gRPC server that can handle xDS requests from Envoy. All
|
|
|
|
// of it's public members must be set before the gRPC server is started.
|
2018-10-03 18:18:55 +00:00
|
|
|
//
|
|
|
|
// A full description of the XDS protocol can be found at
|
2019-06-03 16:03:05 +00:00
|
|
|
// https://www.envoyproxy.io/docs/envoy/latest/api-docs/xds_protocol
|
2018-10-03 18:18:55 +00:00
|
|
|
type Server struct {
|
2020-01-28 23:50:41 +00:00
|
|
|
Logger hclog.Logger
|
2018-10-03 18:18:55 +00:00
|
|
|
CfgMgr ConfigManager
|
|
|
|
ResolveToken ACLResolverFunc
|
2021-04-29 18:54:05 +00:00
|
|
|
CheckFetcher HTTPCheckFetcher
|
|
|
|
CfgFetcher ConfigFetcher
|
|
|
|
|
2019-01-11 15:43:18 +00:00
|
|
|
// AuthCheckFrequency is how often we should re-check the credentials used
|
|
|
|
// during a long-lived gRPC Stream after it has been initially established.
|
|
|
|
// This is only used during idle periods of stream interactions (i.e. when
|
|
|
|
// there has been no recent DiscoveryRequest).
|
|
|
|
AuthCheckFrequency time.Duration
|
2021-02-26 22:23:15 +00:00
|
|
|
|
2021-09-21 14:58:56 +00:00
|
|
|
// ResourceMapMutateFn exclusively exists for testing purposes.
|
|
|
|
ResourceMapMutateFn func(resourceMap *IndexedResources)
|
|
|
|
|
2021-09-20 16:07:11 +00:00
|
|
|
activeStreams *activeStreamCounters
|
2021-05-14 18:59:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// activeStreamCounters simply encapsulates two counters accessed atomically to
|
2021-09-20 16:07:11 +00:00
|
|
|
// ensure alignment is correct. This further requires that activeStreamCounters
|
|
|
|
// be a pointer field.
|
2021-10-28 01:51:35 +00:00
|
|
|
// TODO(eculver): refactor to remove xDSv2 refs
|
2021-05-14 18:59:13 +00:00
|
|
|
type activeStreamCounters struct {
|
|
|
|
xDSv3 uint64
|
|
|
|
xDSv2 uint64
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *activeStreamCounters) Increment(xdsVersion string) func() {
|
|
|
|
var counter *uint64
|
|
|
|
switch xdsVersion {
|
|
|
|
case "v3":
|
|
|
|
counter = &c.xDSv3
|
|
|
|
case "v2":
|
|
|
|
counter = &c.xDSv2
|
|
|
|
default:
|
|
|
|
return func() {}
|
|
|
|
}
|
|
|
|
|
|
|
|
labels := []metrics.Label{{Name: "version", Value: xdsVersion}}
|
|
|
|
|
|
|
|
count := atomic.AddUint64(counter, 1)
|
|
|
|
metrics.SetGaugeWithLabels([]string{"xds", "server", "streams"}, float32(count), labels)
|
|
|
|
return func() {
|
|
|
|
count := atomic.AddUint64(counter, ^uint64(0))
|
|
|
|
metrics.SetGaugeWithLabels([]string{"xds", "server", "streams"}, float32(count), labels)
|
|
|
|
}
|
2019-01-11 15:43:18 +00:00
|
|
|
}
|
|
|
|
|
2021-04-29 18:54:05 +00:00
|
|
|
func NewServer(
|
|
|
|
logger hclog.Logger,
|
|
|
|
cfgMgr ConfigManager,
|
|
|
|
resolveToken ACLResolverFunc,
|
|
|
|
checkFetcher HTTPCheckFetcher,
|
|
|
|
cfgFetcher ConfigFetcher,
|
|
|
|
) *Server {
|
|
|
|
return &Server{
|
|
|
|
Logger: logger,
|
|
|
|
CfgMgr: cfgMgr,
|
|
|
|
ResolveToken: resolveToken,
|
|
|
|
CheckFetcher: checkFetcher,
|
|
|
|
CfgFetcher: cfgFetcher,
|
|
|
|
AuthCheckFrequency: DefaultAuthCheckFrequency,
|
2021-09-20 16:07:11 +00:00
|
|
|
activeStreams: &activeStreamCounters{},
|
2021-04-29 18:54:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-03 18:18:55 +00:00
|
|
|
// StreamAggregatedResources implements
|
2021-02-26 22:23:15 +00:00
|
|
|
// envoy_discovery_v3.AggregatedDiscoveryServiceServer. This is the ADS endpoint which is
|
2018-10-03 18:18:55 +00:00
|
|
|
// the only xDS API we directly support for now.
|
2021-04-29 18:54:05 +00:00
|
|
|
//
|
|
|
|
// Deprecated: use DeltaAggregatedResources instead
|
2018-10-03 18:18:55 +00:00
|
|
|
func (s *Server) StreamAggregatedResources(stream ADSStream) error {
|
2021-04-29 18:54:05 +00:00
|
|
|
return errors.New("not implemented")
|
|
|
|
}
|
|
|
|
|
2018-10-03 18:18:55 +00:00
|
|
|
func tokenFromContext(ctx context.Context) string {
|
|
|
|
md, ok := metadata.FromIncomingContext(ctx)
|
|
|
|
if !ok {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
toks, ok := md["x-consul-token"]
|
|
|
|
if ok && len(toks) > 0 {
|
|
|
|
return toks[0]
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2021-07-09 16:17:45 +00:00
|
|
|
// NewGRPCServer creates a grpc.Server, registers the Server, and then returns
|
|
|
|
// the grpc.Server.
|
|
|
|
func NewGRPCServer(s *Server, tlsConfigurator *tlsutil.Configurator) *grpc.Server {
|
2021-10-16 17:02:03 +00:00
|
|
|
recoveryOpts := agentgrpc.PanicHandlerMiddlewareOpts(s.Logger)
|
2021-08-22 18:06:26 +00:00
|
|
|
|
2018-10-03 18:18:55 +00:00
|
|
|
opts := []grpc.ServerOption{
|
|
|
|
grpc.MaxConcurrentStreams(2048),
|
2021-08-07 12:21:12 +00:00
|
|
|
middleware.WithUnaryServerChain(
|
2021-08-22 18:06:26 +00:00
|
|
|
// Add middlware interceptors to recover in case of panics.
|
|
|
|
recovery.UnaryServerInterceptor(recoveryOpts...),
|
2021-08-07 12:21:12 +00:00
|
|
|
),
|
|
|
|
middleware.WithStreamServerChain(
|
2021-08-22 18:06:26 +00:00
|
|
|
// Add middlware interceptors to recover in case of panics.
|
|
|
|
recovery.StreamServerInterceptor(recoveryOpts...),
|
2021-08-07 12:21:12 +00:00
|
|
|
),
|
2018-10-03 18:18:55 +00:00
|
|
|
}
|
2020-01-22 10:32:17 +00:00
|
|
|
if tlsConfigurator != nil {
|
|
|
|
if tlsConfigurator.Cert() != nil {
|
2021-09-08 15:48:41 +00:00
|
|
|
creds := credentials.NewTLS(tlsConfigurator.IncomingGRPCConfig())
|
2020-01-22 10:32:17 +00:00
|
|
|
opts = append(opts, grpc.Creds(creds))
|
2018-10-03 18:18:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
srv := grpc.NewServer(opts...)
|
2021-02-26 22:23:15 +00:00
|
|
|
envoy_discovery_v3.RegisterAggregatedDiscoveryServiceServer(srv, s)
|
|
|
|
|
2021-07-09 16:17:45 +00:00
|
|
|
return srv
|
2018-10-03 18:18:55 +00:00
|
|
|
}
|
2021-04-29 18:54:05 +00:00
|
|
|
|
2021-08-13 15:53:19 +00:00
|
|
|
// authorize the xDS request using the token stored in ctx. This authorization is
|
|
|
|
// a bit different from most interfaces. Instead of explicitly authorizing or
|
|
|
|
// filtering each piece of data in the response, the request is authorized
|
|
|
|
// by checking the token has `service:write` for the service ID of the destination
|
|
|
|
// service (for kind=ConnectProxy), or the gateway service (for other kinds).
|
|
|
|
// This authorization strategy requires that agent/proxycfg only fetches data
|
|
|
|
// using a token with the same permissions, and that it stores the data by
|
|
|
|
// proxy ID. We assume that any data in the snapshot was already filtered,
|
|
|
|
// which allows this authorization to be a shallow authorization check
|
|
|
|
// for all the data in a ConfigSnapshot.
|
|
|
|
func (s *Server) authorize(ctx context.Context, cfgSnap *proxycfg.ConfigSnapshot) error {
|
2021-04-29 18:54:05 +00:00
|
|
|
if cfgSnap == nil {
|
|
|
|
return status.Errorf(codes.Unauthenticated, "unauthenticated: no config snapshot")
|
|
|
|
}
|
|
|
|
|
2021-08-13 15:53:19 +00:00
|
|
|
authz, err := s.ResolveToken(tokenFromContext(ctx))
|
2021-04-29 18:54:05 +00:00
|
|
|
if acl.IsErrNotFound(err) {
|
|
|
|
return status.Errorf(codes.Unauthenticated, "unauthenticated: %v", err)
|
|
|
|
} else if acl.IsErrPermissionDenied(err) {
|
|
|
|
return status.Errorf(codes.PermissionDenied, "permission denied: %v", err)
|
|
|
|
} else if err != nil {
|
|
|
|
return status.Errorf(codes.Internal, "error resolving acl token: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var authzContext acl.AuthorizerContext
|
|
|
|
switch cfgSnap.Kind {
|
|
|
|
case structs.ServiceKindConnectProxy:
|
|
|
|
cfgSnap.ProxyID.EnterpriseMeta.FillAuthzContext(&authzContext)
|
2021-08-04 21:51:19 +00:00
|
|
|
if authz.ServiceWrite(cfgSnap.Proxy.DestinationServiceName, &authzContext) != acl.Allow {
|
2021-04-29 18:54:05 +00:00
|
|
|
return status.Errorf(codes.PermissionDenied, "permission denied")
|
|
|
|
}
|
|
|
|
case structs.ServiceKindMeshGateway, structs.ServiceKindTerminatingGateway, structs.ServiceKindIngressGateway:
|
|
|
|
cfgSnap.ProxyID.EnterpriseMeta.FillAuthzContext(&authzContext)
|
2021-08-04 21:51:19 +00:00
|
|
|
if authz.ServiceWrite(cfgSnap.Service, &authzContext) != acl.Allow {
|
2021-04-29 18:54:05 +00:00
|
|
|
return status.Errorf(codes.PermissionDenied, "permission denied")
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
return status.Errorf(codes.Internal, "Invalid service kind")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Authed OK!
|
|
|
|
return nil
|
|
|
|
}
|