func (svc *Service) RefetchHost(ctx context.Context, id uint) error {
	if !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) {
		if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {
			return err
		}

		host, err := svc.ds.HostLite(ctx, id)
		if err != nil {
			return ctxerr.Wrap(ctx, err, "find host for refetch")
		}

		// We verify fleet.ActionRead instead of fleet.ActionWrite because we want to allow
		// observers to be able to refetch hosts.
		if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {
			return err
		}
	}

	if err := svc.ds.UpdateHostRefetchRequested(ctx, id, true); err != nil {
		return ctxerr.Wrap(ctx, err, "save host")
	}

	return nil
}


func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) {
	params := k.GetParams(ctx)
	expEpochID := k.GetEpochIdentifier(ctx)
	if epochIdentifier != expEpochID {
		return
	}

	// mint coins, update supply
	epochMintProvision, found := k.GetEpochMintProvision(ctx)
	if !found {
		panic("the epochMintProvision was not found")
	}

	mintedCoin := sdk.NewCoin(params.MintDenom, epochMintProvision.TruncateInt())
	if err := k.MintAndAllocateInflation(ctx, mintedCoin); err != nil {
		panic(err)
	}

	// check if a period is over. If it's completed, update period, and epochMintProvision
	period := k.GetPeriod(ctx)
	epochsPerPeriod := k.GetEpochsPerPeriod(ctx)

	newProvision := epochMintProvision

	// current epoch number needs to be within range for the period
	// Given, epochNumber = 1, period = 0, epochPerPeriod = 365
	// 1 - 365 * 0 < 365 --- nothing to do here
	// Given, epochNumber = 731, period = 1, epochPerPeriod = 365
	// 731 - 1 * 365 > 365 --- a period has passed! we change the epochMintProvision and set a new period
	if epochNumber-epochsPerPeriod*int64(period) > epochsPerPeriod {
		period++
		k.SetPeriod(ctx, period)
		period = k.GetPeriod(ctx)
		bondedRatio := k.stakingKeeper.BondedRatio(ctx)
		newProvision = types.CalculateEpochMintProvision(
			params,
			period,
			epochsPerPeriod,
			bondedRatio,
		)
		k.SetEpochMintProvision(ctx, newProvision)
	}

	ctx.EventManager().EmitEvent(
		sdk.NewEvent(
			types.EventTypeMint,
			sdk.NewAttribute(types.AttributeEpochNumber, fmt.Sprintf("%d", epochNumber)),
			sdk.NewAttribute(types.AttributeKeyEpochProvisions, newProvision.String()),
			sdk.NewAttribute(sdk.AttributeKeyAmount, mintedCoin.Amount.String()),
		),
	)
}


func bindMountDeviceNode(dest string, node *devices.Device) error {
	f, err := os.Create(dest)
	if err != nil && !os.IsExist(err) {
		return err
	}
	if f != nil {
		f.Close()
	}
	return unix.Mount(node.Path, dest, "bind", unix.MS_BIND, "")
}


	if rf, ok := ret.Get(0).(func(string, kube.ResourceKey, func(v1alpha1.ResourceNode, string)) error); ok {
		r0 = rf(server, key, action)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}


func (svc *Service) GetGlobalScheduledQueries(ctx context.Context, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionRead); err != nil {
		return nil, err
	}

	gp, err := svc.ds.EnsureGlobalPack(ctx)
	if err != nil {
		return nil, err
	}

	return svc.ds.ListScheduledQueriesInPackWithStats(ctx, gp.ID, opts)
}


func testExternalNameServiceInsecure(namespace string) {
	Specify("external name services work over http", func() {
		t := f.T()

		f.Fixtures.Echo.Deploy(namespace, "ingress-conformance-echo")

		externalNameService := &corev1.Service{
			ObjectMeta: metav1.ObjectMeta{
				Namespace: namespace,
				Name:      "external-name-service",
			},
			Spec: corev1.ServiceSpec{
				Type:         corev1.ServiceTypeExternalName,
				ExternalName: "ingress-conformance-echo." + namespace,
				Ports: []corev1.ServicePort{
					{
						Name: "http",
						Port: 80,
					},
				},
			},
		}
		require.NoError(t, f.Client.Create(context.TODO(), externalNameService))

		p := &contourv1.HTTPProxy{
			ObjectMeta: metav1.ObjectMeta{
				Namespace: namespace,
				Name:      "external-name-proxy",
			},
			Spec: contourv1.HTTPProxySpec{
				VirtualHost: &contourv1.VirtualHost{
					Fqdn: "externalnameservice.projectcontour.io",
				},
				Routes: []contourv1.Route{
					{
						Services: []contourv1.Service{
							{
								Name: externalNameService.Name,
								Port: 80,
							},
						},
						RequestHeadersPolicy: &contourv1.HeadersPolicy{
							Set: []contourv1.HeaderValue{
								{
									Name:  "Host",
									Value: externalNameService.Spec.ExternalName,
								},
							},
						},
					},
				},
			},
		}
		f.CreateHTTPProxyAndWaitFor(p, httpProxyValid)

		res, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{
			Host:      p.Spec.VirtualHost.Fqdn,
			Condition: e2e.HasStatusCode(200),
		})
		require.Truef(t, ok, "expected 200 response code, got %d", res.StatusCode)
	})
}


func (b *Builder) buildControlPlanePathRoute(path string, protected bool) (*envoy_config_route_v3.Route, error) {
	r := &envoy_config_route_v3.Route{
		Name: "pomerium-path-" + path,
		Match: &envoy_config_route_v3.RouteMatch{
			PathSpecifier: &envoy_config_route_v3.RouteMatch_Path{Path: path},
		},
		Action: &envoy_config_route_v3.Route_Route{
			Route: &envoy_config_route_v3.RouteAction{
				ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
					Cluster: httpCluster,
				},
			},
		},
	}
	if !protected {
		r.TypedPerFilterConfig = map[string]*any.Any{
			"envoy.filters.http.ext_authz": disableExtAuthz,
		}
	}
	return r, nil
}


func getClaimsFromToken(r *http.Request, token string) (map[string]interface{}, error) {


func (AppModuleBasic) ConsensusVersion() uint64 {
	return 1
}


func TestDoesPolicySignatureV2Match(t *testing.T) {
	obj, fsDir, err := prepareFS()
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(fsDir)
	if err = newTestConfig(globalMinioDefaultRegion, obj); err != nil {
		t.Fatal(err)
	}

	creds := globalActiveCred
	policy := "policy"
	testCases := []struct {
		accessKey string
		policy    string
		signature string
		errCode   APIErrorCode
	}{
		{"invalidAccessKey", policy, calculateSignatureV2(policy, creds.SecretKey), ErrInvalidAccessKeyID},
		{creds.AccessKey, policy, calculateSignatureV2("random", creds.SecretKey), ErrSignatureDoesNotMatch},
		{creds.AccessKey, policy, calculateSignatureV2(policy, creds.SecretKey), ErrNone},
	}
	for i, test := range testCases {
		formValues := make(http.Header)
		formValues.Set("Awsaccesskeyid", test.accessKey)
		formValues.Set("Signature", test.signature)
		formValues.Set("Policy", test.policy)
		errCode := doesPolicySignatureV2Match(formValues)
		if errCode != test.errCode {
			t.Fatalf("(%d) expected to get %s, instead got %s", i+1, niceError(test.errCode), niceError(errCode))
		}
	}
}


func queryMatches(rp *arrayPathResult, value Result) bool {
	rpv := rp.query.value
	if len(rpv) > 0 && rpv[0] == '~' {
		// convert to bool
		rpv = rpv[1:]
		if value.Bool() {
			value = Result{Type: True}
		} else {
			value = Result{Type: False}
		}
	}
	if !value.Exists() {
		return false
	}
	if rp.query.op == "" {
		// the query is only looking for existence, such as:
		//   friends.#(name)
		// which makes sure that the array "friends" has an element of
		// "name" that exists
		return true
	}
	switch value.Type {
	case String:
		switch rp.query.op {
		case "=":
			return value.Str == rpv
		case "!=":
			return value.Str != rpv
		case "<":
			return value.Str < rpv
		case "<=":
			return value.Str <= rpv
		case ">":
			return value.Str > rpv
		case ">=":
			return value.Str >= rpv
		case "%":
			return match.Match(value.Str, rpv)
		case "!%":
			return !match.Match(value.Str, rpv)
		}
	case Number:
		rpvn, _ := strconv.ParseFloat(rpv, 64)
		switch rp.query.op {
		case "=":
			return value.Num == rpvn
		case "!=":
			return value.Num != rpvn
		case "<":
			return value.Num < rpvn
		case "<=":
			return value.Num <= rpvn
		case ">":
			return value.Num > rpvn
		case ">=":
			return value.Num >= rpvn
		}
	case True:
		switch rp.query.op {
		case "=":
			return rpv == "true"
		case "!=":
			return rpv != "true"
		case ">":
			return rpv == "false"
		case ">=":
			return true
		}
	case False:
		switch rp.query.op {
		case "=":
			return rpv == "false"
		case "!=":
			return rpv != "false"
		case "<":
			return rpv == "true"
		case "<=":
			return true
		}
	}
	return false
}


func (c *liveStateCache) IterateHierarchy(server string, key kube.ResourceKey, action func(child appv1.ResourceNode, appName string)) error {
	clusterInfo, err := c.getSyncedCluster(server)
	if err != nil {
		return err
	}
	clusterInfo.IterateHierarchy(key, func(resource *clustercache.Resource, namespaceResources map[kube.ResourceKey]*clustercache.Resource) {
		action(asResourceNode(resource), getApp(resource, namespaceResources))
	})
	return nil
}


func TestAuthorizeTeamPacks(t *testing.T) {
	t.Parallel()

	runTestCases(t, []authTestCase{
		// Team maintainer can read packs of the team.
		{
			user: test.UserTeamMaintainerTeam1,
			object: &fleet.Pack{
				TeamIDs: []uint{1},
			},
			action: read,
			allow:  true,
		},
		// Team observer cannot read packs of the team.
		{
			user: test.UserTeamObserverTeam1TeamAdminTeam2,
			object: &fleet.Pack{
				TeamIDs: []uint{1},
			},
			action: read,
			allow:  false,
		},
		// Team observer cannot write packs of the team.
		{
			user: test.UserTeamObserverTeam1TeamAdminTeam2,
			object: &fleet.Pack{
				TeamIDs: []uint{1},
			},
			action: write,
			allow:  false,
		},
		// Members of a team cannot read packs of another team.
		{
			user: test.UserTeamAdminTeam1,
			object: &fleet.Pack{
				TeamIDs: []uint{2},
			},
			action: read,
			allow:  false,
		},
		// Members of a team cannot read packs of another team.
		{
			user: test.UserTeamAdminTeam1,
			object: &fleet.Pack{
				TeamIDs: []uint{2},
			},
			action: read,
			allow:  false,
		},
		// Team maintainers can read global packs.
		{
			user:   test.UserTeamMaintainerTeam1,
			object: &fleet.Pack{},
			action: read,
			allow:  true,
		},
		// Team admins can read global packs.
		{
			user:   test.UserTeamAdminTeam1,
			object: &fleet.Pack{},
			action: read,
			allow:  true,
		},
		// Team admins cannot write global packs.
		{
			user:   test.UserTeamAdminTeam1,
			object: &fleet.Pack{},
			action: write,
			allow:  false,
		},
	})
}


func (evpool *Pool) flushConsensusBuffer() {
	for _, ev := range evpool.consensusBuffer {
		if err := evpool.addPendingEvidence(ev); err != nil {
			evpool.logger.Error("failed to flush evidence from consensus buffer to pending list: %w", err)
			continue
		}

		evpool.evidenceList.PushBack(ev)
	}
	// reset consensus buffer
	evpool.consensusBuffer = make([]types.Evidence, 0)
}


func (b *Builder) buildControlPlanePrefixRoute(prefix string, protected bool) (*envoy_config_route_v3.Route, error) {
	r := &envoy_config_route_v3.Route{
		Name: "pomerium-prefix-" + prefix,
		Match: &envoy_config_route_v3.RouteMatch{
			PathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{Prefix: prefix},
		},
		Action: &envoy_config_route_v3.Route_Route{
			Route: &envoy_config_route_v3.RouteAction{
				ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
					Cluster: httpCluster,
				},
			},
		},
	}
	if !protected {
		r.TypedPerFilterConfig = map[string]*any.Any{
			"envoy.filters.http.ext_authz": disableExtAuthz,
		}
	}
	return r, nil
}


  getReturnAddressWithDisplayName(identityId) {
    check(identityId, String);
    const identity = this.getIdentity(identityId);
    const displayName = identity.profile.name + " (via " + this.getServerTitle() + ")";

    // First remove any instances of characters that cause trouble for SimpleSmtp. Ideally,
    // we could escape such characters with a backslash, but that does not seem to help here.
    const sanitized = displayName.replace(/"|<|>|\\|\r/g, "");

    return "\"" + sanitized + "\" <" + this.getReturnAddress() + ">";
  },


func TestWrapHandler(t *testing.T) {
	router := http.NewServeMux()

	router.Handle("/", Handler(DocExpansion("none"), DomID("#swagger-ui")))

	w1 := performRequest("GET", "/index.html", router)
	assert.Equal(t, 200, w1.Code)
	assert.Equal(t, w1.Header()["Content-Type"][0], "text/html; charset=utf-8")

	w2 := performRequest("GET", "/doc.json", router)
	assert.Equal(t, 500, w2.Code)

	swag.Register(swag.Name, &mockedSwag{})
	w2 = performRequest("GET", "/doc.json", router)
	assert.Equal(t, 200, w2.Code)
	assert.Equal(t, "application/json; charset=utf-8", w2.Header().Get("content-type"))

	w3 := performRequest("GET", "/favicon-16x16.png", router)
	assert.Equal(t, 200, w3.Code)
	assert.Equal(t, w3.Header()["Content-Type"][0], "image/png")

	w4 := performRequest("GET", "/swagger-ui.css", router)
	assert.Equal(t, 200, w4.Code)
	assert.Equal(t, w4.Header()["Content-Type"][0], "text/css; charset=utf-8")

	w5 := performRequest("GET", "/swagger-ui-bundle.js", router)
	assert.Equal(t, 200, w5.Code)
	assert.Equal(t, w5.Header()["Content-Type"][0], "application/javascript")

	w6 := performRequest("GET", "/notfound", router)
	assert.Equal(t, 404, w6.Code)

	w7 := performRequest("GET", "/", router)
	assert.Equal(t, 301, w7.Code)
}


func (svc Service) ModifyTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint, query fleet.ScheduledQueryPayload) (*fleet.ScheduledQuery, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {
		return nil, err
	}

	gp, err := svc.ds.EnsureTeamPack(ctx, teamID)
	if err != nil {
		return nil, err
	}

	query.PackID = ptr.Uint(gp.ID)

	return svc.unauthorizedModifyScheduledQuery(ctx, scheduledQueryID, query)
}


func (evpool *Pool) CheckEvidence(evList types.EvidenceList) error {
	hashes := make([][]byte, len(evList))
	for idx, ev := range evList {

		ok := evpool.fastCheck(ev)

		if !ok {
			// check that the evidence isn't already committed
			if evpool.isCommitted(ev) {
				return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("evidence was already committed")}
			}

			err := evpool.verify(ev)
			if err != nil {
				return &types.ErrInvalidEvidence{Evidence: ev, Reason: err}
			}

			if err := evpool.addPendingEvidence(ev); err != nil {
				// Something went wrong with adding the evidence but we already know it is valid
				// hence we log an error and continue
				evpool.logger.Error("Can't add evidence to pending list", "err", err, "ev", ev)
			}

			evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev)
		}

		// check for duplicate evidence. We cache hashes so we don't have to work them out again.
		hashes[idx] = ev.Hash()
		for i := idx - 1; i >= 0; i-- {
			if bytes.Equal(hashes[i], hashes[idx]) {
				return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("duplicate evidence")}
			}
		}
	}

	return nil
}


func httpProxyValid(proxy *contourv1.HTTPProxy) bool {
	return proxy != nil && proxy.Status.CurrentStatus == "valid"
}


func (p *GitLabProvider) addGroupsToSession(ctx context.Context, s *sessions.SessionState) {
	// Iterate over projects, check if oauth2-proxy can get project information on behalf of the user
	for _, group := range p.Groups {
		s.Groups = append(s.Groups, fmt.Sprintf("group:%s", group))
	}
}


func (AppModule) ConsensusVersion() uint64 { return 1 }


func (svc *Service) GlobalScheduleQuery(ctx context.Context, sq *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionRead); err != nil {
		return nil, err
	}

	gp, err := svc.ds.EnsureGlobalPack(ctx)
	if err != nil {
		return nil, err
	}
	sq.PackID = gp.ID

	return svc.ScheduleQuery(ctx, sq)
}


func New(
	localGRPCAddress string,
	localHTTPAddress string,
	fileManager *filemgr.Manager,
	reproxyHandler *reproxy.Handler,
) *Builder {
	return &Builder{
		localGRPCAddress: localGRPCAddress,
		localHTTPAddress: localHTTPAddress,
		filemgr:          fileManager,
		reproxy:          reproxyHandler,
	}
}


func (g Grant) ValidateBasic() error {
	if g.Expiration.Unix() < time.Now().Unix() {
		return sdkerrors.Wrap(ErrInvalidExpirationTime, "Time can't be in the past")
	}

	av := g.Authorization.GetCachedValue()
	a, ok := av.(Authorization)
	if !ok {
		return sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expected %T, got %T", (Authorization)(nil), av)
	}
	return a.ValidateBasic()
}


func (svc Service) ListSoftware(ctx context.Context, opt fleet.SoftwareListOptions) ([]fleet.Software, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Software{}, fleet.ActionRead); err != nil {
		return nil, err
	}

	// default sort order to hosts_count descending
	if opt.OrderKey == "" {
		opt.OrderKey = "hosts_count"
		opt.OrderDirection = fleet.OrderDescending
	}
	opt.WithHostCounts = true
	return svc.ds.ListSoftware(ctx, opt)
}


func (svc *Service) GetHost(ctx context.Context, id uint) (*fleet.HostDetail, error) {
	alreadyAuthd := svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken)
	if !alreadyAuthd {
		// First ensure the user has access to list hosts, then check the specific
		// host once team_id is loaded.
		if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {
			return nil, err
		}
	}

	host, err := svc.ds.Host(ctx, id, false)
	if err != nil {
		return nil, ctxerr.Wrap(ctx, err, "get host")
	}

	if !alreadyAuthd {
		// Authorize again with team loaded now that we have team_id
		if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {
			return nil, err
		}
	}

	return svc.getHostDetails(ctx, host)
}


func (app *Configurable) Encrypt(parameters map[string]string) interfaces.AppFunction {
	algorithm, ok := parameters[Algorithm]
	if !ok {
		app.lc.Errorf("Could not find '%s' parameter for Encrypt", Algorithm)
		return nil
	}

	secretPath := parameters[SecretPath]
	secretName := parameters[SecretName]
	encryptionKey := parameters[EncryptionKey]

	// SecretPath & SecretName are optional if EncryptionKey specified
	// EncryptionKey is optional if SecretPath & SecretName are specified

	// If EncryptionKey not specified, then SecretPath & SecretName must be specified
	if len(encryptionKey) == 0 && (len(secretPath) == 0 || len(secretName) == 0) {
		app.lc.Errorf("Could not find '%s' or '%s' and '%s' in configuration", EncryptionKey, SecretPath, SecretName)
		return nil
	}

	// SecretPath & SecretName both must be specified it one of them is.
	if (len(secretPath) != 0 && len(secretName) == 0) || (len(secretPath) == 0 && len(secretName) != 0) {
		app.lc.Errorf("'%s' and '%s' both must be set in configuration", SecretPath, SecretName)
		return nil
	}

	initVector, ok := parameters[InitVector]
	if !ok {
		app.lc.Error("Could not find " + InitVector)
		return nil
	}

	transform := transforms.Encryption{
		EncryptionKey:        encryptionKey,
		InitializationVector: initVector,
		SecretPath:           secretPath,
		SecretName:           secretName,
	}

	switch strings.ToLower(algorithm) {
	case EncryptAES:
		return transform.EncryptWithAES
	default:
		app.lc.Errorf(
			"Invalid encryption algorithm '%s'. Must be '%s'",
			algorithm,
			EncryptAES)
		return nil
	}
}


func getGateway(ctx *statsContext) error {
	gatewayID := helpers.GetGatewayID(&ctx.gatewayStats)
	gw, err := storage.GetAndCacheGateway(ctx.ctx, storage.DB(), gatewayID)
	if err != nil {
		return errors.Wrap(err, "get gateway error")
	}

	ctx.gateway = gw
	return nil
}


func Handler(configFns ...func(*Config)) http.HandlerFunc {
	var once sync.Once

	config := &Config{
		URL:          "doc.json",
		DeepLinking:  true,
		DocExpansion: "list",
		DomID:        "#swagger-ui",
	}
	for _, configFn := range configFns {
		configFn(config)
	}

	// create a template with name
	t := template.New("swagger_index.html")
	index, _ := t.Parse(indexTempl)

	var re = regexp.MustCompile(`^(.*/)([^?].*)?[?|.]*$`)

	return func(w http.ResponseWriter, r *http.Request) {
		matches := re.FindStringSubmatch(r.RequestURI)
		path := matches[2]

		h := swaggerFiles.Handler
		once.Do(func() {
			h.Prefix = matches[1]
		})

		switch filepath.Ext(path) {
		case ".html":
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
		case ".css":
			w.Header().Set("Content-Type", "text/css; charset=utf-8")
		case ".js":
			w.Header().Set("Content-Type", "application/javascript")
		case ".png":
			w.Header().Set("Content-Type", "image/png")
		case ".json":
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
		}

		switch path {
		case "index.html":
			_ = index.Execute(w, config)
		case "doc.json":
			doc, err := swag.ReadDoc()
			if err != nil {
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)

				return
			}
			_, _ = w.Write([]byte(doc))
		case "":
			http.Redirect(w, r, h.Prefix+"index.html", 301)
		default:
			h.ServeHTTP(w, r)
		}
	}
}


func TestMaxDepthValidation(t *testing.T) {
	s, err := schema.ParseSchema(interfaceSimple, false)
	if err != nil {
		t.Fatal(err)
	}

	for _, tc := range []struct {
		name     string
		query    string
		maxDepth int
		expected bool
	}{
		{
			name: "off",
			query: `query Fine {        # depth 0
				characters {         # depth 1
				  id                 # depth 2
				  name               # depth 2
				  friends {          # depth 2
					  id               # depth 3
					  name             # depth 3
				  }
				}
			}`,
			maxDepth: 0,
		}, {
			name: "fields",
			query: `query Fine {        # depth 0
				characters {         # depth 1
				  id                 # depth 2
				  name               # depth 2
				  friends {          # depth 2
					  id               # depth 3
					  name             # depth 3
				  }
				}
			}`,
			maxDepth: 2,
			expected: true,
		}, {
			name: "fragment",
			query: `fragment friend on Character {
				id # depth 6
				name
				friends {
					name # depth 7
				}
			}
			query {        # depth 0
				characters {         # depth 1
				  id                 # depth 2
				  name               # depth 2
				  friends {          # depth 2
					friends {        # depth 3
						friends {    # depth 4
						  friends {  # depth 5
							...friend # depth 6
						  }
						}
					}
				  }
				}
			}`,
			maxDepth: 5,
			expected: true,
		}, {
			name: "inlinefragment",
			query: `query { # depth 0
				characters { # depth 1
				  ... on Droid { # depth 2
					primaryFunction # depth 2
				  }
				}
			  }`,
			maxDepth: 1,
			expected: true,
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			doc, err := query.Parse(tc.query)
			if err != nil {
				t.Fatal(err)
			}

			context := newContext(s, doc, tc.maxDepth)
			op := doc.Operations[0]

			opc := &opContext{context: context, ops: doc.Operations}

			actual := validateMaxDepth(opc, op.Selections, 1)
			if actual != tc.expected {
				t.Errorf("expected %t, actual %t", tc.expected, actual)
			}
		})
	}
}


func (p *GitLabProvider) addProjectsToSession(ctx context.Context, s *sessions.SessionState) {
	// Iterate over projects, check if oauth2-proxy can get project information on behalf of the user
	for _, project := range p.Projects {
		projectInfo, err := p.getProjectInfo(ctx, s, project.Name)

		if err != nil {
			logger.Errorf("Warning: project info request failed: %v", err)
			continue
		}

		if !projectInfo.Archived {
			perms := projectInfo.Permissions.ProjectAccess
			if perms == nil {
				// use group project access as fallback
				perms = projectInfo.Permissions.GroupAccess
				// group project access is not set for this user then we give up
				if perms == nil {
					logger.Errorf("Warning: user %q has no project level access to %s", s.Email, project.Name)
					continue
				}
			}

			if perms != nil && perms.AccessLevel >= project.AccessLevel {
				s.Groups = append(s.Groups, fmt.Sprintf("project:%s", project.Name))
			} else {
				logger.Errorf("Warning: user %q does not have the minimum required access level for project %q", s.Email, project.Name)
			}
		} else {
			logger.Errorf("Warning: project %s is archived", project.Name)
		}

	}

}


func (EmptyEvidencePool) AddEvidenceFromConsensus(evidence types.Evidence) error {
	return nil
}


func Test_buildControlPlanePathRoute(t *testing.T) {
	b := &Builder{filemgr: filemgr.NewManager()}
	route, err := b.buildControlPlanePathRoute("/hello/world", false)
	require.NoError(t, err)
	testutil.AssertProtoJSONEqual(t, `
		{
			"name": "pomerium-path-/hello/world",
			"match": {
				"path": "/hello/world"
			},
			"route": {
				"cluster": "pomerium-control-plane-http"
			},
			"typedPerFilterConfig": {
				"envoy.filters.http.ext_authz": {
					"@type": "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute",
					"disabled": true
				}
			}
		}
	`, route)
}


func (svc Service) DeleteTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint) error {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {
		return err
	}
	return svc.ds.DeleteScheduledQuery(ctx, scheduledQueryID)
}


func (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string) (*AuthenticatorOAuth2IntrospectionResult, bool) {
	if !config.Cache.Enabled {
		return nil, false
	}

	item, found := a.tokenCache.Get(token)
	if !found {
		return nil, false
	}

	i := item.(*AuthenticatorOAuth2IntrospectionResult)
	expires := time.Unix(i.Expires, 0)
	if expires.Before(time.Now()) {
		a.tokenCache.Del(token)
		return nil, false
	}

	return i, true
}


func Test_bindConfig(t *testing.T) {
	ctx, clearTimeout := context.WithTimeout(context.Background(), time.Second*10)
	defer clearTimeout()

	b := New("local-grpc", "local-http", filemgr.NewManager(), nil)
	t.Run("no bind config", func(t *testing.T) {
		cluster, err := b.buildPolicyCluster(ctx, &config.Options{}, &config.Policy{
			From: "https://from.example.com",
			To:   mustParseWeightedURLs(t, "https://to.example.com"),
		})
		assert.NoError(t, err)
		assert.Nil(t, cluster.UpstreamBindConfig)
	})
	t.Run("freebind", func(t *testing.T) {
		cluster, err := b.buildPolicyCluster(ctx, &config.Options{
			EnvoyBindConfigFreebind: null.BoolFrom(true),
		}, &config.Policy{
			From: "https://from.example.com",
			To:   mustParseWeightedURLs(t, "https://to.example.com"),
		})
		assert.NoError(t, err)
		testutil.AssertProtoJSONEqual(t, `
			{
				"freebind": true,
				"sourceAddress": {
					"address": "0.0.0.0",
					"portValue": 0
				}
			}
		`, cluster.UpstreamBindConfig)
	})
	t.Run("source address", func(t *testing.T) {
		cluster, err := b.buildPolicyCluster(ctx, &config.Options{
			EnvoyBindConfigSourceAddress: "192.168.0.1",
		}, &config.Policy{
			From: "https://from.example.com",
			To:   mustParseWeightedURLs(t, "https://to.example.com"),
		})
		assert.NoError(t, err)
		testutil.AssertProtoJSONEqual(t, `
			{
				"sourceAddress": {
					"address": "192.168.0.1",
					"portValue": 0
				}
			}
		`, cluster.UpstreamBindConfig)
	})
}


func (evpool *Pool) removePendingEvidence(evidence types.Evidence) {
	key := keyPending(evidence)
	if err := evpool.evidenceStore.Delete(key); err != nil {
		evpool.logger.Error("Unable to delete pending evidence", "err", err)
	} else {
		atomic.AddUint32(&evpool.evidenceSize, ^uint32(0))
		evpool.logger.Info("Deleted pending evidence", "evidence", evidence)
	}
}


func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) {
	added, err := cs.addVote(vote, peerID)
	if err != nil {
		// If the vote height is off, we'll just ignore it,
		// But if it's a conflicting sig, add it to the cs.evpool.
		// If it's otherwise invalid, punish peer.
		// nolint: gocritic
		if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
			if cs.privValidatorPubKey == nil {
				return false, errPubKeyIsNotSet
			}

			if bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) {
				cs.Logger.Error(
					"Found conflicting vote from ourselves. Did you unsafe_reset a validator?",
					"height",
					vote.Height,
					"round",
					vote.Round,
					"type",
					vote.Type)
				return added, err
			}
			var timestamp time.Time
			if voteErr.VoteA.Height == cs.state.InitialHeight {
				timestamp = cs.state.LastBlockTime // genesis time
			} else {
				timestamp = sm.MedianTime(cs.LastCommit.MakeCommit(), cs.LastValidators)
			}
			// form duplicate vote evidence from the conflicting votes and send it across to the
			// evidence pool
			ev := types.NewDuplicateVoteEvidence(voteErr.VoteA, voteErr.VoteB, timestamp, cs.Validators)
			evidenceErr := cs.evpool.AddEvidenceFromConsensus(ev)
			if evidenceErr != nil {
				cs.Logger.Error("Failed to add evidence to the evidence pool", "err", evidenceErr)
			} else {
				cs.Logger.Debug("Added evidence to the evidence pool", "ev", ev)
			}
			return added, err
		} else if err == types.ErrVoteNonDeterministicSignature {
			cs.Logger.Debug("Vote has non-deterministic signature", "err", err)
		} else {
			// Either
			// 1) bad peer OR
			// 2) not a bad peer? this can also err sometimes with "Unexpected step" OR
			// 3) tmkms use with multiple validators connecting to a single tmkms instance
			// 		(https://github.com/tendermint/tendermint/issues/3839).
			cs.Logger.Info("Error attempting to add vote", "err", err)
			return added, ErrAddingVote
		}
	}
	return added, nil
}


func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error {
	var (
		dest  = m.Destination
		data  = label.FormatMountLabel(m.Data, mountLabel)
		flags = m.Flags
	)
	if libcontainerUtils.CleanPath(dest) == "/dev" {
		flags &= ^unix.MS_RDONLY
	}

	// Mount it rw to allow chmod operation. A remount will be performed
	// later to make it ro if set.
	if m.Device == "tmpfs" {
		flags &= ^unix.MS_RDONLY
	}

	copyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP
	if !(copyUp || strings.HasPrefix(dest, rootfs)) {
		dest = filepath.Join(rootfs, dest)
	}

	if err := unix.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil {
		return err
	}

	for _, pflag := range m.PropagationFlags {
		if err := unix.Mount("", dest, "", uintptr(pflag), ""); err != nil {
			return err
		}
	}
	return nil
}


func (cn *clusterNode) resurrect() {
	gRPCServer, err := comm_utils.NewGRPCServer(cn.bindAddress, cn.serverConfig)
	if err != nil {
		panic(fmt.Errorf("failed starting gRPC server: %v", err))
	}
	cn.srv = gRPCServer
	orderer.RegisterClusterServer(gRPCServer.Server(), cn)
	go cn.srv.Start()
}


func (r *schemaResolver) UpdateSavedSearch(ctx context.Context, args *struct {
	ID          graphql.ID
	Description string
	Query       string
	NotifyOwner bool
	NotifySlack bool
	OrgID       *graphql.ID
	UserID      *graphql.ID
}) (*savedSearchResolver, error) {
	var userID, orgID *int32
	// 🚨 SECURITY: Make sure the current user has permission to update a saved search for the specified user or org.
	if args.UserID != nil {
		u, err := unmarshalSavedSearchID(*args.UserID)
		if err != nil {
			return nil, err
		}
		userID = &u
		if err := backend.CheckSiteAdminOrSameUser(ctx, r.db, u); err != nil {
			return nil, err
		}
	} else if args.OrgID != nil {
		o, err := unmarshalSavedSearchID(*args.OrgID)
		if err != nil {
			return nil, err
		}
		orgID = &o
		if err := backend.CheckOrgAccessOrSiteAdmin(ctx, r.db, o); err != nil {
			return nil, err
		}
	} else {
		return nil, errors.New("failed to update saved search: no Org ID or User ID associated with saved search")
	}

	id, err := unmarshalSavedSearchID(args.ID)
	if err != nil {
		return nil, err
	}

	if !queryHasPatternType(args.Query) {
		return nil, errMissingPatternType
	}

	ss, err := r.db.SavedSearches().Update(ctx, &types.SavedSearch{
		ID:          id,
		Description: args.Description,
		Query:       args.Query,
		Notify:      args.NotifyOwner,
		NotifySlack: args.NotifySlack,
		UserID:      userID,
		OrgID:       orgID,
	})
	if err != nil {
		return nil, err
	}

	return r.toSavedSearchResolver(*ss), nil
}


func validateMaxDepth(c *opContext, sels []types.Selection, depth int) bool {
	// maxDepth checking is turned off when maxDepth is 0
	if c.maxDepth == 0 {
		return false
	}

	exceededMaxDepth := false

	for _, sel := range sels {
		switch sel := sel.(type) {
		case *types.Field:
			if depth > c.maxDepth {
				exceededMaxDepth = true
				c.addErr(sel.Alias.Loc, "MaxDepthExceeded", "Field %q has depth %d that exceeds max depth %d", sel.Name.Name, depth, c.maxDepth)
				continue
			}
			exceededMaxDepth = exceededMaxDepth || validateMaxDepth(c, sel.SelectionSet, depth+1)
		case *types.InlineFragment:
			// Depth is not checked because inline fragments resolve to other fields which are checked.
			// Depth is not incremented because inline fragments have the same depth as neighboring fields
			exceededMaxDepth = exceededMaxDepth || validateMaxDepth(c, sel.Selections, depth)
		case *types.FragmentSpread:
			// Depth is not checked because fragments resolve to other fields which are checked.
			frag := c.doc.Fragments.Get(sel.Name.Name)
			if frag == nil {
				// In case of unknown fragment (invalid request), ignore max depth evaluation
				c.addErr(sel.Loc, "MaxDepthEvaluationError", "Unknown fragment %q. Unable to evaluate depth.", sel.Name.Name)
				continue
			}
			// Depth is not incremented because fragments have the same depth as surrounding fields
			exceededMaxDepth = exceededMaxDepth || validateMaxDepth(c, frag.Selections, depth)
		}
	}

	return exceededMaxDepth
}


func (p *GatewayAPIProcessor) validateForwardTo(serviceName *string, port *gatewayapi_v1alpha1.PortNumber, namespace string) (*Service, error) {
	// Verify the service is valid
	if serviceName == nil {
		return nil, fmt.Errorf("Spec.Rules.ForwardTo.ServiceName must be specified")
	}

	// TODO: Do not require port to be present (#3352).
	if port == nil {
		return nil, fmt.Errorf("Spec.Rules.ForwardTo.ServicePort must be specified")
	}

	meta := types.NamespacedName{Name: *serviceName, Namespace: namespace}

	// TODO: Refactor EnsureService to take an int32 so conversion to intstr is not needed.
	service, err := p.dag.EnsureService(meta, intstr.FromInt(int(*port)), p.source)
	if err != nil {
		return nil, fmt.Errorf("service %q does not exist", meta.Name)
	}

	return service, nil
}


func prepareBindMount(m *configs.Mount, rootfs string) error {
	stat, err := os.Stat(m.Source)
	if err != nil {
		// error out if the source of a bind mount does not exist as we will be
		// unable to bind anything to it.
		return err
	}
	// ensure that the destination of the bind mount is resolved of symlinks at mount time because
	// any previous mounts can invalidate the next mount's destination.
	// this can happen when a user specifies mounts within other mounts to cause breakouts or other
	// evil stuff to try to escape the container's rootfs.
	var dest string
	if dest, err = securejoin.SecureJoin(rootfs, m.Destination); err != nil {
		return err
	}
	if err := checkProcMount(rootfs, dest, m.Source); err != nil {
		return err
	}
	// update the mount with the correct dest after symlinks are resolved.
	m.Destination = dest
	if err := createIfNotExists(dest, stat.IsDir()); err != nil {
		return err
	}

	return nil
}


func TestBuilder_BuildBootstrapStatsConfig(t *testing.T) {
	b := New("local-grpc", "local-http", filemgr.NewManager(), nil)
	t.Run("valid", func(t *testing.T) {
		statsCfg, err := b.BuildBootstrapStatsConfig(&config.Config{
			Options: &config.Options{
				Services: "all",
			},
		})
		assert.NoError(t, err)
		testutil.AssertProtoJSONEqual(t, `
			{
				"statsTags": [{
					"tagName": "service",
					"fixedValue": "pomerium"
				}]
			}
		`, statsCfg)
	})
}


func (f *Fosite) WriteAuthorizeError(rw http.ResponseWriter, ar AuthorizeRequester, err error) {
	rw.Header().Set("Cache-Control", "no-store")
	rw.Header().Set("Pragma", "no-cache")

	rfcerr := ErrorToRFC6749Error(err)
	if !f.SendDebugMessagesToClients {
		rfcerr = rfcerr.Sanitize()
	}

	if !ar.IsRedirectURIValid() {
		rw.Header().Set("Content-Type", "application/json;charset=UTF-8")

		js, err := json.Marshal(rfcerr)
		if err != nil {
			if f.SendDebugMessagesToClients {
				errorMessage := EscapeJSONString(err.Error())
				http.Error(rw, fmt.Sprintf(`{"error":"server_error","error_description":"%s"}`, errorMessage), http.StatusInternalServerError)
			} else {
				http.Error(rw, `{"error":"server_error"}`, http.StatusInternalServerError)
			}
			return
		}

		rw.WriteHeader(rfcerr.Code)
		rw.Write(js)
		return
	}

	redirectURI := ar.GetRedirectURI()

	// The endpoint URI MUST NOT include a fragment component.
	redirectURI.Fragment = ""

	query := rfcerr.ToValues()
	query.Add("state", ar.GetState())

	var redirectURIString string
	if !(len(ar.GetResponseTypes()) == 0 || ar.GetResponseTypes().ExactOne("code")) && !errors.Is(err, ErrUnsupportedResponseType) {
		redirectURIString = redirectURI.String() + "#" + query.Encode()
	} else {
		for key, values := range redirectURI.Query() {
			for _, value := range values {
				query.Add(key, value)
			}
		}
		redirectURI.RawQuery = query.Encode()
		redirectURIString = redirectURI.String()
	}

	rw.Header().Add("Location", redirectURIString)
	rw.WriteHeader(http.StatusFound)
}


func TestListActivities(t *testing.T) {
	ds := new(mock.Store)
	svc := newTestService(t, ds, nil, nil)

	ds.ListActivitiesFunc = func(ctx context.Context, opts fleet.ListOptions) ([]*fleet.Activity, error) {
		return []*fleet.Activity{
			{ID: 1},
			{ID: 2},
		}, nil
	}

	// admin user
	activities, err := svc.ListActivities(test.UserContext(test.UserAdmin), fleet.ListOptions{})
	require.NoError(t, err)
	require.Len(t, activities, 2)

	// anyone can read activities
	activities, err = svc.ListActivities(test.UserContext(test.UserNoRoles), fleet.ListOptions{})
	require.NoError(t, err)
	require.Len(t, activities, 2)

	// no user in context
	_, err = svc.ListActivities(context.Background(), fleet.ListOptions{})
	require.Error(t, err)
	require.Contains(t, err.Error(), authz.ForbiddenErrorMessage)
}


func doesPolicySignatureV4Match(formValues http.Header) APIErrorCode {
	// Server region.
	region := globalServerRegion

	// Parse credential tag.
	credHeader, s3Err := parseCredentialHeader("Credential="+formValues.Get(xhttp.AmzCredential), region, serviceS3)
	if s3Err != ErrNone {
		return s3Err
	}

	cred, _, s3Err := checkKeyValid(credHeader.accessKey)
	if s3Err != ErrNone {
		return s3Err
	}

	// Get signing key.
	signingKey := getSigningKey(cred.SecretKey, credHeader.scope.date, credHeader.scope.region, serviceS3)

	// Get signature.
	newSignature := getSignature(signingKey, formValues.Get("Policy"))

	// Verify signature.
	if !compareSignatureV4(newSignature, formValues.Get(xhttp.AmzSignature)) {
		return ErrSignatureDoesNotMatch
	}

	// Success.
	return ErrNone
}


func (EmptyEvidencePool) CheckEvidence(evList types.EvidenceList) error { return nil }


func (evpool *Pool) AddEvidenceFromConsensus(ev types.Evidence) error {

	// we already have this evidence, log this but don't return an error.
	if evpool.isPending(ev) {
		evpool.logger.Info("Evidence already pending, ignoring this one", "ev", ev)
		return nil
	}

	// add evidence to a buffer which will pass the evidence to the pool at the following height.
	// This avoids the issue of some nodes verifying and proposing evidence at a height where the
	// block hasn't been committed on cause others to potentially fail.
	evpool.mtx.Lock()
	defer evpool.mtx.Unlock()
	evpool.consensusBuffer = append(evpool.consensusBuffer, ev)
	evpool.logger.Info("received new evidence of byzantine behavior from consensus", "evidence", ev)

	return nil
}


func (svc Service) CountSoftware(ctx context.Context, opt fleet.SoftwareListOptions) (int, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Software{}, fleet.ActionRead); err != nil {
		return 0, err
	}

	return svc.ds.CountSoftware(ctx, opt)
}


func (svc *Service) ListUsers(ctx context.Context, opt fleet.UserListOptions) ([]*fleet.User, error) {
	if err := svc.authz.Authorize(ctx, &fleet.User{}, fleet.ActionRead); err != nil {
		return nil, err
	}

	return svc.ds.ListUsers(ctx, opt)
}


func (svc *Service) DeleteGlobalScheduledQueries(ctx context.Context, id uint) error {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionWrite); err != nil {
		return err
	}

	return svc.DeleteScheduledQuery(ctx, id)
}


func (p *Profile) write() (pth string, err error) {
	rootDir, err := utils.GetTempDir()
	if err != nil {
		return
	}

	pth = filepath.Join(rootDir, p.Id)

	_ = os.Remove(pth)
	err = ioutil.WriteFile(pth, []byte(p.Data), os.FileMode(0600))
	if err != nil {
		err = &WriteError{
			errors.Wrap(err, "profile: Failed to write profile"),
		}
		return
	}

	return
}


func MkdirSecure(pth string) (err error) {
	err = os.MkdirAll(pth, 0755)
	if err != nil {
		err = &errortypes.WriteError{
			errors.Wrap(err, "utils: Failed to create directory"),
		}
		return
	}

	err = acl.Apply(
		pth,
		true,
		false,
		acl.GrantName(windows.GENERIC_ALL, "CREATOR OWNER"),
		acl.GrantName(windows.GENERIC_ALL, "SYSTEM"),
		acl.GrantName(windows.GENERIC_ALL, "Administrators"),
	)
	if err != nil {
		err = &errortypes.WriteError{
			errors.Wrap(err, "utils: Failed to acl directory"),
		}
		return
	}

	return
}


func Skip(self Protocol, fieldType Type, maxDepth int) (err error) {

	if maxDepth <= 0 {
		return NewProtocolExceptionWithType(DEPTH_LIMIT, errors.New("Depth limit exceeded"))
	}

	switch fieldType {
	case STOP:
		return
	case BOOL:
		_, err = self.ReadBool()
		return
	case BYTE:
		_, err = self.ReadByte()
		return
	case I16:
		_, err = self.ReadI16()
		return
	case I32:
		_, err = self.ReadI32()
		return
	case I64:
		_, err = self.ReadI64()
		return
	case DOUBLE:
		_, err = self.ReadDouble()
		return
	case FLOAT:
		_, err = self.ReadFloat()
		return
	case STRING:
		_, err = self.ReadString()
		return
	case STRUCT:
		if _, err = self.ReadStructBegin(); err != nil {
			return err
		}
		for {
			_, typeId, _, _ := self.ReadFieldBegin()
			if typeId == STOP {
				break
			}
			err := Skip(self, typeId, maxDepth-1)
			if err != nil {
				return err
			}
			self.ReadFieldEnd()
		}
		return self.ReadStructEnd()
	case MAP:
		keyType, valueType, size, err := self.ReadMapBegin()
		if err != nil {
			return err
		}
		for i := 0; i < size; i++ {
			err := Skip(self, keyType, maxDepth-1)
			if err != nil {
				return err
			}
			self.Skip(valueType)
		}
		return self.ReadMapEnd()
	case SET:
		elemType, size, err := self.ReadSetBegin()
		if err != nil {
			return err
		}
		for i := 0; i < size; i++ {
			err := Skip(self, elemType, maxDepth-1)
			if err != nil {
				return err
			}
		}
		return self.ReadSetEnd()
	case LIST:
		elemType, size, err := self.ReadListBegin()
		if err != nil {
			return err
		}
		for i := 0; i < size; i++ {
			err := Skip(self, elemType, maxDepth-1)
			if err != nil {
				return err
			}
		}
		return self.ReadListEnd()
	}
	return nil
}


func (f *Fosite) WriteAccessResponse(rw http.ResponseWriter, requester AccessRequester, responder AccessResponder) {
	rw.Header().Set("Cache-Control", "no-store")
	rw.Header().Set("Pragma", "no-cache")

	js, err := json.Marshal(responder.ToMap())
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}

	rw.Header().Set("Content-Type", "application/json;charset=UTF-8")

	rw.WriteHeader(http.StatusOK)
	rw.Write(js)
}


func InstallNps() {
	path := common.GetInstallPath()
	if common.FileExists(path) {
		log.Fatalf("the path %s has exist, does not support install", path)
	}
	MkidrDirAll(path, "conf", "web/static", "web/views")
	//复制文件到对应目录
	if err := CopyDir(filepath.Join(common.GetAppPath(), "web", "views"), filepath.Join(path, "web", "views")); err != nil {
		log.Fatalln(err)
	}
	if err := CopyDir(filepath.Join(common.GetAppPath(), "web", "static"), filepath.Join(path, "web", "static")); err != nil {
		log.Fatalln(err)
	}
	if err := CopyDir(filepath.Join(common.GetAppPath(), "conf"), filepath.Join(path, "conf")); err != nil {
		log.Fatalln(err)
	}

	if !common.IsWindows() {
		if _, err := copyFile(filepath.Join(common.GetAppPath(), "nps"), "/usr/bin/nps"); err != nil {
			if _, err := copyFile(filepath.Join(common.GetAppPath(), "nps"), "/usr/local/bin/nps"); err != nil {
				log.Fatalln(err)
			} else {
				os.Chmod("/usr/local/bin/nps", 0777)
				log.Println("Executable files have been copied to", "/usr/local/bin/nps")
			}
		} else {
			os.Chmod("/usr/bin/nps", 0777)
			log.Println("Executable files have been copied to", "/usr/bin/nps")
		}

	}
	log.Println("install ok!")
	log.Println("Static files and configuration files in the current directory will be useless")
	log.Println("The new configuration file is located in", path, "you can edit them")
	if !common.IsWindows() {
		log.Println("You can start with nps test|start|stop|restart|status anywhere")
	} else {
		log.Println("You can copy executable files to any directory and start working with nps.exe test|start|stop|restart|status")
	}
}


	ctx := log.WithContext(context.TODO(), func(c zerolog.Context) zerolog.Context {
		return c.Str("config_file_source", configFile)
	})

	options, err := newOptionsFromConfig(configFile)
	if err != nil {
		return nil, err
	}

	ports, err := netutil.AllocatePorts(3)
	if err != nil {
		return nil, err
	}
	grpcPort := ports[0]
	httpPort := ports[1]
	outboundPort := ports[2]

	cfg := &Config{
		Options:      options,
		EnvoyVersion: envoyVersion,

		GRPCPort:     grpcPort,
		HTTPPort:     httpPort,
		OutboundPort: outboundPort,
	}
	metrics.SetConfigInfo(ctx, cfg.Options.Services, "local", cfg.Checksum(), true)

	src := &FileOrEnvironmentSource{
		configFile: configFile,
		config:     cfg,
	}
	options.viper.OnConfigChange(src.onConfigChange(ctx))
	go options.viper.WatchConfig()

	return src, nil
}


func TestService_ListSoftware(t *testing.T) {
	ds := new(mock.Store)

	var calledWithTeamID *uint
	var calledWithOpt fleet.SoftwareListOptions
	ds.ListSoftwareFunc = func(ctx context.Context, opt fleet.SoftwareListOptions) ([]fleet.Software, error) {
		calledWithTeamID = opt.TeamID
		calledWithOpt = opt
		return []fleet.Software{}, nil
	}

	user := &fleet.User{ID: 3, Email: "foo@bar.com", GlobalRole: ptr.String(fleet.RoleObserver)}

	svc := newTestService(t, ds, nil, nil)
	ctx := context.Background()
	ctx = viewer.NewContext(ctx, viewer.Viewer{User: user})

	_, err := svc.ListSoftware(ctx, fleet.SoftwareListOptions{TeamID: ptr.Uint(42), ListOptions: fleet.ListOptions{PerPage: 77, Page: 4}})
	require.NoError(t, err)

	assert.True(t, ds.ListSoftwareFuncInvoked)
	assert.Equal(t, ptr.Uint(42), calledWithTeamID)
	// sort order defaults to hosts_count descending, automatically, if not explicitly provided
	assert.Equal(t, fleet.ListOptions{PerPage: 77, Page: 4, OrderKey: "hosts_count", OrderDirection: fleet.OrderDescending}, calledWithOpt.ListOptions)
	assert.True(t, calledWithOpt.WithHostCounts)

	// call again, this time with an explicit sort
	ds.ListSoftwareFuncInvoked = false
	_, err = svc.ListSoftware(ctx, fleet.SoftwareListOptions{TeamID: nil, ListOptions: fleet.ListOptions{PerPage: 11, Page: 2, OrderKey: "id", OrderDirection: fleet.OrderAscending}})
	require.NoError(t, err)

	assert.True(t, ds.ListSoftwareFuncInvoked)
	assert.Nil(t, calledWithTeamID)
	assert.Equal(t, fleet.ListOptions{PerPage: 11, Page: 2, OrderKey: "id", OrderDirection: fleet.OrderAscending}, calledWithOpt.ListOptions)
	assert.True(t, calledWithOpt.WithHostCounts)
}


func (set *IdmapSet) doUidshiftIntoContainer(dir string, testmode bool, how string) error {
	convert := func(path string, fi os.FileInfo, err error) (e error) {
		uid, gid, err := GetOwner(path)
		if err != nil {
			return err
		}
		var newuid, newgid int
		switch how {
		case "in":
			newuid, newgid = set.ShiftIntoNs(uid, gid)
		case "out":
			newuid, newgid = set.ShiftFromNs(uid, gid)
		}
		if testmode {
			fmt.Printf("I would shift %q to %d %d\n", path, newuid, newgid)
		} else {
			err = os.Lchown(path, int(newuid), int(newgid))
			if err == nil {
				m := fi.Mode()
				if m&os.ModeSymlink == 0 {
					err = os.Chmod(path, m)
					if err != nil {
						fmt.Printf("Error resetting mode on %q, continuing\n", path)
					}
				}
			}
		}
		return nil
	}

	if !PathExists(dir) {
		return fmt.Errorf("No such file or directory: %q", dir)
	}
	return filepath.Walk(dir, convert)
}


func TestMsgGrantAuthorization(t *testing.T) {
	tests := []struct {
		title            string
		granter, grantee sdk.AccAddress
		authorization    authz.Authorization
		expiration       time.Time
		expectErr        bool
		expectPass       bool
	}{
		{"nil granter address", nil, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
		{"nil grantee address", granter, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
		{"nil granter and grantee address", nil, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
		{"nil authorization", granter, grantee, nil, time.Now(), true, false},
		{"valid test case", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 1, 0), false, true},
		{"past time", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 0, -1), false, false},
	}
	for i, tc := range tests {
		msg, err := authz.NewMsgGrant(
			tc.granter, tc.grantee, tc.authorization, tc.expiration,
		)
		if !tc.expectErr {
			require.NoError(t, err)
		} else {
			continue
		}
		if tc.expectPass {
			require.NoError(t, msg.ValidateBasic(), "test: %v", i)
		} else {
			require.Error(t, msg.ValidateBasic(), "test: %v", i)
		}
	}
}


func (p *GitLabProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error {
	// Retrieve user info
	userInfo, err := p.getUserInfo(ctx, s)
	if err != nil {
		return fmt.Errorf("failed to retrieve user info: %v", err)
	}

	// Check if email is verified
	if !p.AllowUnverifiedEmail && !userInfo.EmailVerified {
		return fmt.Errorf("user email is not verified")
	}

	s.User = userInfo.Username
	s.Email = userInfo.Email

	p.addGroupsToSession(ctx, s)

	p.addProjectsToSession(ctx, s)

	return nil

}


func (mgr *MetricsManager) OnConfigChange(ctx context.Context, cfg *Config) {
	mgr.mu.Lock()
	defer mgr.mu.Unlock()

	mgr.updateInfo(cfg)
	mgr.updateServer(cfg)
}


func Test_buildControlPlanePrefixRoute(t *testing.T) {
	b := &Builder{filemgr: filemgr.NewManager()}
	route, err := b.buildControlPlanePrefixRoute("/hello/world/", false)
	require.NoError(t, err)
	testutil.AssertProtoJSONEqual(t, `
		{
			"name": "pomerium-prefix-/hello/world/",
			"match": {
				"prefix": "/hello/world/"
			},
			"route": {
				"cluster": "pomerium-control-plane-http"
			},
			"typedPerFilterConfig": {
				"envoy.filters.http.ext_authz": {
					"@type": "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute",
					"disabled": true
				}
			}
		}
	`, route)
}


func TestCheckValid(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	objLayer, fsDir, err := prepareFS()
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(fsDir)
	if err = newTestConfig(globalMinioDefaultRegion, objLayer); err != nil {
		t.Fatalf("unable initialize config file, %s", err)
	}

	newAllSubsystems()

	initConfigSubsystem(ctx, objLayer)

	globalIAMSys.Init(ctx, objLayer, globalEtcdClient, globalNotificationSys, 2*time.Second)

	req, err := newTestRequest(http.MethodGet, "http://example.com:9000/bucket/object", 0, nil)
	if err != nil {
		t.Fatal(err)
	}

	if err = signRequestV4(req, globalActiveCred.AccessKey, globalActiveCred.SecretKey); err != nil {
		t.Fatal(err)
	}

	_, owner, s3Err := checkKeyValid(req, globalActiveCred.AccessKey)
	if s3Err != ErrNone {
		t.Fatalf("Unexpected failure with %v", errorCodes.ToAPIErr(s3Err))
	}

	if !owner {
		t.Fatalf("Expected owner to be 'true', found %t", owner)
	}

	_, _, s3Err = checkKeyValid(req, "does-not-exist")
	if s3Err != ErrInvalidAccessKeyID {
		t.Fatalf("Expected error 'ErrInvalidAccessKeyID', found %v", s3Err)
	}

	ucreds, err := auth.CreateCredentials("myuser1", "mypassword1")
	if err != nil {
		t.Fatalf("unable create credential, %s", err)
	}

	globalIAMSys.CreateUser(ctx, ucreds.AccessKey, madmin.UserInfo{
		SecretKey: ucreds.SecretKey,
		Status:    madmin.AccountEnabled,
	})

	_, owner, s3Err = checkKeyValid(req, ucreds.AccessKey)
	if s3Err != ErrNone {
		t.Fatalf("Unexpected failure with %v", errorCodes.ToAPIErr(s3Err))
	}

	if owner {
		t.Fatalf("Expected owner to be 'false', found %t", owner)
	}
}


func NewGrant(a Authorization, expiration time.Time) (Grant, error) {
	g := Grant{
		Expiration: expiration,
	}
	msg, ok := a.(proto.Message)
	if !ok {
		return Grant{}, sdkerrors.Wrapf(sdkerrors.ErrPackAny, "cannot proto marshal %T", a)
	}

	any, err := cdctypes.NewAnyWithValue(msg)
	if err != nil {
		return Grant{}, err
	}
	g.Authorization = any

	return g, nil
}


func (sys *IAMSys) CreateUser(ctx context.Context, accessKey string, uinfo madmin.UserInfo) error {
	if !sys.Initialized() {
		return errServerNotInitialized
	}

	if sys.usersSysType != MinIOUsersSysType {
		return errIAMActionNotAllowed
	}

	if !auth.IsAccessKeyValid(accessKey) {
		return auth.ErrInvalidAccessKeyLength
	}

	if !auth.IsSecretKeyValid(uinfo.SecretKey) {
		return auth.ErrInvalidSecretKeyLength
	}

	err := sys.store.AddUser(ctx, accessKey, uinfo)
	if err != nil {
		return err
	}

	sys.notifyForUser(ctx, accessKey, false)
	return nil
}


func (evpool *Pool) AddEvidence(ev types.Evidence) error {
	evpool.logger.Debug("Attempting to add evidence", "ev", ev)

	// We have already verified this piece of evidence - no need to do it again
	if evpool.isPending(ev) {
		evpool.logger.Info("Evidence already pending, ignoring this one", "ev", ev)
		return nil
	}

	// check that the evidence isn't already committed
	if evpool.isCommitted(ev) {
		// this can happen if the peer that sent us the evidence is behind so we shouldn't
		// punish the peer.
		evpool.logger.Debug("Evidence was already committed, ignoring this one", "ev", ev)
		return nil
	}

	// 1) Verify against state.
	err := evpool.verify(ev)
	if err != nil {
		return types.NewErrInvalidEvidence(ev, err)
	}

	// 2) Save to store.
	if err := evpool.addPendingEvidence(ev); err != nil {
		return fmt.Errorf("can't add evidence to pending list: %w", err)
	}

	// 3) Add evidence to clist.
	evpool.evidenceList.PushBack(ev)

	evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev)

	return nil
}


func (f *Fosite) writeJsonError(rw http.ResponseWriter, err error) {
	rw.Header().Set("Content-Type", "application/json;charset=UTF-8")
	rw.Header().Set("Cache-Control", "no-store")
	rw.Header().Set("Pragma", "no-cache")

	rfcerr := ErrorToRFC6749Error(err)
	if !f.SendDebugMessagesToClients {
		rfcerr = rfcerr.Sanitize()
	}

	js, err := json.Marshal(rfcerr)
	if err != nil {
		if f.SendDebugMessagesToClients {
			errorMessage := EscapeJSONString(err.Error())
			http.Error(rw, fmt.Sprintf(`{"error":"server_error","error_description":"%s"}`, errorMessage), http.StatusInternalServerError)
		} else {
			http.Error(rw, `{"error":"server_error"}`, http.StatusInternalServerError)
		}
		return
	}

	rw.WriteHeader(rfcerr.Code)
	rw.Write(js)
}


func (a *AuthenticatorOAuth2Introspection) traceRequest(ctx context.Context, req *http.Request) func() {
	tracer := opentracing.GlobalTracer()
	if tracer == nil {
		return func() {}
	}

	parentSpan := opentracing.SpanFromContext(ctx)
	opts := make([]opentracing.StartSpanOption, 0, 1)
	if parentSpan != nil {
		opts = append(opts, opentracing.ChildOf(parentSpan.Context()))
	}

	urlStr := req.URL.String()
	clientSpan := tracer.StartSpan(req.Method+" "+urlStr, opts...)

	ext.SpanKindRPCClient.Set(clientSpan)
	ext.HTTPUrl.Set(clientSpan, urlStr)
	ext.HTTPMethod.Set(clientSpan, req.Method)

	tracer.Inject(clientSpan.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
	return clientSpan.Finish
}


func LoadAll(basedir string) ([]*Plugin, error) {
	plugins := []*Plugin{}
	// We want basedir/*/plugin.yaml
	scanpath := filepath.Join(basedir, "*", PluginFileName)
	matches, err := filepath.Glob(scanpath)
	if err != nil {
		return plugins, err
	}

	if matches == nil {
		return plugins, nil
	}

	for _, yaml := range matches {
		dir := filepath.Dir(yaml)
		p, err := LoadDir(dir)
		if err != nil {
			return plugins, err
		}
		plugins = append(plugins, p)
	}
	return plugins, nil
}


func (EmptyEvidencePool) AddEvidence(types.Evidence) error              { return nil }


func (c *linuxContainer) prepareCriuRestoreMounts(mounts []*configs.Mount) error {
	// First get a list of a all tmpfs mounts
	tmpfs := []string{}
	for _, m := range mounts {
		switch m.Device {
		case "tmpfs":
			tmpfs = append(tmpfs, m.Destination)
		}
	}
	// Now go through all mounts and create the mountpoints
	// if the mountpoints are not on a tmpfs, as CRIU will
	// restore the complete tmpfs content from its checkpoint.
	umounts := []string{}
	defer func() {
		for _, u := range umounts {
			if e := unix.Unmount(u, unix.MNT_DETACH); e != nil {
				if e != unix.EINVAL {
					// Ignore EINVAL as it means 'target is not a mount point.'
					// It probably has already been unmounted.
					logrus.Warnf("Error during cleanup unmounting of %q (%v)", u, e)
				}
			}
		}
	}()
	for _, m := range mounts {
		if !isPathInPrefixList(m.Destination, tmpfs) {
			if err := c.makeCriuRestoreMountpoints(m); err != nil {
				return err
			}
			// If the mount point is a bind mount, we need to mount
			// it now so that runc can create the necessary mount
			// points for mounts in bind mounts.
			// This also happens during initial container creation.
			// Without this CRIU restore will fail
			// See: https://github.com/opencontainers/runc/issues/2748
			// It is also not necessary to order the mount points
			// because during initial container creation mounts are
			// set up in the order they are configured.
			if m.Device == "bind" {
				if err := unix.Mount(m.Source, m.Destination, "", unix.MS_BIND|unix.MS_REC, ""); err != nil {
					return errorsf.Wrapf(err, "unable to bind mount %q to %q", m.Source, m.Destination)
				}
				umounts = append(umounts, m.Destination)
			}
		}
	}
	return nil
}


func (i *IDTokenHandleHelper) GetAccessTokenHash(ctx context.Context, requester fosite.AccessRequester, responder fosite.AccessResponder) string {
	token := responder.GetAccessToken()

	buffer := bytes.NewBufferString(token)
	hash := sha256.New()
	hash.Write(buffer.Bytes())
	hashBuf := bytes.NewBuffer(hash.Sum([]byte{}))
	len := hashBuf.Len()

	return base64.RawURLEncoding.EncodeToString(hashBuf.Bytes()[:len/2])
}


func LoadDir(dirname string) (*Plugin, error) {
	data, err := ioutil.ReadFile(filepath.Join(dirname, PluginFileName))
	if err != nil {
		return nil, err
	}

	plug := &Plugin{Dir: dirname}
	if err := yaml.Unmarshal(data, &plug.Metadata); err != nil {
		return nil, err
	}
	return plug, nil
}


func Test_buildRouteConfiguration(t *testing.T) {
	b := New("local-grpc", "local-http", nil, nil)
	virtualHosts := make([]*envoy_config_route_v3.VirtualHost, 10)
	routeConfig, err := b.buildRouteConfiguration("test-route-configuration", virtualHosts)
	require.NoError(t, err)
	assert.Equal(t, "test-route-configuration", routeConfig.GetName())
	assert.Equal(t, virtualHosts, routeConfig.GetVirtualHosts())
	assert.False(t, routeConfig.GetValidateClusters().GetValue())
}


func (f *ScmpFilter) addRuleWrapper(call ScmpSyscall, action ScmpAction, exact bool, cond C.scmp_cast_t) error {
	var length C.uint
	if cond != nil {
		length = 1
	} else {
		length = 0
	}

	var retCode C.int
	if exact {
		retCode = C.seccomp_rule_add_exact_array(f.filterCtx, action.toNative(), C.int(call), length, cond)
	} else {
		retCode = C.seccomp_rule_add_array(f.filterCtx, action.toNative(), C.int(call), length, cond)
	}

	if syscall.Errno(-1*retCode) == syscall.EFAULT {
		return fmt.Errorf("unrecognized syscall")
	} else if syscall.Errno(-1*retCode) == syscall.EPERM {
		return fmt.Errorf("requested action matches default action of filter")
	} else if retCode != 0 {
		return syscall.Errno(-1 * retCode)
	}

	return nil
}


func mountCgroupV2(m *configs.Mount, c *mountConfig) error {
	dest, err := securejoin.SecureJoin(c.root, m.Destination)
	if err != nil {
		return err
	}
	if err := os.MkdirAll(dest, 0755); err != nil {
		return err
	}
	if err := unix.Mount(m.Source, dest, "cgroup2", uintptr(m.Flags), m.Data); err != nil {
		// when we are in UserNS but CgroupNS is not unshared, we cannot mount cgroup2 (#2158)
		if err == unix.EPERM || err == unix.EBUSY {
			src := fs2.UnifiedMountpoint
			if c.cgroupns && c.cgroup2Path != "" {
				// Emulate cgroupns by bind-mounting
				// the container cgroup path rather than
				// the whole /sys/fs/cgroup.
				src = c.cgroup2Path
			}
			err = unix.Mount(src, dest, "", uintptr(m.Flags)|unix.MS_BIND, "")
			if err == unix.ENOENT && c.rootlessCgroups {
				err = nil
			}
			return err
		}
		return err
	}
	return nil
}


func TestAddDebug(t *testing.T) {
	err := ErrRevocationClientMismatch.WithDebug("debug")
	assert.NotEqual(t, err, ErrRevocationClientMismatch)
	assert.Empty(t, ErrRevocationClientMismatch.Debug)
	assert.NotEmpty(t, err.Debug)
}


func (f *Fosite) WriteRevocationResponse(rw http.ResponseWriter, err error) {
	rw.Header().Set("Cache-Control", "no-store")
	rw.Header().Set("Pragma", "no-cache")

	if err == nil {
		rw.WriteHeader(http.StatusOK)
		return
	}

	if errors.Is(err, ErrInvalidRequest) {
		rw.Header().Set("Content-Type", "application/json;charset=UTF-8")

		js, err := json.Marshal(ErrInvalidRequest)
		if err != nil {
			http.Error(rw, fmt.Sprintf(`{"error": "%s"}`, err.Error()), http.StatusInternalServerError)
			return
		}

		rw.WriteHeader(ErrInvalidRequest.Code)
		rw.Write(js)
	} else if errors.Is(err, ErrInvalidClient) {
		rw.Header().Set("Content-Type", "application/json;charset=UTF-8")

		js, err := json.Marshal(ErrInvalidClient)
		if err != nil {
			http.Error(rw, fmt.Sprintf(`{"error": "%s"}`, err.Error()), http.StatusInternalServerError)
			return
		}

		rw.WriteHeader(ErrInvalidClient.Code)
		rw.Write(js)
	} else {
		// 200 OK
		rw.WriteHeader(http.StatusOK)
	}
}


func doesPolicySignatureMatch(formValues http.Header) APIErrorCode {
	// For SignV2 - Signature field will be valid
	if _, ok := formValues["Signature"]; ok {
		return doesPolicySignatureV2Match(formValues)
	}
	return doesPolicySignatureV4Match(formValues)
}


func (svc *Service) ListHostDeviceMapping(ctx context.Context, id uint) ([]*fleet.HostDeviceMapping, error) {
	if !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) {
		if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {
			return nil, err
		}

		host, err := svc.ds.HostLite(ctx, id)
		if err != nil {
			return nil, ctxerr.Wrap(ctx, err, "get host")
		}

		// Authorize again with team loaded now that we have team_id
		if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {
			return nil, err
		}
	}

	return svc.ds.ListHostDeviceMapping(ctx, id)
}


func isAdminOfTheModifiedTeams(currentUser *fleet.User, originalUserTeams, newUserTeams []fleet.UserTeam) bool {
	// If the user is of the right global role, then they can modify the teams
	if currentUser.GlobalRole != nil && (*currentUser.GlobalRole == fleet.RoleAdmin || *currentUser.GlobalRole == fleet.RoleMaintainer) {
		return true
	}

	// otherwise, gather the resulting teams
	resultingTeams := make(map[uint]string)
	for _, team := range newUserTeams {
		resultingTeams[team.ID] = team.Role
	}

	// and see which ones were removed or changed from the original
	teamsAffected := make(map[uint]struct{})
	for _, team := range originalUserTeams {
		if resultingTeams[team.ID] != team.Role {
			teamsAffected[team.ID] = struct{}{}
		}
	}

	// then gather the teams the current user is admin for
	currentUserTeamAdmin := make(map[uint]struct{})
	for _, team := range currentUser.Teams {
		if team.Role == fleet.RoleAdmin {
			currentUserTeamAdmin[team.ID] = struct{}{}
		}
	}

	// and let's check that the teams that were either removed or changed are also teams this user is an admin of
	for teamID := range teamsAffected {
		if _, ok := currentUserTeamAdmin[teamID]; !ok {
			return false
		}
	}

	return true
}


func Test_requireProxyProtocol(t *testing.T) {
	b := New("local-grpc", "local-http", nil, nil)
	t.Run("required", func(t *testing.T) {
		li, err := b.buildMainListener(context.Background(), &config.Config{Options: &config.Options{
			UseProxyProtocol: true,
			InsecureServer:   true,
		}})
		require.NoError(t, err)
		testutil.AssertProtoJSONEqual(t, `[
			{
				"name": "envoy.filters.listener.proxy_protocol",
				"typedConfig": {
					"@type": "type.googleapis.com/envoy.extensions.filters.listener.proxy_protocol.v3.ProxyProtocol"
				}
			}
		]`, li.GetListenerFilters())
	})
	t.Run("not required", func(t *testing.T) {
		li, err := b.buildMainListener(context.Background(), &config.Config{Options: &config.Options{
			UseProxyProtocol: false,
			InsecureServer:   true,
		}})
		require.NoError(t, err)
		assert.Len(t, li.GetListenerFilters(), 0)
	})
}


func createDeviceNode(rootfs string, node *devices.Device, bind bool) error {
	if node.Path == "" {
		// The node only exists for cgroup reasons, ignore it here.
		return nil
	}
	dest := filepath.Join(rootfs, node.Path)
	if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
		return err
	}
	if bind {
		return bindMountDeviceNode(dest, node)
	}
	if err := mknodDevice(dest, node); err != nil {
		if os.IsExist(err) {
			return nil
		} else if os.IsPermission(err) {
			return bindMountDeviceNode(dest, node)
		}
		return err
	}
	return nil
}


func (a *AuthenticatorOAuth2Introspection) tokenToCache(config *AuthenticatorOAuth2IntrospectionConfiguration, i *AuthenticatorOAuth2IntrospectionResult, token string) {
	if !config.Cache.Enabled {
		return
	}

	if a.cacheTTL != nil {
		a.tokenCache.SetWithTTL(token, i, 1, *a.cacheTTL)
	} else {
		a.tokenCache.Set(token, i, 1)
	}
}


func (svc *Service) OSVersions(ctx context.Context, teamID *uint, platform *string) (*fleet.OSVersions, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Host{TeamID: teamID}, fleet.ActionList); err != nil {
		return nil, err
	}

	osVersions, err := svc.ds.OSVersions(ctx, teamID, platform)
	if err != nil {
		return nil, err
	}

	return osVersions, nil

}


func logNamespaceDiagnostics(spec *specs.Spec) {
	sawMountNS := false
	sawUserNS := false
	sawUTSNS := false
	for _, ns := range spec.Linux.Namespaces {
		switch ns.Type {
		case specs.CgroupNamespace:
			if ns.Path != "" {
				logrus.Debugf("unable to join cgroup namespace, sorry about that")
			} else {
				logrus.Debugf("unable to create cgroup namespace, sorry about that")
			}
		case specs.IPCNamespace:
			if ns.Path != "" {
				logrus.Debugf("unable to join IPC namespace, sorry about that")
			} else {
				logrus.Debugf("unable to create IPC namespace, sorry about that")
			}
		case specs.MountNamespace:
			if ns.Path != "" {
				logrus.Debugf("unable to join mount namespace %q, creating a new one", ns.Path)
			}
			sawMountNS = true
		case specs.NetworkNamespace:
			if ns.Path != "" {
				logrus.Debugf("unable to join network namespace, sorry about that")
			} else {
				logrus.Debugf("unable to create network namespace, sorry about that")
			}
		case specs.PIDNamespace:
			if ns.Path != "" {
				logrus.Debugf("unable to join PID namespace, sorry about that")
			} else {
				logrus.Debugf("unable to create PID namespace, sorry about that")
			}
		case specs.UserNamespace:
			if ns.Path != "" {
				logrus.Debugf("unable to join user namespace %q, creating a new one", ns.Path)
			}
			sawUserNS = true
		case specs.UTSNamespace:
			if ns.Path != "" {
				logrus.Debugf("unable to join UTS namespace %q, creating a new one", ns.Path)
			}
			sawUTSNS = true
		}
	}
	if !sawMountNS {
		logrus.Debugf("mount namespace not requested, but creating a new one anyway")
	}
	if !sawUserNS {
		logrus.Debugf("user namespace not requested, but creating a new one anyway")
	}
	if !sawUTSNS {
		logrus.Debugf("UTS namespace not requested, but creating a new one anyway")
	}
}


func (svc *Service) User(ctx context.Context, id uint) (*fleet.User, error) {
	if err := svc.authz.Authorize(ctx, &fleet.User{ID: id}, fleet.ActionRead); err != nil {
		return nil, err
	}

	return svc.ds.UserByID(ctx, id)
}


        signBufferFunc:  (chunk: Buffer) => makeMessageChunkSignatureWithDerivedKeys(chunk, derivedKeys),
        signatureLength: derivedKeys.signatureLength,
        sequenceHeaderSize: 0,
    };

    const securityHeader = new SymmetricAlgorithmSecurityHeader({
        tokenId: 10
    });

    const msgChunkManager = new SecureMessageChunkManager("MSG", options, securityHeader, sequenceNumberGenerator);
    msgChunkManager.on("chunk", (chunk, final) => callback(null, chunk));
    msgChunkManager.write(buffer, buffer.length);
    msgChunkManager.end();
}


async function installMonitoredItem(subscription, nodeId) {
    debugLog("installMonitoredItem", nodeId.toString());
    const monitoredItem = await subscription.monitor(
        { nodeId, attributeId: AttributeIds.Value },
        {
            samplingInterval: 0, // reports immediately
            discardOldest: true,
            queueSize: 10
        },
        TimestampsToReturn.Both,
        MonitoringMode.Reporting
    );
    const recordedValue = [];

    monitoredItem.on("changed", function (dataValue) {
        recordedValue.push(dataValue.value.value);
        debugLog("change =", recordedValue);
    });
    return await new Promise((resolve, reject) => {
        const timer = setTimeout(() => {
            reject(new Error("Never received changedx for id" + nodeId.toString()));
        }, 5000);

        monitoredItem.once("changed", function (dataValue) {
            clearTimeout(timer);
            resolve([recordedValue, monitoredItem]);
        });
    });
}


    static parseChunkToInt(intBytes: Buffer, minByteLen: number, maxByteLen: number, raise_on_Null = false) {
        // # Parse data as unsigned-big-endian encoded integer.
        // # For empty data different possibilities may occur:
        // #      minByteLen <= 0 : return 0
        // #      raise_on_Null == False and minByteLen > 0: return None
        // #      raise_on_Null == True and minByteLen > 0:  raise SlpInvalidOutputMessage
        if(intBytes.length >= minByteLen && intBytes.length <= maxByteLen)
            return intBytes.readUIntBE(0, intBytes.length)
        if(intBytes.length === 0 && !raise_on_Null)
            return null;
        throw Error('Field has wrong length');
    }


                response.responseHeader.serviceResult.should.eql(StatusCodes.BadDiscoveryUrlMissing);
            }

            await send_registered_server_request(discoveryServerEndpointUrl, request, check_response);
        });


export function getExtensionPath(): string {
	return extensionPath;
}


        html: html({ url, host, theme }),
      })
      const failed = result.rejected.concat(result.pending).filter(Boolean)
      if (failed.length) {
        throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`)
      }
    },
    options,
  }
}


    calculateMintCost(mintOpReturnLength: number, inputUtxoSize: number, batonAddress: string|null, bchChangeAddress?: string, feeRate = 1) {
        return this.calculateMintOrGenesisCost(mintOpReturnLength, inputUtxoSize, batonAddress, bchChangeAddress, feeRate);
    }


        function sendResponse(response1: Response) {
            try {
                assert(response1 instanceof ResponseClass);
                if (message.session) {
                    const counterName = ResponseClass.name.replace("Response", "");
                    message.session.incrementRequestTotalCounter(counterName);
                }
                return channel.send_response("MSG", response1, message);
            } catch (err) {
                warningLog(err);
                // istanbul ignore next
                if (err instanceof Error) {
                    // istanbul ignore next
                    errorLog(
                        "Internal error in issuing response\nplease contact support@sterfive.com",
                        message.request.toString(),
                        "\n",
                        response1.toString()
                    );
                }
                // istanbul ignore next
                throw err;
            }
        }


        }validateOrReject(Object.assign(new Validators.${checker.typeToString(v.type)}(), req.${
          v.name
        }), validatorOptions)${v.hasQuestion ? ' : null' : ''}`
      : ''
  )
  .join(',\n')}\n    ])`


  async signup(params: any) {
    // Check if the installation allows user signups
    if (process.env.DISABLE_SIGNUPS === 'true') {
      return {};
    }

    const { email } = params;
    const existingUser = await this.usersService.findByEmail(email);
    if (existingUser) {
      throw new NotAcceptableException('Email already exists');
    }
    const organization = await this.organizationsService.create('Untitled organization');
    const user = await this.usersService.create({ email }, organization, ['all_users', 'admin']);

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const organizationUser = await this.organizationUsersService.create(user, organization);

    await this.emailService.sendWelcomeEmail(user.email, user.firstName, user.invitationToken);

    return {};
  }


  }

  actionItems() {
    let composing = new PrivateComposing(this.user);

    const items = new ItemList();

    if (app.session.user && app.forum.attribute('canStartPrivateDiscussion')) {
      items.add('start_private', composing.component());
    }


      .catch(error => {
        // There was an error with the session token
        const result = {};
        if (error && error.code === Parse.Error.INVALID_SESSION_TOKEN) {
          // Store a resolved promise with the error for 10 minutes
          result.error = error;
          this.authCache.set(
            sessionToken,
            Promise.resolve(result),
            60 * 10 * 1000
          );
        } else {


          Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null
        ])


          use: (path) => {
            useCount++;
            expect(path).toEqual('somepath');
          },


    static buildMintOpReturn(config: configBuildMintOpReturn, type = 0x01) {
        return SlpTokenType1.buildMintOpReturn(
            config.tokenIdHex,
            config.batonVout,
            config.mintQuantity,
            type
        )
    }


      type: new GraphQLNonNull(parseGraphQLSchema.viewerType),
      async resolve(_source, _args, context, queryInfo) {
        try {
          const { config, info } = context;
          return await getUserFromSessionToken(
            config,
            info,
            queryInfo,
            'user.',
            false
          );
        } catch (e) {
          parseGraphQLSchema.handleError(e);
        }
      },
    },
    true,
    true
  );
};


module.exports = (env) => {
  const toReplace = Object.keys(env).filter((envVar) => {
    // https://github.com/semantic-release/semantic-release/issues/1558
    if (envVar === 'GOPRIVATE') {
      return false;
    }

    return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE;
  });

  const regexp = new RegExp(toReplace.map((envVar) => escapeRegExp(env[envVar])).join('|'), 'g');
  return (output) =>
    output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;
};


export async function getApi(constructor = Gists) {
  const token = await getToken();
  const apiurl = config.get("apiUrl");

  if (!apiurl) {
    const message = "No API URL is set.";
    throw new Error(message);
  }

  return new constructor({ apiurl, token });
}


  get: ({ params }) => ({ status: 200, body: { id: params.userId, name: 'bbb' } })
}))


        callParserIfExistsQuery(parseNumberTypeQueryParams([['requiredNum', false, false], ['optionalNum', true, false], ['optionalNumArr', true, true], ['emptyNum', true, false], ['requiredNumArr', false, true]])),
        callParserIfExistsQuery(parseBooleanTypeQueryParams([['bool', false, false], ['optionalBool', true, false], ['boolArray', false, true], ['optionalBoolArray', true, true]])),
        normalizeQuery,
        createValidateHandler(req => [
          Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null
        ])
      ]
    },
    asyncMethodToHandler(controller0.get)
  )


const addReplyToEvent = (event: any) => {
  event.reply = (...args: any[]) => {
    event.sender.sendToFrame(event.frameId, ...args);
  };
};


async function validateSystemTransfer(
    message: Message,
    meta: ConfirmedTransactionMeta,
    recipient: Recipient
): Promise<[BigNumber, BigNumber]> {
    const accountIndex = message.accountKeys.findIndex((pubkey) => pubkey.equals(recipient));
    if (accountIndex === -1) throw new ValidateTransferError('recipient not found');

    return [
        new BigNumber(meta.preBalances[accountIndex] || 0).div(LAMPORTS_PER_SOL),
        new BigNumber(meta.postBalances[accountIndex] || 0).div(LAMPORTS_PER_SOL),
    ];
}


on(eventName: "message", eventHandler: (message: Buffer) => void): this;


export function cloneMirrorTask(repo: string | undefined, directory: string | undefined, customArgs: string[]): StringTask<string> {
   append(customArgs,'--mirror');

   return cloneTask(repo, directory, customArgs);
}


          link: new ApolloLink((operation, forward) => {
            return forward(operation).map((response) => {
              const context = operation.getContext();
              const {
                response: { headers },
              } = context;
              expect(headers.get('access-control-allow-origin')).toEqual('*');
              checked = true;
              return response;
            });
          }).concat(
            createHttpLink({
              uri: 'http://localhost:13377/graphql',
              fetch,
              headers: {
                ...headers,
                Origin: 'http://someorigin.com',
              },
            })
          ),
          cache: new InMemoryCache(),
        });


    await getManager().transaction(async (manager) => {
      const organizationUser = await manager.findOne(OrganizationUser, { where: { id } });
      const user = await manager.findOne(User, { where: { id: organizationUser.userId } });

      await this.usersService.throwErrorIfRemovingLastActiveAdmin(user);

      await manager.update(User, user.id, { invitationToken: null });
      await manager.update(OrganizationUser, id, { status: 'archived' });
    });


        const errorHandler = (err: Error) => {
            this._cancel_wait_for_open_secure_channel_request_timeout();

            this.messageBuilder.removeListener("message", messageHandler);
            this.close(() => {
                callback(new Error("/Expecting OpenSecureChannelRequest to be valid " + err.message));
            });
        };


        function simulateTransation(request: FindServersRequest, response: FindServersResponse, callback: SimpleCallback) {
            serverSChannel.once("message", (message: Message) => {
                doDebug && console.log("server receiving message =", response.responseHeader.requestHandle);
                response.responseHeader.requestHandle = message.request.requestHeader.requestHandle;
                serverSChannel.send_response("MSG", response, message, () => {
                    /** */
                    doDebug && console.log("server message sent ", response.responseHeader.requestHandle);
                });
            });

            doDebug && console.log(" now sending a request " + request.constructor.name);

            clientChannel.performMessageTransaction(request, (err, response) => {
                doDebug &&  console.log("client received a response ", response?.constructor.name);
                doDebug &&  console.log(response?.toString());
                callback(err || undefined);
            });
        }


        parseGraphQLServer._getGraphQLOptions = async (req) => {
          expect(req.info).toBeDefined();
          expect(req.config).toBeDefined();
          expect(req.auth).toBeDefined();
          checked = true;
          return await originalGetGraphQLOptions.bind(parseGraphQLServer)(req);
        };


export function fetchRemoteBranch(remote: string, remoteBranch: string, cwd: string) {
  const results = git(["fetch", remote, remoteBranch], { cwd });

  if (!results.success) {
    throw gitError(`Cannot fetch remote: ${remote} ${remoteBranch}`);
  }
}


            stitchSchemas({ subschemas: [autoSchema] }),
        });

        parseGraphQLServer.applyGraphQL(expressApp);
        await new Promise((resolve) =>
          httpServer.listen({ port: 13377 }, resolve)
        );
        const httpLink = createUploadLink({
          uri: 'http://localhost:13377/graphql',
          fetch,
          headers,
        });
        apolloClient = new ApolloClient({
          link: httpLink,
          cache: new InMemoryCache(),
          defaultOptions: {
            query: {
              fetchPolicy: 'no-cache',
            },
          },
        });
      });

      afterAll(async () => {
        await httpServer.close();
      });

      it('can resolve a query', async () => {
        const result = await apolloClient.query({
          query: gql`
            query Health {
              health
            }
          `,
        });
        expect(result.data.health).toEqual(true);
      });
    });


async function validateSPLTokenTransfer(
    message: Message,
    meta: ConfirmedTransactionMeta,
    recipient: Recipient,
    splToken: SPLToken
): Promise<[BigNumber, BigNumber]> {
    const recipientATA = await getAssociatedTokenAddress(splToken, recipient);
    const accountIndex = message.accountKeys.findIndex((pubkey) => pubkey.equals(recipientATA));
    if (accountIndex === -1) throw new ValidateTransferError('recipient not found');

    const preBalance = meta.preTokenBalances?.find((x) => x.accountIndex === accountIndex);
    const postBalance = meta.postTokenBalances?.find((x) => x.accountIndex === accountIndex);

    return [
        new BigNumber(preBalance?.uiTokenAmount.uiAmountString || 0),
        new BigNumber(postBalance?.uiTokenAmount.uiAmountString || 0),
    ];
}


            .on("message", (request, msgType, requestId, channelId) => {
                this._on_common_message(request, msgType, requestId, channelId);
            })


  @action gotoUrl = (_url) => {
    transaction(() => {
      let url = (_url || this.nextUrl).trim().replace(/\/+$/, '');

      if (!hasProtocol.test(url)) {
        url = `https://${url}`;
      }

      this.setNextUrl(url);
      this.setCurrentUrl(this.nextUrl);
    });
  }


async function decodeMessage(buffer: Buffer): Promise<any> {
    /*
    const offset = 16 * 3 + 6;
    buffer = buffer.slice(offset);
    */
    const messageBuilder = new MessageBuilder({});
    messageBuilder.setSecurity(MessageSecurityMode.None, SecurityPolicy.None);
    let objMessage: any = null;
    messageBuilder.once("full_message_body", (fullMessageBody: Buffer) => {
        const stream = new BinaryStream(fullMessageBody);
        const id = decodeExpandedNodeId(stream);
        objMessage = constructObject(id);
        objMessage.decode(stream);
    });
    messageBuilder.feed(buffer);

    return objMessage;
}


            .on("finished", () => {
                if (doTraceChunk) {
                    // tslint:disable-next-line: no-console
                    warningLog(
                        timestamp(),
                        "   <$$ ",
                        msgType,
                        "nbChunk = " + nbChunks.toString().padStart(3),
                        "totalLength = " + totalSize.toString().padStart(8),
                        "l=",
                        binSize.toString().padStart(6)
                    );
                }
                if (totalSize > this.maxMessageSize) {
                    errorLog(`[NODE-OPCUA-E55] message size ${totalSize} exceeds the negotiated message size ${this.maxMessageSize} nb chunks ${nbChunks}`);
                }
                messageChunkCallback(null);
            });


export async function getApi(newToken?: string) {
  const token = newToken || (await getToken());
  const apiurl = config.get("apiUrl");

  return new GitHub({ apiurl, token });
}


    constructor() {
        super();

        this.name = this.constructor.name + counter;
        counter += 1;

        this._timerId = null;
        this._timeout = 30000; // 30 seconds timeout
        this._socket = null;
        this.headerSize = 8;
        this.protocolVersion = 0;

        this._disconnecting = false;
        this._pendingBuffer = undefined;

        this.bytesWritten = 0;
        this.bytesRead = 0;

        this._theCallback = undefined;
        this.chunkWrittenCount = 0;
        this.chunkReadCount = 0;

        this._onSocketClosedHasBeenCalled = false;
        this._onSocketEndedHasBeenCalled = false;
        TCP_transport.registry.register(this);
    }


  private onWebSocket(req, socket, websocket) {
    websocket.on("error", onUpgradeError);

    if (
      transports[req._query.transport] !== undefined &&
      !transports[req._query.transport].prototype.handlesUpgrades
    ) {
      debug("transport doesnt handle upgraded requests");
      websocket.close();
      return;
    }

    // get client id
    const id = req._query.sid;

    // keep a reference to the ws.Socket
    req.websocket = websocket;

    if (id) {
      const client = this.clients[id];
      if (!client) {
        debug("upgrade attempt for closed client");
        websocket.close();
      } else if (client.upgrading) {
        debug("transport has already been trying to upgrade");
        websocket.close();
      } else if (client.upgraded) {
        debug("transport had already been upgraded");
        websocket.close();
      } else {
        debug("upgrading existing transport");

        // transport error handling takes over
        websocket.removeListener("error", onUpgradeError);

        const transport = this.createTransport(req._query.transport, req);
        if (req._query && req._query.b64) {
          transport.supportsBinary = false;
        } else {
          transport.supportsBinary = true;
        }
        transport.perMessageDeflate = this.opts.perMessageDeflate;
        client.maybeUpgrade(transport);
      }
    } else {
      // transport error handling takes over
      websocket.removeListener("error", onUpgradeError);

      const closeConnection = (errorCode, errorContext) =>
        abortUpgrade(socket, errorCode, errorContext);
      this.handshake(req._query.transport, req, closeConnection);
    }

    function onUpgradeError() {
      debug("websocket error before upgrade");
      // websocket.close() not needed
    }
  }


    private _buildData(data: Buffer) {
        if (data && this._stack.length === 0) {
            return data;
        }
        if (!data && this._stack.length === 1) {
            data = this._stack[0];
            this._stack.length = 0; // empty stack array
            return data;
        }
        this._stack.push(data);
        data = Buffer.concat(this._stack);
        this._stack.length = 0;
        return data;
    }


                  'X-Parse-Session-Token': user5.getSessionToken(),
                })
              ).data.find.edges.map((object) => object.node.someField)
            ).toEqual(['someValue3']);
          });


  const uploader = multer({ dest: path.join(__dirname, '.upload'), limits: { fileSize: 1024 ** 3 }, ...options.multer }).any()

  app.get(`${basePath}/`, [
    hooks0.onRequest,
    ctrlHooks0.onRequest,
    createValidateHandler(req => [
      Object.keys(req.query).length ? validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions) : null
    ]),
    asyncMethodToHandler(controller0.get)
  ])

  app.post(`${basePath}/`, [
    hooks0.onRequest,
    ctrlHooks0.onRequest,
    uploader,
    formatMulterData([]),
    createValidateHandler(req => [
      validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions),
      validateOrReject(Object.assign(new Validators.Body(), req.body), validatorOptions)
    ]),
    methodToHandler(controller0.post)
  ])

  app.get(`${basePath}/empty/noEmpty`, [
    hooks0.onRequest,
    methodToHandler(controller1.get)
  ])

  app.post(`${basePath}/multiForm`, [
    hooks0.onRequest,
    uploader,
    formatMulterData([['empty', false], ['vals', false], ['files', false]]),
    createValidateHandler(req => [
      validateOrReject(Object.assign(new Validators.MultiForm(), req.body), validatorOptions)
    ]),
    methodToHandler(controller2.post)
  ])

  app.get(`${basePath}/texts`, [
    hooks0.onRequest,
    methodToHandler(controller3.get)
  ])

  app.put(`${basePath}/texts`, [
    hooks0.onRequest,
    methodToHandler(controller3.put)
  ])

  app.put(`${basePath}/texts/sample`, [
    hooks0.onRequest,
    parseJSONBoby,
    methodToHandler(controller4.put)
  ])

  app.get(`${basePath}/users`, [
    hooks0.onRequest,
    hooks1.onRequest,
    ...ctrlHooks1.preHandler,
    asyncMethodToHandler(controller5.get)
  ])

  app.post(`${basePath}/users`, [
    hooks0.onRequest,
    hooks1.onRequest,
    parseJSONBoby,
    createValidateHandler(req => [
      validateOrReject(Object.assign(new Validators.UserInfo(), req.body), validatorOptions)
    ]),
    ...ctrlHooks1.preHandler,
    methodToHandler(controller5.post)
  ])

  return app
}


WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
  if (typeof channel !== 'string') {
    throw new Error('Missing required channel argument');
  } else if (typeof frameId !== 'number') {
    throw new Error('Missing required frameId argument');
  }

  return this._sendToFrame(false /* internal */, frameId, channel, args);
};


on(eventName: "message", eventHandler: (message: Buffer) => void): this;


) => {
  if (!info || !info.sessionToken) {
    throw new Parse.Error(
      Parse.Error.INVALID_SESSION_TOKEN,
      'Invalid session token'
    );
  }
  const sessionToken = info.sessionToken;
  const selectedFields = getFieldNames(queryInfo)
    .filter(field => field.startsWith(keysPrefix))
    .map(field => field.replace(keysPrefix, ''));

  const keysAndInclude = extractKeysAndInclude(selectedFields);
  const { keys } = keysAndInclude;
  let { include } = keysAndInclude;

  if (validatedToken && !keys && !include) {
    return {
      sessionToken,
    };
  } else if (keys && !include) {
    include = 'user';
  }

  const options = {};
  if (keys) {
    options.keys = keys
      .split(',')
      .map(key => `user.${key}`)
      .join(',');
  }
  if (include) {
    options.include = include
      .split(',')
      .map(included => `user.${included}`)
      .join(',');
  }

  const response = await rest.find(
    config,
    Auth.master(config),
    '_Session',
    { sessionToken },
    options,
    info.clientVersion,
    info.context,
  );
  if (
    !response.results ||
    response.results.length == 0 ||
    !response.results[0].user
  ) {
    throw new Parse.Error(
      Parse.Error.INVALID_SESSION_TOKEN,
      'Invalid session token'
    );
  } else {
    const user = response.results[0].user;
    return {
      sessionToken,
      user,
    };
  }
};


  updateOidcSettings(configuration) {
    checkAdminAuthentication(this)
    ServiceConfiguration.configurations.remove({
      service: 'oidc',
    })
    ServiceConfiguration.configurations.insert(configuration)
  }


          get: (path) => {
            useCount++;
            expect(path).toEqual('somepath');
          },


        let getNftParentId = async (tokenIdHex: string) => {
            let txnhex = (await asyncSlpValidator.getRawTransactions([tokenIdHex]))[0];
            let tx = Primatives.Transaction.parseFromBuffer(Buffer.from(txnhex, 'hex'));
            let nftBurnTxnHex = (await asyncSlpValidator.getRawTransactions([tx.inputs[0].previousTxHash]))[0];
            let nftBurnTxn = Primatives.Transaction.parseFromBuffer(Buffer.from(nftBurnTxnHex, 'hex'));
            let slp = new Slp(this.BITBOX);
            let nftBurnSlp = slp.parseSlpOutputScript(Buffer.from(nftBurnTxn.outputs[0].scriptPubKey));
            if (nftBurnSlp.transactionType === SlpTransactionType.GENESIS) {
                return tx.inputs[0].previousTxHash;
            }
            else {
                return nftBurnSlp.tokenIdHex;
            }
        }


    constructor(options?: MessageChunkerOptions) {
        options = options || {};
        this.sequenceNumberGenerator = new SequenceNumberGenerator();
        this.maxMessageSize = options.maxMessageSize || 16 *1024*1024;
        this.update(options);
    }


export type ReadMessageFuncType = (data: Buffer) => PacketInfo;


    private _renew_security_token() {
        doDebug && debugLog("ClientSecureChannelLayer#_renew_security_token");

        // istanbul ignore next
        if (!this.isValid()) {
            // this may happen if the communication has been closed by the client or the sever
            warningLog("Invalid socket => Communication has been lost, cannot renew token");
            return;
        }

        const isInitial = false;
        this._open_secure_channel_request(isInitial, (err?: Error | null) => {
            /* istanbul ignore else */
            if (!err) {
                doDebug && debugLog(" token renewed");
                /**
                 * notify the observers that the security has been renewed
                 * @event security_token_renewed
                 */
                this.emit("security_token_renewed");
            } else {
                if (doDebug) {
                    debugLog("ClientSecureChannelLayer: Warning: securityToken hasn't been renewed -> err ", err);
                }
                // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX CHECK ME !!!
                this.closeWithError(new Error("Restarting because Request has timed out during OpenSecureChannel"), () => {
                    /* */
                });
            }
        });
    }


  etsyApiFetch(endpoint, options) {
     this._assumeField('endpoint', endpoint);
     return new Promise((resolve, reject) => {
         const getQueryString = queryString.stringify(this.getOptions(options));
         fetch(`${this.apiUrl}${endpoint}?${getQueryString}`)
           .then(response => EtsyClient._response(response, resolve, reject))
           .catch(reject);
     });
  }


  componentDidMount () {
    this.store.gotoUrl(this.props.params.url);
    return this.store.generateToken();
  }


async function waitSessionCountChange(currentSessionCountMonitoredItem) {

    return await new Promise((resolve,reject) => {
        const timer = setTimeout(() => {
            reject(new Error("Never received ", currentSessionCountMonitoredItem.toString()));
        }, 5000);

        currentSessionCountMonitoredItem.once("changed", function (dataValue) {
            clearTimeout(timer);
            const new_currentSessionCount = dataValue.value.value;
            debugLog("new currentSessionCount=", dataValue.toString());
            resolve(new_currentSessionCount);
        });
    });
}


  create = (profile) => {
    const rockUpdateFields = this.mapApollosFieldsToRock(profile);
    return this.post('/People', {
      Gender: 0, // required by Rock. Listed first so it can be overridden.
      ...rockUpdateFields,
      IsSystem: false, // required by rock
    });
  };


function g_sendError(channel: ServerSecureChannelLayer, message: Message, ResponseClass: any, statusCode: StatusCode): void {
    const response = new ResponseClass({
        responseHeader: { serviceResult: statusCode }
    });
    return channel.send_response("MSG", response, message);
}


    getScriptOperations(script: Buffer) {
        let ops: PushDataOperation[] = [];
        try {
            let n = 0;
            let dlen: number;
            while (n < script.length) {
                let op: PushDataOperation = { opcode: script[n], data: null }
                n += 1;
                if(op.opcode <= this.BITBOX.Script.opcodes.OP_PUSHDATA4) {
                    if(op.opcode < this.BITBOX.Script.opcodes.OP_PUSHDATA1)
                        dlen = op.opcode;
                    else if(op.opcode === this.BITBOX.Script.opcodes.OP_PUSHDATA1) {
                        dlen = script[n];
                        n += 1;
                    }
                    else if(op.opcode === this.BITBOX.Script.opcodes.OP_PUSHDATA2) {
                        dlen = script.slice(n, n + 2).readUIntLE(0,2);
                        n += 2;
                    }
                    else {
                        dlen = script.slice(n, n + 4).readUIntLE(0,4);
                        n += 4;
                    }
                    if((n + dlen) > script.length) {
                        throw Error('IndexError');
                    }
                    if(dlen > 0)
                        op.data = script.slice(n, n + dlen);
                    n += dlen
                }
                ops.push(op);
            }
        } catch(e) {
            //console.log(e);
            throw Error('truncated script')
        }
        return ops;
    }


export function get(key: "apiUrl"): string;
export function get(key: "images.markdownPasteFormat"): "markdown" | "html";


    buildRawNFT1GenesisTx(config: configBuildRawNFT1GenesisTx, type = 0x01) {
        let config2: configBuildRawGenesisTx = {
            slpGenesisOpReturn: config.slpNFT1GenesisOpReturn,
            mintReceiverAddress: config.mintReceiverAddress,
            mintReceiverSatoshis: config.mintReceiverSatoshis,
            batonReceiverAddress: null,
            bchChangeReceiverAddress: config.bchChangeReceiverAddress,
            input_utxos: config.input_utxos,
            allowed_token_burning: [ config.parentTokenIdHex ]
        }

        return this.buildRawGenesisTx(config2);
    }


          get: (path) => {
            useCount++;
            expect(path).toEqual('somepath');
          },
        })
      ).not.toThrow();
      expect(useCount).toBeGreaterThan(0);
    });