text:
package v1beta1

import (
	"reflect"
	"testing"
	"time"

	"github.com/davecgh/go-spew/spew"
	core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
	route "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
	envoy_jwt "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/jwt_authn/v3"
	hcm "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"
	tls "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3"
	"github.com/google/go-cmp/cmp"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/testing/protocmp"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/emptypb"

	authn_alpha "istio.io/api/authentication/v1alpha1"
	authn_filter "istio.io/api/envoy/config/filter/http/authn/v2alpha1"
	"istio.io/api/security/v1beta1"
	type_beta "istio.io/api/type/v1beta1"
	"istio.io/istio/pilot/pkg/features"
	"istio.io/istio/pilot/pkg/model"
	"istio.io/istio/pilot/pkg/model/test"
	"istio.io/istio/pilot/pkg/security/authn"
	"istio.io/istio/pilot/pkg/util/protoconv"
	"istio.io/istio/pkg/config"
	"istio.io/istio/pkg/config/host"
	protovalue "istio.io/istio/pkg/proto"
	istiotest "istio.io/istio/pkg/test"
)

func TestJwtFilter(t *testing.T) {
	ms, err := test.StartNewServer()
	if err != nil {
		t.Fatal("failed to start a mock server")
	}

	jwksURI := ms.URL + "/oauth2/v3/certs"

	cases := []struct {
		name             string
		in               []*config.Config
		enableRemoteJwks bool
		expected         *hcm.HttpFilter
	}{
		{
			name:     "No policy",
			in:       []*config.Config{},
			expected: nil,
		},
		{
			name: "Empty policy",
			in: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{},
				},
			},
			expected: nil,
		},
		{
			name: "Single JWT policy",
			in: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:  "https://secret.foo.com",
								JwksUri: jwksURI,
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "envoy.filters.http.jwt_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(
						&envoy_jwt.JwtAuthentication{
							Rules: []*envoy_jwt.RequirementRule{
								{
									Match: &route.RouteMatch{
										PathSpecifier: &route.RouteMatch_Prefix{
											Prefix: "/",
										},
									},
									RequirementType: &envoy_jwt.RequirementRule_Requires{
										Requires: &envoy_jwt.JwtRequirement{
											RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
												RequiresAny: &envoy_jwt.JwtRequirementOrList{
													Requirements: []*envoy_jwt.JwtRequirement{
														{
															RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																ProviderName: "origins-0",
															},
														},
														{
															RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																AllowMissing: &emptypb.Empty{},
															},
														},
													},
												},
											},
										},
									},
								},
							},
							Providers: map[string]*envoy_jwt.JwtProvider{
								"origins-0": {
									Issuer: "https://secret.foo.com",
									JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
										LocalJwks: &core.DataSource{
											Specifier: &core.DataSource_InlineString{
												InlineString: test.JwtPubKey1,
											},
										},
									},
									Forward:           false,
									PayloadInMetadata: "https://secret.foo.com",
								},
							},
							BypassCorsPreflight: true,
						}),
				},
			},
		},
		{
			name: "JWT policy with Mesh cluster as issuer and remote jwks enabled",
			in: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:  "mesh cluster",
								JwksUri: "http://jwt-token-issuer.mesh:7443/jwks",
							},
						},
					},
				},
			},
			enableRemoteJwks: true,
			expected: &hcm.HttpFilter{
				Name: "envoy.filters.http.jwt_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(
						&envoy_jwt.JwtAuthentication{
							Rules: []*envoy_jwt.RequirementRule{
								{
									Match: &route.RouteMatch{
										PathSpecifier: &route.RouteMatch_Prefix{
											Prefix: "/",
										},
									},
									RequirementType: &envoy_jwt.RequirementRule_Requires{
										Requires: &envoy_jwt.JwtRequirement{
											RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
												RequiresAny: &envoy_jwt.JwtRequirementOrList{
													Requirements: []*envoy_jwt.JwtRequirement{
														{
															RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																ProviderName: "origins-0",
															},
														},
														{
															RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																AllowMissing: &emptypb.Empty{},
															},
														},
													},
												},
											},
										},
									},
								},
							},
							Providers: map[string]*envoy_jwt.JwtProvider{
								"origins-0": {
									Issuer: "mesh cluster",
									JwksSourceSpecifier: &envoy_jwt.JwtProvider_RemoteJwks{
										RemoteJwks: &envoy_jwt.RemoteJwks{
											HttpUri: &core.HttpUri{
												Uri: "http://jwt-token-issuer.mesh:7443/jwks",
												HttpUpstreamType: &core.HttpUri_Cluster{
													Cluster: "outbound|7443||jwt-token-issuer.mesh.svc.cluster.local",
												},
												Timeout: &durationpb.Duration{Seconds: 5},
											},
											CacheDuration: &durationpb.Duration{Seconds: 5 * 60},
										},
									},
									Forward:           false,
									PayloadInMetadata: "mesh cluster",
								},
							},
							BypassCorsPreflight: true,
						}),
				},
			},
		},
		{
			name: "JWT policy with non Mesh cluster as issuer and remote jwks enabled",
			in: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:  "invalid|7443|",
								JwksUri: jwksURI,
							},
						},
					},
				},
			},
			enableRemoteJwks: true,
			expected: &hcm.HttpFilter{
				Name: "envoy.filters.http.jwt_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(
						&envoy_jwt.JwtAuthentication{
							Rules: []*envoy_jwt.RequirementRule{
								{
									Match: &route.RouteMatch{
										PathSpecifier: &route.RouteMatch_Prefix{
											Prefix: "/",
										},
									},
									RequirementType: &envoy_jwt.RequirementRule_Requires{
										Requires: &envoy_jwt.JwtRequirement{
											RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
												RequiresAny: &envoy_jwt.JwtRequirementOrList{
													Requirements: []*envoy_jwt.JwtRequirement{
														{
															RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																ProviderName: "origins-0",
															},
														},
														{
															RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																AllowMissing: &emptypb.Empty{},
															},
														},
													},
												},
											},
										},
									},
								},
							},
							Providers: map[string]*envoy_jwt.JwtProvider{
								"origins-0": {
									Issuer: "invalid|7443|",
									JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
										LocalJwks: &core.DataSource{
											Specifier: &core.DataSource_InlineString{
												InlineString: test.JwtPubKey2,
											},
										},
									},
									Forward:           false,
									PayloadInMetadata: "invalid|7443|",
								},
							},
							BypassCorsPreflight: true,
						}),
				},
			},
		},
		{
			name: "Multi JWTs policy",
			in: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:  "https://secret.foo.com",
								JwksUri: jwksURI,
							},
						},
					},
				},
				{
					Spec: &v1beta1.RequestAuthentication{},
				},
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer: "https://secret.bar.com",
								Jwks:   "jwks-inline-data",
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "envoy.filters.http.jwt_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(
						&envoy_jwt.JwtAuthentication{
							Rules: []*envoy_jwt.RequirementRule{
								{
									Match: &route.RouteMatch{
										PathSpecifier: &route.RouteMatch_Prefix{
											Prefix: "/",
										},
									},
									RequirementType: &envoy_jwt.RequirementRule_Requires{
										Requires: &envoy_jwt.JwtRequirement{
											RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
												RequiresAny: &envoy_jwt.JwtRequirementOrList{
													Requirements: []*envoy_jwt.JwtRequirement{
														{
															RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																ProviderName: "origins-0",
															},
														},
														{
															RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																ProviderName: "origins-1",
															},
														},
														{
															RequiresType: &envoy_jwt.JwtRequirement_RequiresAll{
																RequiresAll: &envoy_jwt.JwtRequirementAndList{
																	Requirements: []*envoy_jwt.JwtRequirement{
																		{
																			RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
																				RequiresAny: &envoy_jwt.JwtRequirementOrList{
																					Requirements: []*envoy_jwt.JwtRequirement{
																						{
																							RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																								ProviderName: "origins-0",
																							},
																						},
																						{
																							RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																								AllowMissing: &emptypb.Empty{},
																							},
																						},
																					},
																				},
																			},
																		},
																		{
																			RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
																				RequiresAny: &envoy_jwt.JwtRequirementOrList{
																					Requirements: []*envoy_jwt.JwtRequirement{
																						{
																							RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																								ProviderName: "origins-1",
																							},
																						},
																						{
																							RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																								AllowMissing: &emptypb.Empty{},
																							},
																						},
																					},
																				},
																			},
																		},
																	},
																},
															},
														},
													},
												},
											},
										},
									},
								},
							},
							Providers: map[string]*envoy_jwt.JwtProvider{
								"origins-0": {
									Issuer: "https://secret.bar.com",
									JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
										LocalJwks: &core.DataSource{
											Specifier: &core.DataSource_InlineString{
												InlineString: "jwks-inline-data",
											},
										},
									},
									Forward:           false,
									PayloadInMetadata: "https://secret.bar.com",
								},
								"origins-1": {
									Issuer: "https://secret.foo.com",
									JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
										LocalJwks: &core.DataSource{
											Specifier: &core.DataSource_InlineString{
												InlineString: test.JwtPubKey1,
											},
										},
									},
									Forward:           false,
									PayloadInMetadata: "https://secret.foo.com",
								},
							},
							BypassCorsPreflight: true,
						}),
				},
			},
		},
		{
			name: "JWT policy with inline Jwks",
			in: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer: "https://secret.foo.com",
								Jwks:   "inline-jwks-data",
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "envoy.filters.http.jwt_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(
						&envoy_jwt.JwtAuthentication{
							Rules: []*envoy_jwt.RequirementRule{
								{
									Match: &route.RouteMatch{
										PathSpecifier: &route.RouteMatch_Prefix{
											Prefix: "/",
										},
									},
									RequirementType: &envoy_jwt.RequirementRule_Requires{
										Requires: &envoy_jwt.JwtRequirement{
											RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
												RequiresAny: &envoy_jwt.JwtRequirementOrList{
													Requirements: []*envoy_jwt.JwtRequirement{
														{
															RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																ProviderName: "origins-0",
															},
														},
														{
															RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																AllowMissing: &emptypb.Empty{},
															},
														},
													},
												},
											},
										},
									},
								},
							},
							Providers: map[string]*envoy_jwt.JwtProvider{
								"origins-0": {
									Issuer: "https://secret.foo.com",
									JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
										LocalJwks: &core.DataSource{
											Specifier: &core.DataSource_InlineString{
												InlineString: "inline-jwks-data",
											},
										},
									},
									Forward:           false,
									PayloadInMetadata: "https://secret.foo.com",
								},
							},
							BypassCorsPreflight: true,
						}),
				},
			},
		},
		{
			name: "JWT policy with bad Jwks URI",
			in: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:  "https://secret.foo.com",
								JwksUri: "http://site.not.exist",
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "envoy.filters.http.jwt_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(
						&envoy_jwt.JwtAuthentication{
							Rules: []*envoy_jwt.RequirementRule{
								{
									Match: &route.RouteMatch{
										PathSpecifier: &route.RouteMatch_Prefix{
											Prefix: "/",
										},
									},
									RequirementType: &envoy_jwt.RequirementRule_Requires{
										Requires: &envoy_jwt.JwtRequirement{
											RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
												RequiresAny: &envoy_jwt.JwtRequirementOrList{
													Requirements: []*envoy_jwt.JwtRequirement{
														{
															RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																ProviderName: "origins-0",
															},
														},
														{
															RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																AllowMissing: &emptypb.Empty{},
															},
														},
													},
												},
											},
										},
									},
								},
							},
							Providers: map[string]*envoy_jwt.JwtProvider{
								"origins-0": {
									Issuer: "https://secret.foo.com",
									JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
										LocalJwks: &core.DataSource{
											Specifier: &core.DataSource_InlineString{
												InlineString: model.CreateFakeJwks("http://site.not.exist"),
											},
										},
									},
									Forward:           false,
									PayloadInMetadata: "https://secret.foo.com",
								},
							},
							BypassCorsPreflight: true,
						}),
				},
			},
		},
		{
			name: "Forward original token",
			in: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:               "https://secret.foo.com",
								JwksUri:              jwksURI,
								ForwardOriginalToken: true,
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "envoy.filters.http.jwt_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(
						&envoy_jwt.JwtAuthentication{
							Rules: []*envoy_jwt.RequirementRule{
								{
									Match: &route.RouteMatch{
										PathSpecifier: &route.RouteMatch_Prefix{
											Prefix: "/",
										},
									},
									RequirementType: &envoy_jwt.RequirementRule_Requires{
										Requires: &envoy_jwt.JwtRequirement{
											RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
												RequiresAny: &envoy_jwt.JwtRequirementOrList{
													Requirements: []*envoy_jwt.JwtRequirement{
														{
															RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																ProviderName: "origins-0",
															},
														},
														{
															RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																AllowMissing: &emptypb.Empty{},
															},
														},
													},
												},
											},
										},
									},
								},
							},
							Providers: map[string]*envoy_jwt.JwtProvider{
								"origins-0": {
									Issuer: "https://secret.foo.com",
									JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
										LocalJwks: &core.DataSource{
											Specifier: &core.DataSource_InlineString{
												InlineString: test.JwtPubKey1,
											},
										},
									},
									Forward:           true,
									PayloadInMetadata: "https://secret.foo.com",
								},
							},
							BypassCorsPreflight: true,
						}),
				},
			},
		},
		{
			name: "Output payload",
			in: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:                "https://secret.foo.com",
								JwksUri:               jwksURI,
								ForwardOriginalToken:  true,
								OutputPayloadToHeader: "x-foo",
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "envoy.filters.http.jwt_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(
						&envoy_jwt.JwtAuthentication{
							Rules: []*envoy_jwt.RequirementRule{
								{
									Match: &route.RouteMatch{
										PathSpecifier: &route.RouteMatch_Prefix{
											Prefix: "/",
										},
									},
									RequirementType: &envoy_jwt.RequirementRule_Requires{
										Requires: &envoy_jwt.JwtRequirement{
											RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
												RequiresAny: &envoy_jwt.JwtRequirementOrList{
													Requirements: []*envoy_jwt.JwtRequirement{
														{
															RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																ProviderName: "origins-0",
															},
														},
														{
															RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																AllowMissing: &emptypb.Empty{},
															},
														},
													},
												},
											},
										},
									},
								},
							},
							Providers: map[string]*envoy_jwt.JwtProvider{
								"origins-0": {
									Issuer: "https://secret.foo.com",
									JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
										LocalJwks: &core.DataSource{
											Specifier: &core.DataSource_InlineString{
												InlineString: test.JwtPubKey1,
											},
										},
									},
									Forward:              true,
									ForwardPayloadHeader: "x-foo",
									PayloadInMetadata:    "https://secret.foo.com",
								},
							},
							BypassCorsPreflight: true,
						}),
				},
			},
		},
		{
			name: "Output claim to header",
			in: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:               "https://secret.foo.com",
								JwksUri:              jwksURI,
								ForwardOriginalToken: true,
								OutputClaimToHeaders: []*v1beta1.ClaimToHeader{
									{Header: "x-jwt-key1", Claim: "value1"},
									{Header: "x-jwt-key2", Claim: "value2"},
								},
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "envoy.filters.http.jwt_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(
						&envoy_jwt.JwtAuthentication{
							Rules: []*envoy_jwt.RequirementRule{
								{
									Match: &route.RouteMatch{
										PathSpecifier: &route.RouteMatch_Prefix{
											Prefix: "/",
										},
									},
									RequirementType: &envoy_jwt.RequirementRule_Requires{
										Requires: &envoy_jwt.JwtRequirement{
											RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
												RequiresAny: &envoy_jwt.JwtRequirementOrList{
													Requirements: []*envoy_jwt.JwtRequirement{
														{
															RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																ProviderName: "origins-0",
															},
														},
														{
															RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																AllowMissing: &emptypb.Empty{},
															},
														},
													},
												},
											},
										},
									},
								},
							},
							Providers: map[string]*envoy_jwt.JwtProvider{
								"origins-0": {
									Issuer: "https://secret.foo.com",
									JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
										LocalJwks: &core.DataSource{
											Specifier: &core.DataSource_InlineString{
												InlineString: test.JwtPubKey1,
											},
										},
									},
									Forward: true,
									ClaimToHeaders: []*envoy_jwt.JwtClaimToHeader{
										{HeaderName: "x-jwt-key1", ClaimName: "value1"},
										{HeaderName: "x-jwt-key2", ClaimName: "value2"},
									},
									PayloadInMetadata: "https://secret.foo.com",
								},
							},
							BypassCorsPreflight: true,
						}),
				},
			},
		},
	}

	push := model.NewPushContext()
	push.JwtKeyResolver = model.NewJwksResolver(
		model.JwtPubKeyEvictionDuration, model.JwtPubKeyRefreshInterval,
		model.JwtPubKeyRefreshIntervalOnFailure, model.JwtPubKeyRetryInterval)
	defer push.JwtKeyResolver.Close()

	push.ServiceIndex.HostnameAndNamespace[host.Name("jwt-token-issuer.mesh")] = map[string]*model.Service{}
	push.ServiceIndex.HostnameAndNamespace[host.Name("jwt-token-issuer.mesh")]["mesh"] = &model.Service{
		Hostname: "jwt-token-issuer.mesh.svc.cluster.local",
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			istiotest.SetForTest(t, &features.EnableRemoteJwks, c.enableRemoteJwks)
			if got := NewPolicyApplier("root-namespace", c.in, nil, push).JwtFilter(); !reflect.DeepEqual(c.expected, got) {
				t.Errorf("got:\n%s\nwanted:\n%s", spew.Sdump(got), spew.Sdump(c.expected))
			}
		})
	}
}

func TestConvertToEnvoyJwtConfig(t *testing.T) {
	ms, err := test.StartNewServer()
	if err != nil {
		t.Fatal("failed to start a mock server")
	}

	jwksURI := ms.URL + "/oauth2/v3/certs"

	cases := []struct {
		name     string
		in       []*v1beta1.JWTRule
		expected *envoy_jwt.JwtAuthentication
	}{
		{
			name:     "No rule",
			in:       []*v1beta1.JWTRule{},
			expected: nil,
		},
		{
			name: "Single JWT rule",
			in: []*v1beta1.JWTRule{
				{
					Issuer:  "https://secret.foo.com",
					JwksUri: jwksURI,
				},
			},
			expected: &envoy_jwt.JwtAuthentication{
				Rules: []*envoy_jwt.RequirementRule{
					{
						Match: &route.RouteMatch{
							PathSpecifier: &route.RouteMatch_Prefix{
								Prefix: "/",
							},
						},
						RequirementType: &envoy_jwt.RequirementRule_Requires{
							Requires: &envoy_jwt.JwtRequirement{
								RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
									RequiresAny: &envoy_jwt.JwtRequirementOrList{
										Requirements: []*envoy_jwt.JwtRequirement{
											{
												RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
													ProviderName: "origins-0",
												},
											},
											{
												RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
													AllowMissing: &emptypb.Empty{},
												},
											},
										},
									},
								},
							},
						},
					},
				},
				Providers: map[string]*envoy_jwt.JwtProvider{
					"origins-0": {
						Issuer: "https://secret.foo.com",
						JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
							LocalJwks: &core.DataSource{
								Specifier: &core.DataSource_InlineString{
									InlineString: test.JwtPubKey1,
								},
							},
						},
						Forward:           false,
						PayloadInMetadata: "https://secret.foo.com",
					},
				},
				BypassCorsPreflight: true,
			},
		},
		{
			name: "Multiple JWT rule",
			in: []*v1beta1.JWTRule{
				{
					Issuer:  "https://secret.foo.com",
					JwksUri: jwksURI,
				},
				{
					Issuer: "https://secret.bar.com",
					Jwks:   "jwks-inline-data",
				},
			},
			expected: &envoy_jwt.JwtAuthentication{
				Rules: []*envoy_jwt.RequirementRule{
					{
						Match: &route.RouteMatch{
							PathSpecifier: &route.RouteMatch_Prefix{
								Prefix: "/",
							},
						},
						RequirementType: &envoy_jwt.RequirementRule_Requires{
							Requires: &envoy_jwt.JwtRequirement{
								RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
									RequiresAny: &envoy_jwt.JwtRequirementOrList{
										Requirements: []*envoy_jwt.JwtRequirement{
											{
												RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
													ProviderName: "origins-0",
												},
											},
											{
												RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
													ProviderName: "origins-1",
												},
											},
											{
												RequiresType: &envoy_jwt.JwtRequirement_RequiresAll{
													RequiresAll: &envoy_jwt.JwtRequirementAndList{
														Requirements: []*envoy_jwt.JwtRequirement{
															{
																RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
																	RequiresAny: &envoy_jwt.JwtRequirementOrList{
																		Requirements: []*envoy_jwt.JwtRequirement{
																			{
																				RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																					ProviderName: "origins-0",
																				},
																			},
																			{
																				RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																					AllowMissing: &emptypb.Empty{},
																				},
																			},
																		},
																	},
																},
															},
															{
																RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
																	RequiresAny: &envoy_jwt.JwtRequirementOrList{
																		Requirements: []*envoy_jwt.JwtRequirement{
																			{
																				RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
																					ProviderName: "origins-1",
																				},
																			},
																			{
																				RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
																					AllowMissing: &emptypb.Empty{},
																				},
																			},
																		},
																	},
																},
															},
														},
													},
												},
											},
										},
									},
								},
							},
						},
					},
				},
				Providers: map[string]*envoy_jwt.JwtProvider{
					"origins-0": {
						Issuer: "https://secret.foo.com",
						JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
							LocalJwks: &core.DataSource{
								Specifier: &core.DataSource_InlineString{
									InlineString: test.JwtPubKey1,
								},
							},
						},
						Forward:           false,
						PayloadInMetadata: "https://secret.foo.com",
					},
					"origins-1": {
						Issuer: "https://secret.bar.com",
						JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
							LocalJwks: &core.DataSource{
								Specifier: &core.DataSource_InlineString{
									InlineString: "jwks-inline-data",
								},
							},
						},
						Forward:           false,
						PayloadInMetadata: "https://secret.bar.com",
					},
				},
				BypassCorsPreflight: true,
			},
		},
		{
			name: "Empty Jwks URI",
			in: []*v1beta1.JWTRule{
				{
					Issuer: "https://secret.foo.com",
				},
			},
			expected: &envoy_jwt.JwtAuthentication{
				Rules: []*envoy_jwt.RequirementRule{
					{
						Match: &route.RouteMatch{
							PathSpecifier: &route.RouteMatch_Prefix{
								Prefix: "/",
							},
						},
						RequirementType: &envoy_jwt.RequirementRule_Requires{
							Requires: &envoy_jwt.JwtRequirement{
								RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
									RequiresAny: &envoy_jwt.JwtRequirementOrList{
										Requirements: []*envoy_jwt.JwtRequirement{
											{
												RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
													ProviderName: "origins-0",
												},
											},
											{
												RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
													AllowMissing: &emptypb.Empty{},
												},
											},
										},
									},
								},
							},
						},
					},
				},
				Providers: map[string]*envoy_jwt.JwtProvider{
					"origins-0": {
						Issuer: "https://secret.foo.com",
						JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
							LocalJwks: &core.DataSource{
								Specifier: &core.DataSource_InlineString{
									InlineString: model.CreateFakeJwks(""),
								},
							},
						},
						Forward:           false,
						PayloadInMetadata: "https://secret.foo.com",
					},
				},
				BypassCorsPreflight: true,
			},
		},
		{
			name: "Unreachable Jwks URI",
			in: []*v1beta1.JWTRule{
				{
					Issuer:  "https://secret.foo.com",
					JwksUri: "http://site.not.exist",
				},
			},
			expected: &envoy_jwt.JwtAuthentication{
				Rules: []*envoy_jwt.RequirementRule{
					{
						Match: &route.RouteMatch{
							PathSpecifier: &route.RouteMatch_Prefix{
								Prefix: "/",
							},
						},
						RequirementType: &envoy_jwt.RequirementRule_Requires{
							Requires: &envoy_jwt.JwtRequirement{
								RequiresType: &envoy_jwt.JwtRequirement_RequiresAny{
									RequiresAny: &envoy_jwt.JwtRequirementOrList{
										Requirements: []*envoy_jwt.JwtRequirement{
											{
												RequiresType: &envoy_jwt.JwtRequirement_ProviderName{
													ProviderName: "origins-0",
												},
											},
											{
												RequiresType: &envoy_jwt.JwtRequirement_AllowMissing{
													AllowMissing: &emptypb.Empty{},
												},
											},
										},
									},
								},
							},
						},
					},
				},
				Providers: map[string]*envoy_jwt.JwtProvider{
					"origins-0": {
						Issuer: "https://secret.foo.com",
						JwksSourceSpecifier: &envoy_jwt.JwtProvider_LocalJwks{
							LocalJwks: &core.DataSource{
								Specifier: &core.DataSource_InlineString{
									InlineString: model.CreateFakeJwks("http://site.not.exist"),
								},
							},
						},
						Forward:           false,
						PayloadInMetadata: "https://secret.foo.com",
					},
				},
				BypassCorsPreflight: true,
			},
		},
	}

	push := &model.PushContext{}
	push.JwtKeyResolver = model.NewJwksResolver(
		model.JwtPubKeyEvictionDuration, model.JwtPubKeyRefreshInterval,
		model.JwtPubKeyRefreshIntervalOnFailure, model.JwtPubKeyRetryInterval)
	defer push.JwtKeyResolver.Close()

	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := convertToEnvoyJwtConfig(c.in, push); !reflect.DeepEqual(c.expected, got) {
				t.Errorf("got:\n%s\nwanted:\n%s\n", spew.Sdump(got), spew.Sdump(c.expected))
			}
		})
	}
}

func humanReadableAuthnFilterDump(filter *hcm.HttpFilter) string {
	if filter == nil {
		return "<nil>"
	}
	config := &authn_filter.FilterConfig{}
	filter.GetTypedConfig().UnmarshalTo(config)
	return spew.Sdump(config)
}

func TestAuthnFilterConfig(t *testing.T) {
	ms, err := test.StartNewServer()
	if err != nil {
		t.Fatal("failed to start a mock server")
	}
	jwksURI := ms.URL + "/oauth2/v3/certs"

	cases := []struct {
		name       string
		forSidecar bool
		jwtIn      []*config.Config
		peerIn     []*config.Config
		expected   *hcm.HttpFilter
	}{
		{
			name:     "no-policy",
			expected: nil,
		},
		{
			name: "beta-jwt",
			jwtIn: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:  "https://secret.foo.com",
								JwksUri: jwksURI,
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "istio_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(&authn_filter.FilterConfig{
						SkipValidateTrustDomain: true,
						Policy: &authn_alpha.Policy{
							Origins: []*authn_alpha.OriginAuthenticationMethod{
								{
									Jwt: &authn_alpha.Jwt{
										Issuer: "https://secret.foo.com",
									},
								},
							},
							OriginIsOptional: true,
							PrincipalBinding: authn_alpha.PrincipalBinding_USE_ORIGIN,
						},
					}),
				},
			},
		},
		{
			name:       "beta-jwt-for-sidecar",
			forSidecar: true,
			jwtIn: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:  "https://secret.foo.com",
								JwksUri: jwksURI,
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "istio_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(&authn_filter.FilterConfig{
						SkipValidateTrustDomain: true,
						DisableClearRouteCache:  true,
						Policy: &authn_alpha.Policy{
							Origins: []*authn_alpha.OriginAuthenticationMethod{
								{
									Jwt: &authn_alpha.Jwt{
										Issuer: "https://secret.foo.com",
									},
								},
							},
							OriginIsOptional: true,
							PrincipalBinding: authn_alpha.PrincipalBinding_USE_ORIGIN,
						},
					}),
				},
			},
		},
		{
			name: "multi-beta-jwt",
			jwtIn: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:  "https://secret.bar.com",
								JwksUri: jwksURI,
							},
						},
					},
				},
				{
					Spec: &v1beta1.RequestAuthentication{},
				},
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer: "https://secret.foo.com",
								Jwks:   "jwks-inline-data",
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "istio_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(&authn_filter.FilterConfig{
						SkipValidateTrustDomain: true,
						Policy: &authn_alpha.Policy{
							Origins: []*authn_alpha.OriginAuthenticationMethod{
								{
									Jwt: &authn_alpha.Jwt{
										Issuer: "https://secret.bar.com",
									},
								},
								{
									Jwt: &authn_alpha.Jwt{
										Issuer: "https://secret.foo.com",
									},
								},
							},
							OriginIsOptional: true,
							PrincipalBinding: authn_alpha.PrincipalBinding_USE_ORIGIN,
						},
					}),
				},
			},
		},
		{
			name: "multi-beta-jwt-sort-by-issuer-again",
			jwtIn: []*config.Config{
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer:  "https://secret.foo.com",
								JwksUri: jwksURI,
							},
						},
					},
				},
				{
					Spec: &v1beta1.RequestAuthentication{},
				},
				{
					Spec: &v1beta1.RequestAuthentication{
						JwtRules: []*v1beta1.JWTRule{
							{
								Issuer: "https://secret.bar.com",
								Jwks:   "jwks-inline-data",
							},
						},
					},
				},
			},
			expected: &hcm.HttpFilter{
				Name: "istio_authn",
				ConfigType: &hcm.HttpFilter_TypedConfig{
					TypedConfig: protoconv.MessageToAny(&authn_filter.FilterConfig{
						SkipValidateTrustDomain: true,
						Policy: &authn_alpha.Policy{
							Origins: []*authn_alpha.OriginAuthenticationMethod{
								{
									Jwt: &authn_alpha.Jwt{
										Issuer: "https://secret.bar.com",
									},
								},
								{
									Jwt: &authn_alpha.Jwt{
										Issuer: "https://secret.foo.com",
									},
								},
							},
							OriginIsOptional: true,
							PrincipalBinding: authn_alpha.PrincipalBinding_USE_ORIGIN,
						},
					}),
				},
			},
		},
		{
			name: "beta-mtls",
			peerIn: []*config.Config{
				{
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
			},
			expected: nil,
		},
		{
			name: "beta-mtls-disable",
			peerIn: []*config.Config{
				{
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
						},
					},
				},
			},
			expected: nil,
		},
		{
			name: "beta-mtls-skip-trust-domain",
			peerIn: []*config.Config{
				{
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
			},
			expected: nil,
		},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got := NewPolicyApplier("root-namespace", c.jwtIn, c.peerIn, &model.PushContext{}).AuthNFilter(c.forSidecar)
			if !reflect.DeepEqual(c.expected, got) {
				t.Errorf("got:\n%v\nwanted:\n%v\n", humanReadableAuthnFilterDump(got), humanReadableAuthnFilterDump(c.expected))
			}
		})
	}
}

func TestInboundMTLSSettings(t *testing.T) {
	now := time.Now()
	tlsContext := &tls.DownstreamTlsContext{
		CommonTlsContext: &tls.CommonTlsContext{
			TlsCertificateSdsSecretConfigs: []*tls.SdsSecretConfig{
				{
					Name: "default",
					SdsConfig: &core.ConfigSource{
						ConfigSourceSpecifier: &core.ConfigSource_ApiConfigSource{
							ApiConfigSource: &core.ApiConfigSource{
								ApiType:                   core.ApiConfigSource_GRPC,
								SetNodeOnFirstMessageOnly: true,
								TransportApiVersion:       core.ApiVersion_V3,
								GrpcServices: []*core.GrpcService{
									{
										TargetSpecifier: &core.GrpcService_EnvoyGrpc_{
											EnvoyGrpc: &core.GrpcService_EnvoyGrpc{ClusterName: "sds-grpc"},
										},
									},
								},
							},
						},
						InitialFetchTimeout: durationpb.New(time.Second * 0),
						ResourceApiVersion:  core.ApiVersion_V3,
					},
				},
			},
			ValidationContextType: &tls.CommonTlsContext_CombinedValidationContext{
				CombinedValidationContext: &tls.CommonTlsContext_CombinedCertificateValidationContext{
					DefaultValidationContext: &tls.CertificateValidationContext{},
					ValidationContextSdsSecretConfig: &tls.SdsSecretConfig{
						Name: "ROOTCA",
						SdsConfig: &core.ConfigSource{
							ConfigSourceSpecifier: &core.ConfigSource_ApiConfigSource{
								ApiConfigSource: &core.ApiConfigSource{
									ApiType:                   core.ApiConfigSource_GRPC,
									SetNodeOnFirstMessageOnly: true,
									TransportApiVersion:       core.ApiVersion_V3,
									GrpcServices: []*core.GrpcService{
										{
											TargetSpecifier: &core.GrpcService_EnvoyGrpc_{
												EnvoyGrpc: &core.GrpcService_EnvoyGrpc{ClusterName: "sds-grpc"},
											},
										},
									},
								},
							},
							InitialFetchTimeout: durationpb.New(time.Second * 0),
							ResourceApiVersion:  core.ApiVersion_V3,
						},
					},
				},
			},
			AlpnProtocols: []string{"istio-peer-exchange", "h2", "http/1.1"},
			TlsParams: &tls.TlsParameters{
				TlsMinimumProtocolVersion: tls.TlsParameters_TLSv1_2,
				TlsMaximumProtocolVersion: tls.TlsParameters_TLSv1_3,
				CipherSuites: []string{
					"ECDHE-ECDSA-AES256-GCM-SHA384",
					"ECDHE-RSA-AES256-GCM-SHA384",
					"ECDHE-ECDSA-AES128-GCM-SHA256",
					"ECDHE-RSA-AES128-GCM-SHA256",
					"AES256-GCM-SHA384",
					"AES128-GCM-SHA256",
				},
			},
		},
		RequireClientCertificate: protovalue.BoolTrue,
	}
	tlsContextHTTP := proto.Clone(tlsContext).(*tls.DownstreamTlsContext)
	tlsContextHTTP.CommonTlsContext.AlpnProtocols = []string{"h2", "http/1.1"}

	expectedStrict := authn.MTLSSettings{
		Port: 8080,
		Mode: model.MTLSStrict,
		TCP:  tlsContext,
		HTTP: tlsContextHTTP,
	}
	expectedPermissive := authn.MTLSSettings{
		Port: 8080,
		Mode: model.MTLSPermissive,
		TCP:  tlsContext,
		HTTP: tlsContextHTTP,
	}

	cases := []struct {
		name         string
		peerPolicies []*config.Config
		expected     authn.MTLSSettings
	}{
		{
			name:     "No policy - behave as permissive",
			expected: expectedPermissive,
		},
		{
			name: "Single policy - disable mode",
			peerPolicies: []*config.Config{
				{
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
						},
					},
				},
			},
			expected: authn.MTLSSettings{Port: 8080, Mode: model.MTLSDisable},
		},
		{
			name: "Single policy - permissive mode",
			peerPolicies: []*config.Config{
				{
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
						},
					},
				},
			},
			expected: expectedPermissive,
		},
		{
			name: "Single policy - strict mode",
			peerPolicies: []*config.Config{
				{
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
			},
			expected: expectedStrict,
		},
		{
			name: "Multiple policies resolved to STRICT",
			peerPolicies: []*config.Config{
				{
					Meta: config.Meta{
						Name:              "now",
						Namespace:         "my-ns",
						CreationTimestamp: now,
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:              "later",
						Namespace:         "my-ns",
						CreationTimestamp: now.Add(time.Second),
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
						},
					},
				},
			},
			expected: expectedStrict,
		},
		{
			name: "Multiple policies resolved to PERMISSIVE",
			peerPolicies: []*config.Config{
				{
					Meta: config.Meta{
						Name:              "now",
						Namespace:         "my-ns",
						CreationTimestamp: now,
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:              "earlier",
						Namespace:         "my-ns",
						CreationTimestamp: now.Add(time.Second * -1),
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
						},
					},
				},
			},
			expected: expectedPermissive,
		},
		{
			name: "Port level hit",
			peerPolicies: []*config.Config{
				{
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
						},
						PortLevelMtls: map[uint32]*v1beta1.PeerAuthentication_MutualTLS{
							8080: {
								Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
							},
						},
					},
				},
			},
			expected: expectedStrict,
		},
		{
			name: "Port level miss",
			peerPolicies: []*config.Config{
				{
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
						PortLevelMtls: map[uint32]*v1beta1.PeerAuthentication_MutualTLS{
							7070: {
								Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
							},
						},
					},
				},
			},
			expected: expectedPermissive,
		},
	}

	testNode := &model.Proxy{
		Labels: map[string]string{
			"app": "foo",
		},
		Metadata: &model.NodeMetadata{},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			got := NewPolicyApplier("root-namespace", nil, tc.peerPolicies, &model.PushContext{}).InboundMTLSSettings(
				8080,
				testNode,
				[]string{},
				authn.NoOverride,
			)
			if diff := cmp.Diff(tc.expected, got, protocmp.Transform()); diff != "" {
				t.Errorf("unexpected filter chains: %v", diff)
			}
		})
	}
}

func TestComposePeerAuthentication(t *testing.T) {
	now := time.Now()
	tests := []struct {
		name    string
		configs []*config.Config
		want    *v1beta1.PeerAuthentication
	}{
		{
			name:    "no config",
			configs: []*config.Config{},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
				},
			},
		},
		{
			name: "mesh only",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "root-namespace",
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
				},
			},
		},
		{
			name: "mesh vs namespace",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "root-namespace",
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{},
						},
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "my-ns",
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
				},
			},
		},
		{
			name: "ignore non-emptypb selector in root namespace",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "root-namespace",
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
				},
			},
		},
		{
			name: "workload vs namespace config",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "my-ns",
					},
					Spec: &v1beta1.PeerAuthentication{},
				},
				{
					Meta: config.Meta{
						Name:      "foo",
						Namespace: "my-ns",
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
				},
			},
		},
		{
			name: "workload vs mesh config",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "my-ns",
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "root-namespace",
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
				},
			},
		},
		{
			name: "multiple mesh policy",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:              "now",
						Namespace:         "root-namespace",
						CreationTimestamp: now,
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:              "second ago",
						Namespace:         "root-namespace",
						CreationTimestamp: now.Add(time.Second * -1),
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:              "second later",
						Namespace:         "root-namespace",
						CreationTimestamp: now.Add(time.Second * -1),
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
				},
			},
		},
		{
			name: "multiple namespace policy",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:              "now",
						Namespace:         "my-ns",
						CreationTimestamp: now,
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:              "second ago",
						Namespace:         "my-ns",
						CreationTimestamp: now.Add(time.Second * -1),
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:              "second later",
						Namespace:         "my-ns",
						CreationTimestamp: now.Add(time.Second * -1),
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
				},
			},
		},
		{
			name: "multiple workload policy",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:              "now",
						Namespace:         "my-ns",
						CreationTimestamp: now,
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:              "second ago",
						Namespace:         "my-ns",
						CreationTimestamp: now.Add(time.Second * -1),
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:              "second later",
						Namespace:         "my-ns",
						CreationTimestamp: now.Add(time.Second * -1),
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"stage": "prod",
							},
						},
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
				},
			},
		},
		{
			name: "inheritance: default mesh",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "root-namespace",
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_UNSET,
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
				},
			},
		},
		{
			name: "inheritance: mesh to workload",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "root-namespace",
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:      "foo",
						Namespace: "my-ns",
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
				},
			},
		},
		{
			name: "inheritance: namespace to workload",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "my-ns",
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:      "foo",
						Namespace: "my-ns",
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
				},
			},
		},
		{
			name: "inheritance: mesh to namespace to workload",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "root-namespace",
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "my-ns",
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_UNSET,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:      "foo",
						Namespace: "my-ns",
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
				},
			},
		},
		{
			name: "port level",
			configs: []*config.Config{
				{
					Meta: config.Meta{
						Name:      "default",
						Namespace: "root-namespace",
					},
					Spec: &v1beta1.PeerAuthentication{
						Mtls: &v1beta1.PeerAuthentication_MutualTLS{
							Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
						},
					},
				},
				{
					Meta: config.Meta{
						Name:      "foo",
						Namespace: "my-ns",
					},
					Spec: &v1beta1.PeerAuthentication{
						Selector: &type_beta.WorkloadSelector{
							MatchLabels: map[string]string{
								"app": "foo",
							},
						},
						PortLevelMtls: map[uint32]*v1beta1.PeerAuthentication_MutualTLS{
							80: {
								Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
							},
							90: {
								Mode: v1beta1.PeerAuthentication_MutualTLS_UNSET,
							},
							100: {},
						},
					},
				},
			},
			want: &v1beta1.PeerAuthentication{
				Mtls: &v1beta1.PeerAuthentication_MutualTLS{
					Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
				},
				PortLevelMtls: map[uint32]*v1beta1.PeerAuthentication_MutualTLS{
					80: {
						Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
					},
					90: {
						Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
					},
					100: {
						Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
					},
				},
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := ComposePeerAuthentication("root-namespace", tt.configs); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("composePeerAuthentication() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestGetMutualTLSMode(t *testing.T) {
	tests := []struct {
		name string
		in   *v1beta1.PeerAuthentication_MutualTLS
		want model.MutualTLSMode
	}{
		{
			name: "unset",
			in: &v1beta1.PeerAuthentication_MutualTLS{
				Mode: v1beta1.PeerAuthentication_MutualTLS_UNSET,
			},
			want: model.MTLSUnknown,
		},
		{
			name: "disable",
			in: &v1beta1.PeerAuthentication_MutualTLS{
				Mode: v1beta1.PeerAuthentication_MutualTLS_DISABLE,
			},
			want: model.MTLSDisable,
		},
		{
			name: "permissive",
			in: &v1beta1.PeerAuthentication_MutualTLS{
				Mode: v1beta1.PeerAuthentication_MutualTLS_PERMISSIVE,
			},
			want: model.MTLSPermissive,
		},
		{
			name: "strict",
			in: &v1beta1.PeerAuthentication_MutualTLS{
				Mode: v1beta1.PeerAuthentication_MutualTLS_STRICT,
			},
			want: model.MTLSStrict,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := getMutualTLSMode(tt.in); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("getMutualTLSMode() = %v, want %v", got, tt.want)
			}
		})
	}
}


text:
package net.it_adviser.gps.pgsd4java.backend;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.it_adviser.gps.pgsd4java.api.IObjectListener;
import net.it_adviser.gps.pgsd4java.types.ATTObject;
import net.it_adviser.gps.pgsd4java.types.DeviceObject;
import net.it_adviser.gps.pgsd4java.types.DevicesObject;
import net.it_adviser.gps.pgsd4java.types.IGPSObject;
import net.it_adviser.gps.pgsd4java.types.ParseException;
import net.it_adviser.gps.pgsd4java.types.PollObject;
import net.it_adviser.gps.pgsd4java.types.SKYObject;
import net.it_adviser.gps.pgsd4java.types.TPVObject;
import net.it_adviser.gps.pgsd4java.types.VersionObject;
import net.it_adviser.gps.pgsd4java.types.WatchObject;
import net.it_adviser.gps.pgsd4java.types.subframes.SUBFRAMEObject;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * GPSd client endpoint
 *
 * @author thoeger
 */
public class GPSdEndpoint {

	private static final Logger LOG = Logger.getLogger(GPSdEndpoint.class.getName());

	private final Socket socket;

	private final BufferedReader in;

	private final BufferedWriter out;

	private SocketThread listenThread;

	private final List<IObjectListener> listeners = new ArrayList<IObjectListener>(1);

	private IGPSObject asnycResult = null;

	private final Object asyncMutex = new Object();

	private final Object asyncWaitMutex = new Object();

	private final AbstractResultParser resultParser;

	/**
	 * Instantiate this class to connect to a GPSd server
	 *
	 * @param server
	 *            the server name or IP
	 * @param port
	 *            the server port
	 * @param resultParser
	 * @throws UnknownHostException
	 * @throws IOException
	 */
	public GPSdEndpoint(final String server, final int port, final AbstractResultParser resultParser) throws UnknownHostException,
			IOException {
		if (server == null) {
			throw new IllegalArgumentException("server can not be null!");
		}
		if ((port < 0) || (port > 65535)) {
			throw new IllegalArgumentException("Illegal port number: " + port);
		}
		if (resultParser == null) {
			throw new IllegalArgumentException("resultParser can not be null!");
		}

		this.socket = new Socket(server, port);
		this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
		this.out = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
		this.resultParser = resultParser;
	}

	/**
	 * start the endpoint
	 */
	public void start() {
		this.listenThread = new SocketThread(this.in, this, this.resultParser);
		this.listenThread.start();

		try {
			Thread.sleep(500);
		} catch (final InterruptedException e) {
			GPSdEndpoint.LOG.log(Level.FINE, null, e);
		}
	}

	/**
	 * Stops the endpoint.
	 */
	public void stop() {
		try {
			this.listenThread.halt();
		} catch (final Exception e) {
			GPSdEndpoint.LOG.log(Level.FINE, null, e);
		}
		this.listenThread = null;
	}

	/**
	 * send WATCH command
	 *
	 * @param enable
	 *            enable/disable watch mode
	 * @param dumpData
	 *            enable/disable dumping of data
	 * @return {@link WatchObject}
	 * @throws IOException
	 *             on IO error in socket
	 * @throws JSONException
	 */
	public WatchObject watch(final boolean enable, final boolean dumpData) throws IOException, JSONException {
		return this.watch(enable, dumpData, null);
	}

	/**
	 * send WATCH command
	 *
	 * @param enable
	 *            enable/disable watch mode
	 * @param dumpData
	 *            enable/disable dumping of data
	 * @param device
	 *            If present, enable watching only of the specified device rather than all devices
	 * @return {@link WatchObject}
	 * @throws IOException
	 *             on IO error in socket
	 * @throws JSONException
	 */
	public WatchObject watch(final boolean enable, final boolean dumpData, final String device) throws IOException, JSONException {
		final JSONObject watch = new JSONObject();
		watch.put("class", "WATCH");
		watch.put("enable", enable);
		watch.put("json", dumpData);
		if (device != null) {
			watch.put("device", device);
		}
		return this.syncCommand("?WATCH=" + watch.toString(), WatchObject.class);
	}

	/**
	 * Poll GPSd for Message
	 *
	 * @return {@link PollObject}
	 * @throws IOException
	 *             on IO error in socket
	 * @throws ParseException
	 *             on illegal response
	 */
	public PollObject poll() throws IOException, ParseException {
		return this.syncCommand("?POLL;", PollObject.class);
	}

	/**
	 * Poll GPSd version
	 *
	 * @return {@link VersionObject}
	 * @throws IOException
	 *             on IO error in socket
	 * @throws ParseException
	 *             on illegal response
	 */
	public VersionObject version() throws IOException, ParseException {
		return this.syncCommand("?VERSION;", VersionObject.class);
	}

	// TODO implement rest of commands
	// ########################################################
	/**
	 * @param listener
	 *            the listener to add
	 */
	public void addListener(final IObjectListener listener) {
		this.listeners.add(listener);
	}

	/**
	 * @param listener
	 *            the listener to remove
	 */
	public void removeListener(final IObjectListener listener) {
		this.listeners.remove(listener);
	}

	// ########################################################

	/*
	 * send command to GPSd and wait for response
	 */
	private <T extends IGPSObject> T syncCommand(final String command, final Class<T> responseClass) throws IOException {
		synchronized (this.asyncMutex) {
			this.out.write(command + "\n");
			this.out.flush();

			while (true) {
				// wait for awaited message
				final IGPSObject result = this.waitForResult();
				if ((result == null) || result.getClass().equals(responseClass)) {
					return responseClass.cast(result);
				}
			}
		}
	}

	/*
	 * send command without response
	 */
	public void voidCommand(final String command) throws IOException {
		synchronized (this.asyncMutex) {
			this.out.write(command + "\n");
			this.out.flush();
		}
	}

	/*
	 * wait for a response for one second
	 */
	private IGPSObject waitForResult() {
		synchronized (this.asyncWaitMutex) {
			this.asnycResult = null;
			try {
				this.asyncWaitMutex.wait(1000);
			} catch (final InterruptedException e) {
				GPSdEndpoint.LOG.log(Level.INFO, null, e);
			}
			if (this.asnycResult != null) {
				return this.asnycResult;
			}
		}
		return null;
	}

	/*
	 * handle incoming messages and dispatch them
	 */
	void handle(final IGPSObject object) {
		if (object instanceof TPVObject) {
			for (final IObjectListener l : this.listeners) {
				l.handleTPV((TPVObject) object);
			}
		} else if (object instanceof SKYObject) {
			for (final IObjectListener l : this.listeners) {
				l.handleSKY((SKYObject) object);
			}
		} else if (object instanceof ATTObject) {
			for (final IObjectListener l : this.listeners) {
				l.handleATT((ATTObject) object);
			}
		} else if (object instanceof SUBFRAMEObject) {
			for (final IObjectListener l : this.listeners) {
				l.handleSUBFRAME((SUBFRAMEObject) object);
			}
		} else if (object instanceof DevicesObject) {
			for (final IObjectListener l : this.listeners) {
				l.handleDevices((DevicesObject) object);
			}
		} else if (object instanceof DeviceObject) {
			for (final IObjectListener l : this.listeners) {
				l.handleDevice((DeviceObject) object);
			}
		} else {
			// object was requested, so put it in the response object
			synchronized (this.asyncWaitMutex) {
				this.asnycResult = object;
				this.asyncWaitMutex.notifyAll();
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package io.druid.benchmark;

import com.google.common.collect.Sets;
import io.druid.java.util.common.StringUtils;
import io.druid.server.router.ConsistentHasher;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@State(Scope.Benchmark)
@Fork(value = 1)
@Warmup(iterations = 15)
@Measurement(iterations = 30)
public class ConsistentHasherBenchmark
{
  @Param({"100000"})
  int numIds;

  ConsistentHasher hasher;
  List<String> uuids;
  Set<String> servers;

  @Setup
  public void setup()
  {
    hasher = new ConsistentHasher(null);
    uuids = new ArrayList<>();
    servers = Sets.newHashSet(
        "localhost:1",
        "localhost:2",
        "localhost:3",
        "localhost:4",
        "localhost:5",
        "localhost:6",
        "localhost:7",
        "localhost:8",
        "localhost:9",
        "localhost:10"
    );

    for (int i = 0; i < numIds; i++) {
      UUID uuid = UUID.randomUUID();
      uuids.add(uuid.toString());
    }

    hasher.updateKeys(servers);
  }

  @Benchmark
  @BenchmarkMode(Mode.AverageTime)
  @OutputTimeUnit(TimeUnit.MICROSECONDS)
  public void hash(Blackhole blackhole)
  {
    for (String uuid : uuids) {
      String server = hasher.findKey(StringUtils.toUtf8(uuid));
      blackhole.consume(server);
    }
  }
}


text:
import math
from common.string import normalize_text
from preprocess.words import stemAndRemoveAccents, towords

def inverseDF(term, index):
	try:
		arg = index.total_records / index.document_frequency(term)
		return math.log(arg) + 1
	except ZeroDivisionError:
		return 0

def tf_idf(term, docID, index, wordsCount):
	idf = inverseDF(term, index)
	tf = index.term_frequency(term, docID, wordsCount)
	return idf * tf

def document_score(terms, docID, index, wordsCount):
	res = 0
	for term in terms:
		res += tf_idf(term, docID, index, wordsCount)
	return res

def score(terms, documents, index, lang):
	for doc in documents:
		doc['score'] = document_score(terms, doc['id'], index, doc['words'])

	rankMetaInfo(terms, documents, lang)
	return documents

def rankMetaInfo(terms, documents, lang):
	for doc in documents:
		title = normalize(doc['title'], lang)
		url = normalize(doc['url'], lang)
		description = normalize(doc['description'], lang)

		for term in terms:
			if term in title or term in url:
				doc['score'] *= 3

			if term in description:
				doc['score'] *= 2

def normalize(text, lang):
	return stemAndRemoveAccents(towords(normalize_text(text)), lang)


text:
from . import exceptions
from .remote_legacy import RemoteLegacy
from .remote_websocket import RemoteWebsocket

class Remote:
    def __init__(self, config):
        if config["method"] == "legacy":
            self.remote = RemoteLegacy(config)
        elif config["method"] == "websocket":
            self.remote = RemoteWebsocket(config)
        else:
            raise exceptions.UnknownMethod()

    def __enter__(self):
        return self.remote.__enter__()

    def __exit__(self, type, value, traceback):
        self.remote.__exit__(type, value, traceback)

    def close(self):
        return self.remote.close()

    def control(self, key):
        return self.remote.control(key)


text:
package design_patterns.creational.abstract_factory;

class MaleAbstractFactory extends AbstractFactory {

  public Product makeGift() {
    return new MaleGiftProduct();
  }

  public Product makePack() {
    return new MalePackProduct();
  }
}


text:
@interface GVDeviceTableViewController : PFQueryTableViewController

@end


text:
require 'carmen'

module Spree
  module BaseHelper
    def link_to_cart(text = nil)
      text = text ? h(text) : t('spree.cart')
      css_class = nil

      if current_order.nil? || current_order.item_count.zero?
        text = "#{text}: (#{t('spree.empty')})"
        css_class = 'empty'
      else
        text = "#{text}: (#{current_order.item_count})  #{current_order.display_total.to_html}"
        css_class = 'full'
      end

      link_to text.html_safe, spree.cart_path, class: "cart-info #{css_class}"
    end

    # human readable list of variant options
    def variant_options(variant, _options = {})
      variant.options_text
    end

    def meta_data
      object = instance_variable_get('@' + controller_name.singularize)
      meta = {}

      if object.is_a? ActiveRecord::Base
        meta[:keywords] = object.meta_keywords if object[:meta_keywords].present?
        meta[:description] = object.meta_description if object[:meta_description].present?
      end

      if meta[:description].blank? && object.is_a?(Spree::Product)
        meta[:description] = truncate(strip_tags(object.description), length: 160, separator: ' ')
      end

      if meta[:keywords].blank? || meta[:description].blank?
        meta.reverse_merge!({
          keywords: current_store.meta_keywords,
          description: current_store.meta_description
        })
      end
      meta
    end

    def meta_data_tags
      meta_data.map do |name, content|
        tag('meta', name: name, content: content)
      end.join("\n")
    end

    def body_class
      @body_class ||= content_for?(:sidebar) ? 'two-col' : 'one-col'
      @body_class
    end

    def logo(image_path = Spree::Config[:logo])
      link_to image_tag(image_path), spree.root_path
    end

    def flash_messages(opts = {})
      ignore_types = ["order_completed"].concat(Array(opts[:ignore_types]).map(&:to_s) || [])

      flash.each do |msg_type, text|
        unless ignore_types.include?(msg_type)
          concat(content_tag(:div, text, class: "flash #{msg_type}"))
        end
      end
      nil
    end

    def taxon_breadcrumbs(taxon, separator = ' » ', breadcrumb_class = 'inline')
      return '' if current_page?('/') || taxon.nil?

      crumbs = [[t('spree.home'), spree.root_path]]

      crumbs << [t('spree.products'), products_path]
      if taxon
        crumbs += taxon.ancestors.collect { |ancestor| [ancestor.name, spree.nested_taxons_path(ancestor.permalink)] } unless taxon.ancestors.empty?
        crumbs << [taxon.name, spree.nested_taxons_path(taxon.permalink)]
      end

      separator = raw(separator)

      items = crumbs.each_with_index.collect do |crumb, index|
        content_tag(:li, itemprop: 'itemListElement', itemscope: '', itemtype: 'https://schema.org/ListItem') do
          link_to(crumb.last, itemprop: 'item') do
            content_tag(:span, crumb.first, itemprop: 'name') + tag('meta', { itemprop: 'position', content: (index + 1).to_s }, false, false)
          end + (crumb == crumbs.last ? '' : separator)
        end
      end

      content_tag(:nav, content_tag(:ol, raw(items.map(&:mb_chars).join), class: breadcrumb_class, itemscope: '', itemtype: 'https://schema.org/BreadcrumbList'), id: 'breadcrumbs', class: 'sixteen columns')
    end

    def taxons_tree(root_taxon, current_taxon, max_level = 1)
      return '' if max_level < 1 || root_taxon.children.empty?
      content_tag :ul, class: 'taxons-list' do
        taxons = root_taxon.children.map do |taxon|
          css_class = (current_taxon && current_taxon.self_and_ancestors.include?(taxon)) ? 'current' : nil
          content_tag :li, class: css_class do
           link_to(taxon.name, seo_url(taxon)) +
             taxons_tree(taxon, current_taxon, max_level - 1)
          end
        end
        safe_join(taxons, "\n")
      end
    end

    def available_countries(restrict_to_zone: Spree::Config[:checkout_zone])
      countries = Spree::Country.available(restrict_to_zone: restrict_to_zone)

      country_names = Carmen::Country.all.map do |country|
        [country.code, country.name]
      end.to_h

      country_names.update I18n.t('spree.country_names', default: {}).stringify_keys

      countries.collect do |country|
        country.name = country_names.fetch(country.iso, country.name)
        country
      end.sort_by { |country| country.name.parameterize }
    end

    def seo_url(taxon)
      spree.nested_taxons_path(taxon.permalink)
    end

    def display_price(product_or_variant)
      product_or_variant.price_for(current_pricing_options).to_html
    end

    def pretty_time(time, format = :long)
      I18n.l(time, format: :"solidus.#{format}")
    end

    def link_to_tracking(shipment, options = {})
      return unless shipment.tracking && shipment.shipping_method

      if shipment.tracking_url
        link_to(shipment.tracking, shipment.tracking_url, options)
      else
        content_tag(:span, shipment.tracking)
      end
    end

    def plural_resource_name(resource_class)
      resource_class.model_name.human(count: Spree::I18N_GENERIC_PLURAL)
    end
  end
end


text:
import "source-map-support/register";

import uuids from "../noblePeripheral/common-uuids";

/**
 * @class
 */
export abstract class Update {
  constructor (type: string, time: number) {
    this._type = type;
    this._time = new Date(time);
  }

  private _type: string;
  private _time: Date;

  get time () { return this._time; }

  get type () { return this._type; }

  public abstract accept(vistor: any): any;
}

/**
 * @class
 */
export class ClickUpdate extends Update {
  constructor(down: boolean) {
    super("click", Date.now());
    this._down = down;
  }

  private _down: boolean;

  get down () { return this._down; }

  public accept(vistor: any) {
    return vistor.withClick(this);
  }
}

/**
 * @class
 */
export class TurnUpdate extends Update {
  constructor(offset: number) {
    super("turn", Date.now());
    this._offset = offset;
  }

  private _offset: number;

  get offset () { return this._offset; }

  public accept(vistor: any) {
    return vistor.withTurn(this);
  }
}

/**
 * @class
 */
export class SwipeUpdate extends Update {
  constructor(direction: string) {
    super("swipe", Date.now());
    this._direction = direction;
  }

  private _direction: string;

  get direction () { return this._direction; }

  public accept(vistor: any) {
    return vistor.withSwipe(this);
  }
}

export class FlyUpdate extends Update {
    constructor(direction: string, speed: number) {
    super("fly", Date.now());
    this._direction = direction;
    this._speed = speed;
  }

  private _direction: string;
  private _speed: number;

  get direction () { return this._direction; }
  get speed () { return this._speed; }

  public accept(vistor: any) {
    return vistor.withSwipe(this);
  }
}

/**
 * parses the updates buffer representation, and returns an update
 * see here https://cdn-images-2.medium.com/max/1600/1*lL52VX2WKOUu1ezul4FQrQ.jpeg
 *
 * @param {UUID} (a uuid string)
 * @param {Buffer} (a node buffer)
 * @return Update
 */
export function updateFactory(characteristicUUID: string, buffer: Buffer): Update {
  switch (characteristicUUID) {
    case uuids.characteristics.turn:
      const offset = buffer.readInt16LE(0);
      return new TurnUpdate(offset);
    case uuids.characteristics.swipe:
      let swipeDirection: string;
      switch (buffer.readInt8(0)) {
        case 0: swipeDirection = "l"; break;
        case 1: swipeDirection = "r"; break;
        case 2: swipeDirection = "u"; break;
        case 3: swipeDirection = "d"; break;
      }
      return new SwipeUpdate(swipeDirection);
    case uuids.characteristics.click:
      const down = !!buffer.readInt8(0);
      return new ClickUpdate(down);
    case uuids.characteristics.fly:
      // FlyUpdate was added from documentation, but I have no real device to test with
      let flyDirection: string;
      switch (buffer.readInt8(0)) {
        case 0: flyDirection = "l"; break;
        case 1: flyDirection = "r"; break;
        case 2: flyDirection = "b"; break;
        case 3: flyDirection = "t"; break;

        //TODO check up/down
        case 4: flyDirection = "u"; break;
        case 5: flyDirection = "d"; break;
      }
      const speed = buffer.readInt8(1);
      return new FlyUpdate(flyDirection, speed);
    default:
      throw new Error(`unidenfied update '${characteristicUUID}'`);
  }
}


text:
// Implementation of stack backed by our singly linked list.
// Used by red-black tree during in-order traversal.
// Structure is not thread safe.
// References: http://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29

package linkedliststack

import (
	"fmt"
	"github.com/emirpasic/gods/lists/singlylinkedlist"
	"github.com/emirpasic/gods/stacks"
	"strings"
)

func assertInterfaceImplementation() {
	var _ stacks.Interface = (*Stack)(nil)
}

type Stack struct {
	list *singlylinkedlist.List
}

// Instantiates a new empty stack
func New() *Stack {
	return &Stack{list: &singlylinkedlist.List{}}
}

// Pushes a value onto the top of the stack
func (stack *Stack) Push(value interface{}) {
	stack.list.Prepend(value)
}

// Pops (removes) top element on stack and returns it, or nil if stack is empty.
// Second return parameter is true, unless the stack was empty and there was nothing to pop.
func (stack *Stack) Pop() (value interface{}, ok bool) {
	value, ok = stack.list.Get(0)
	stack.list.Remove(0)
	return
}

// Returns top element on the stack without removing it, or nil if stack is empty.
// Second return parameter is true, unless the stack was empty and there was nothing to peek.
func (stack *Stack) Peek() (value interface{}, ok bool) {
	return stack.list.Get(0)
}

// Returns true if stack does not contain any elements.
func (stack *Stack) Empty() bool {
	return stack.list.Empty()
}

// Returns number of elements within the stack.
func (stack *Stack) Size() int {
	return stack.list.Size()
}

// Removes all elements from the stack.
func (stack *Stack) Clear() {
	stack.list.Clear()
}

// Returns all elements in the stack (LIFO order).
func (stack *Stack) Values() []interface{} {
	return stack.list.Values()
}

func (stack *Stack) String() string {
	str := "LinkedListStack\n"
	values := []string{}
	for _, value := range stack.list.Values() {
		values = append(values, fmt.Sprintf("%v", value))
	}
	str += strings.Join(values, ", ")
	return str
}


text:
namespace lldb_private {
namespace process_linux {

class NativeProcessLinux;

class NativeRegisterContextLinux_mips64 : public NativeRegisterContextLinux {
public:
  NativeRegisterContextLinux_mips64(const ArchSpec &target_arch,
                                    NativeThreadProtocol &native_thread);

  uint32_t GetRegisterSetCount() const override;

  lldb::addr_t GetPCfromBreakpointLocation(
      lldb::addr_t fail_value = LLDB_INVALID_ADDRESS) override;

  lldb::addr_t GetWatchpointHitAddress(uint32_t wp_index) override;

  const RegisterSet *GetRegisterSet(uint32_t set_index) const override;

  Status ReadRegister(const RegisterInfo *reg_info,
                      RegisterValue &reg_value) override;

  Status WriteRegister(const RegisterInfo *reg_info,
                       const RegisterValue &reg_value) override;

  Status ReadAllRegisterValues(lldb::DataBufferSP &data_sp) override;

  Status WriteAllRegisterValues(const lldb::DataBufferSP &data_sp) override;

  Status ReadCP1();

  Status WriteCP1();

  uint8_t *ReturnFPOffset(uint8_t reg_index, uint32_t byte_offset);

  Status IsWatchpointHit(uint32_t wp_index, bool &is_hit) override;

  Status GetWatchpointHitIndex(uint32_t &wp_index,
                               lldb::addr_t trap_addr) override;

  Status IsWatchpointVacant(uint32_t wp_index, bool &is_vacant) override;

  bool ClearHardwareWatchpoint(uint32_t wp_index) override;

  Status ClearAllHardwareWatchpoints() override;

  Status SetHardwareWatchpointWithIndex(lldb::addr_t addr, size_t size,
                                        uint32_t watch_flags,
                                        uint32_t wp_index);

  uint32_t SetHardwareWatchpoint(lldb::addr_t addr, size_t size,
                                 uint32_t watch_flags) override;

  lldb::addr_t GetWatchpointAddress(uint32_t wp_index) override;

  uint32_t NumSupportedHardwareWatchpoints() override;

  static bool IsMSAAvailable();

protected:
  Status Read_SR_Config(uint32_t offset, const char *reg_name, uint32_t size,
                        RegisterValue &value);

  Status ReadRegisterRaw(uint32_t reg_index, RegisterValue &value) override;

  Status WriteRegisterRaw(uint32_t reg_index,
                          const RegisterValue &value) override;

  Status DoReadWatchPointRegisterValue(lldb::tid_t tid, void *watch_readback);

  Status DoWriteWatchPointRegisterValue(lldb::tid_t tid, void *watch_readback);

  bool IsFR0();

  bool IsFRE();

  bool IsFPR(uint32_t reg_index) const;

  bool IsMSA(uint32_t reg_index) const;

  void *GetGPRBuffer() override { return &m_gpr; }

  void *GetFPRBuffer() override { return &m_fpr; }

  size_t GetFPRSize() override { return sizeof(FPR_linux_mips); }

private:
  // Info about register ranges.
  struct RegInfo {
    uint32_t num_registers;
    uint32_t num_gpr_registers;
    uint32_t num_fpr_registers;

    uint32_t last_gpr;
    uint32_t first_fpr;
    uint32_t last_fpr;
    uint32_t first_msa;
    uint32_t last_msa;
  };

  RegInfo m_reg_info;

  GPR_linux_mips m_gpr;

  FPR_linux_mips m_fpr;

  MSA_linux_mips m_msa;

  lldb::addr_t hw_addr_map[MAX_NUM_WP];

  struct iovec m_iovec;
};

} // namespace process_linux
} // namespace lldb_private

#endif // #ifndef lldb_NativeRegisterContextLinux_mips64_h

#endif // defined (__mips__)


text:
require 'spec_helper'

describe Travis::Api::V1::Http::Repositories do
  include Travis::Testing::Stubs, Support::Formats

  let(:data) { Travis::Api::V1::Http::Repositories.new([repository]).data }

  it 'data' do
    data.first.should == {
      'id' => repository.id,
      'slug' => 'svenfuchs/minimal',
      'description' => 'the repo description',
      'last_build_id' => repository.last_build_id,
      'last_build_number' => repository.last_build_number,
      'last_build_started_at' => json_format_time(Time.now.utc - 1.minute),
      'last_build_finished_at' => json_format_time(Time.now.utc),
      'last_build_status' => repository.last_build_result, # still here for backwards compatibility
      'last_build_result' => repository.last_build_result,
      'last_build_language' => 'ruby',
      'last_build_duration' => 60
    }
  end
end


text:
package controllers;

import play.mvc.Controller;
import play.mvc.Result;
import views.html.about;

public class About extends Controller {

  public Result about() {
    return ok(about.render());
  }

}


text:
package org.apache.ignite.spi.communication.tcp.internal;

import java.nio.channels.SelectableChannel;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.ignite.internal.util.nio.GridCommunicationClient;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;

/**
 * Callback that is intended to be executed after timeout on handshake.
 */
public class HandshakeTimeoutObject implements Runnable {
    /** Object which used for connection. */
    private final Object connectionObj;

    /** Done. */
    private final AtomicBoolean done = new AtomicBoolean();

    /**
     * @param connectionObj Client.
     */
    public HandshakeTimeoutObject(Object connectionObj) {
        assert connectionObj != null;
        assert connectionObj instanceof GridCommunicationClient || connectionObj instanceof SelectableChannel;

        this.connectionObj = connectionObj;
    }

    /**
     * @return {@code True} if object has not yet been timed out.
     */
    public boolean cancel() {
        return done.compareAndSet(false, true);
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(HandshakeTimeoutObject.class, this);
    }

    /** {@inheritDoc} */
    @Override public void run() {
        if (done.compareAndSet(false, true)) {
            // Close socket - timeout occurred.
            if (connectionObj instanceof GridCommunicationClient)
                ((GridCommunicationClient)connectionObj).forceClose();
            else
                U.closeQuiet((AutoCloseable)connectionObj);
        }
    }
}


text:
import Route    from '@ember/routing/route'
import query    from 'dummy/graph/queries/users'

export default Route.extend({
  model() {
    let variables =  {page: 1, size: 10}
    return this.store.graphQuery({query, variables})
  }
})


text:
<?php

/**
 * Date: 24/03/2017
 * Time: 15:38
 */

namespace Magecon\Cli\Tasks;

use Magecon\Cms\Model\Page;
use Phalcon\Cli\Task;

/**
 * Automatically take model metadata and update table
 * Command:
 * php run migration:action
 * Class MigrationTask
 * @package Magecon\Cli
 */

class MigrationTask extends Task {

    /**
     *
     */
    public function mainAction() {
        $block = new Page();
        /* @var $blockMeta \Phalcon\Mvc\Model\MetaData\Redis */
        $blockMeta = $block->getModelsMetaData();
        $metaData = $blockMeta->readMetaData($block);
    }

    public function updateAction() {
        echo "in update action\n";
    }
}


text:
$(document).ready(function () {
    $('.tooltipped').tooltip({ delay: 50 });
});

function clearTooltips() {
    $('.tooltipped').tooltip('remove');
}

function reloadToolTips() {
    $('.tooltipped').tooltip({ delay: 50 });

    $('.btn-add-comment').on('click', () => {
        $('.comment-box-textarea').focus();
    })
}

function commentDeleted(args) {
    notify('success', 'Comment deleted!');

    $.validator.unobtrusive.parse('#comment-box-' + args);

    var selector = 'comments-count-' + args;
    var commentsCount = $('#' + selector).html();
    $('#' + selector).html(+commentsCount - 1);

    $('.comment-box-textarea').on('focus', () => {
        $('.btn-submit-box').show();
    })
}

function changed() {
    $('#searchForm').submit();
}

function likeImage(args) {
    $('.btn-like-image').addClass('disabled');

    var selector = $(args).attr('data-target');
    var likesCount = $('#' + selector).html();
    $('#' + selector).html(+likesCount + 1);

    notify('success', 'Image liked!');

    setTimeout(() => {
        $('.btn-like-image').removeClass('disabled');
    }, 2000);
}

function unlikeImage(args) {
    $('.btn-like-image').addClass('disabled');

    var selector = $(args).attr('data-target');
    var likesCount = $('#' + selector).html();
    $('#' + selector).html(+likesCount - 1);

    notify('success', 'Like removed!');

    setTimeout(() => {
        $('.btn-like-image').removeClass('disabled');
    }, 2000);
}

function commentSubmitted(args) {
    $('.comment-box-textarea').val('');
    notify('success', 'Your comment has been submitted!')

    $.validator.unobtrusive.parse('#comment-box-' + args);

    var selector = 'comments-count-' + args;
    var commentsCount = $('#' + selector).html();
    $('#' + selector).html(+commentsCount + 1);

    $('.comment-box-textarea').on('focus', () => {
        $('.btn-submit-box').show();
    })
}

function populateModal(selector) {
    $('#' + selector).submit();
}

$('.btn-add-comment').on('click', () => {
    $('.comment-box-textarea').focus();
    $('.btn-submit-box').show();
})

$('.comment-box-textarea').on('focus', () => {
    $('.btn-submit-box').show();
})

function rebindCommentEvent(args) {
    $.validator.unobtrusive.parse('#comment-box-' + args);

    $('.btn-add-comment').on('click', () => {
        $('.comment-box-textarea').focus();
        $('.btn-submit-box').show();
    });

    $('.comment-box-textarea').on('focus', () => {
        $('.btn-submit-box').show();
    });
}

$('body').keyup((ev) => {
    if ($('#image-details').hasClass('in')) {
        if (ev.which == 37) {
            $('#btn-left').click();
        } else if (ev.which == 39) {
            $('#btn-right').click();
        }
        ev.preventDefault();
    }
});

$('#image-details').on('hidden.bs.modal', () => {
    $('#image-details').html('');
})


text:
class Chef
  class Recipe
    class AptPackageExtras
      def self.virtual_package?(package_name)
        # This functionality is based on that in the apt package provider
        # See https://github.com/chef/chef/blob/master/lib/chef/provider/package/apt.rb
        # The provider functionality isn't easily exposed for consumption in other recipes

        policy = Mixlib::ShellOut.new("apt-cache policy '#{package_name}'")
        policy.run_command
        policy.error!

        policy.stdout.each_line do |line|
          case line
          when /^\s{2}Candidate: (.+)$/
            candidate_version = Regexp.last_match[1]
            if candidate_version == '(none)'
              # This may not be an appropriate assumption, but is the same as that used by the apt package provider
              Chef::Log.info("#{package_name} is a virtual package, no candidate version.")
              return true
            else
              Chef::Log.info("#{package_name} is not a virtual package, candidate version is #{candidate_version}.")
              return false
            end
          end
        end
      end

      def self.get_providing_packages(package_name)
        # This functionality is based on that in the apt package provider
        # See https://github.com/chef/chef/blob/master/lib/chef/provider/package/apt.rb
        # The provider functionality isn't easily exposed for consumption in other recipes

        unless virtual_package?(package_name)
          raise "#{package_name} is not a virtual package, cannot remove providing packages."
        end

        showpkg = Mixlib::ShellOut.new("apt-cache showpkg '#{package_name}'")
        showpkg.run_command
        showpkg.error!

        providers = {}

        # Disable rubocop warning to get a build
        showpkg.stdout.rpartition(/Reverse Provides: ?#{$/}/)[2].each_line do |line| # rubocop:disable Style/SpecialGlobalVars
          provider, version = line.split
          providers[provider] = version
          Chef::Log.info("Package #{provider} #{version} provides virtual package #{package_name}")
        end

        if providers.length <= 0
          Chef::Log.warn("There are no providing packages for virtual package #{package_name}.")
        end

        providers.keys
      end
    end
  end
end


text:
@implementation CBAScrollView

#pragma mark - Initialization

-(id) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];

    self.scrollEnabled = YES;
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    self.delaysContentTouches = NO;

    return self;
}

#pragma mark - Lifecycle

-(BOOL) touchesShouldCancelInContentView:(UIView *)view {
    if( [view isKindOfClass:UIControl.class] ){
        return YES;
    }

    return [super touchesShouldCancelInContentView:view];
}

@end


text:
export default function processResponse(response) {
  let isOk = response.ok;

  return response
    .text()
    .then(
      body => {
        let jsonBody;

        try {
          jsonBody = JSON.parse(body);
        } catch (error) {
          if (isOk) {
            isOk = false;
          }
        }
        console.log(jsonBody, response);

        if (isOk) {
          return jsonBody;
        }

        throw new Error({ ...jsonBody, statusCode: response.status });
      }
    );
}


text:
var webdriver = require('selenium-webdriver');
var Q = require("q");
var util = require("util");
var events = require("events");
var mapToJson = require("../util/mapToJson");

webdriver.promise.USE_PROMISE_MANAGER = false;

var WebdriverLauncher = module.exports = function() {};

util.inherits(WebdriverLauncher, events.EventEmitter);

WebdriverLauncher.prototype.start = function(param) {
    var self = this;
    var config = param.config;
    var variables = param.variables;

    var configError = "";
    if (!config.capabilities || !config.capabilities.browserName) {
        configError += "Missing browserName capability. ";
    }
    if (configError) {
        self.emit("log", ["error", configError]);
        self.emit("disable");
        self.emit("exit");
        return;
    }

    // building the driver:
    var builder = new webdriver.Builder();
    builder.disableEnvironmentOverrides();
    if (config.server) {
        builder.usingServer(config.server);
    }
    builder.withCapabilities(variables.recursivelyReplace(config.capabilities));

    self.url = variables.replace("${ATTESTER-URL}");
    self.keepAliveDelay = config.keepAliveDelay;
    self.driver = builder.build();

    // starting the browser:
    Q(self.driver.getSession())
        .then(self.onReceivedSession.bind(self))
        .then(self.beginConnection.bind(self))
        .catch(self.onWebdriverError.bind(self))
        .then(function() {
            if (!self.shouldEnd) {
                self.stopPromise = Q.Promise(function(resolve) {
                    self.stopResolve = resolve;
                });
                self.keepConnection();
                return self.stopPromise;
            }
        })
        .finally(self.endConnection.bind(self)).finally(function() {
            self.driver = null;
            self.emit("exit");
        });
};

WebdriverLauncher.prototype.onReceivedSession = function(session) {
    this.emit("log", ["info", "Started session %s", session.getId()]);
    this.emit("log", ["debug", "Capabilities: %j", mapToJson(session.getCapabilities())]);
};

WebdriverLauncher.prototype.beginConnection = function() {
    return this.driver.get(this.url);
};

WebdriverLauncher.prototype.keepConnection = function() {
    this.keepAliveCallback();
};

WebdriverLauncher.prototype.keepAlive = function() {
    this.keepAliveTimeout = null;
    if (!this.shouldEnd) {
        this.emit("log", ["debug", "Sending keep-alive command (getCurrentUrl)"]);
        Q(this.driver.getCurrentUrl()).then(this.keepAliveCallback.bind(this), this.onWebdriverError.bind(this));
    }
};

WebdriverLauncher.prototype.keepAliveCallback = function() {
    if (!this.shouldEnd && this.keepAliveDelay > -1) {
        this.keepAliveTimeout = setTimeout(this.keepAlive.bind(this), this.keepAliveDelay);
    }
};

WebdriverLauncher.prototype.endConnection = function() {
    if (this.keepAliveTimeout) {
        clearTimeout(this.keepAliveTimeout);
        this.keepAliveTimeout = null;
    }
    return this.driver.quit();
};

WebdriverLauncher.prototype.stop = function() {
    this.shouldEnd = true;
    var stopResolve = this.stopResolve;
    if (stopResolve) {
        this.stopResolve = null;
        stopResolve();
    }
};

WebdriverLauncher.prototype.onWebdriverError = function(error) {
    this.emit("log", ["error", "Error in webdriver: %s", error + ""]);
    this.stop();
};