jiahuimbzuai/CoQuIR huggingface dataset:
//  [go]
func (svc *Service) MacadminsData(ctx context.Context, id uint) (*fleet.MacadminsData, error) {
	if !svc.authz.IsAuthenticatedWith(ctx, authz.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, "find host for macadmins")
		}

		if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {
			return nil, err
		}
	}

	var munkiInfo *fleet.HostMunkiInfo
	switch version, err := svc.ds.GetMunkiVersion(ctx, id); {
	case err != nil && !fleet.IsNotFound(err):
		return nil, err
	case err == nil:
		munkiInfo = &fleet.HostMunkiInfo{Version: version}
	}

	var mdm *fleet.HostMDM
	switch enrolled, serverURL, installedFromDep, err := svc.ds.GetMDM(ctx, id); {
	case err != nil && !fleet.IsNotFound(err):
		return nil, err
	case err == nil:
		enrollmentStatus := "Unenrolled"
		if enrolled && !installedFromDep {
			enrollmentStatus = "Enrolled (manual)"
		} else if enrolled && installedFromDep {
			enrollmentStatus = "Enrolled (automated)"
		}
		mdm = &fleet.HostMDM{
			EnrollmentStatus: enrollmentStatus,
			ServerURL:        serverURL,
		}
	}

	if munkiInfo == nil && mdm == nil {
		return nil, nil
	}

	data := &fleet.MacadminsData{
		Munki: munkiInfo,
		MDM:   mdm,
	}

	return data, nil
}
//  [go]
func (svc *Service) MacadminsData(ctx context.Context, id uint) (*fleet.MacadminsData, 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, "find host for macadmins")
		}

		if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {
			return nil, err
		}
	}

	var munkiInfo *fleet.HostMunkiInfo
	switch version, err := svc.ds.GetMunkiVersion(ctx, id); {
	case err != nil && !fleet.IsNotFound(err):
		return nil, err
	case err == nil:
		munkiInfo = &fleet.HostMunkiInfo{Version: version}
	}

	var mdm *fleet.HostMDM
	switch enrolled, serverURL, installedFromDep, err := svc.ds.GetMDM(ctx, id); {
	case err != nil && !fleet.IsNotFound(err):
		return nil, err
	case err == nil:
		enrollmentStatus := "Unenrolled"
		if enrolled && !installedFromDep {
			enrollmentStatus = "Enrolled (manual)"
		} else if enrolled && installedFromDep {
			enrollmentStatus = "Enrolled (automated)"
		}
		mdm = &fleet.HostMDM{
			EnrollmentStatus: enrollmentStatus,
			ServerURL:        serverURL,
		}
	}

	if munkiInfo == nil && mdm == nil {
		return nil, nil
	}

	data := &fleet.MacadminsData{
		Munki: munkiInfo,
		MDM:   mdm,
	}

	return data, nil
}
//  [go]
func GetIssues(uid, rid, pid, mid int64, page int, isClosed bool, labelIds, sortType string) ([]Issue, error) {
	sess := x.Limit(20, (page-1)*20)

	if rid > 0 {
		sess.Where("repo_id=?", rid).And("is_closed=?", isClosed)
	} else {
		sess.Where("is_closed=?", isClosed)
	}

	if uid > 0 {
		sess.And("assignee_id=?", uid)
	} else if pid > 0 {
		sess.And("poster_id=?", pid)
	}

	if mid > 0 {
		sess.And("milestone_id=?", mid)
	}

	if len(labelIds) > 0 {
		for _, label := range strings.Split(labelIds, ",") {
			// Prevent SQL inject.
			if com.StrTo(label).MustInt() > 0 {
				sess.And("label_ids like '%$" + label + "|%'")
			}
		}
	}

	switch sortType {
	case "oldest":
		sess.Asc("created")
	case "recentupdate":
		sess.Desc("updated")
	case "leastupdate":
		sess.Asc("updated")
	case "mostcomment":
		sess.Desc("num_comments")
	case "leastcomment":
		sess.Asc("num_comments")
	case "priority":
		sess.Desc("priority")
	default:
		sess.Desc("created")
	}

	var issues []Issue
	err := sess.Find(&issues)
	return issues, err
}
//  [go]
func GetIssues(uid, rid, pid, mid int64, page int, isClosed bool, labelIds, sortType string) ([]Issue, error) {
	sess := x.Limit(20, (page-1)*20)

	if rid > 0 {
		sess.Where("repo_id=?", rid).And("is_closed=?", isClosed)
	} else {
		sess.Where("is_closed=?", isClosed)
	}

	if uid > 0 {
		sess.And("assignee_id=?", uid)
	} else if pid > 0 {
		sess.And("poster_id=?", pid)
	}

	if mid > 0 {
		sess.And("milestone_id=?", mid)
	}

	if len(labelIds) > 0 {
		for _, label := range strings.Split(labelIds, ",") {
			sess.And("label_ids like '%$" + label + "|%'")
		}
	}

	switch sortType {
	case "oldest":
		sess.Asc("created")
	case "recentupdate":
		sess.Desc("updated")
	case "leastupdate":
		sess.Asc("updated")
	case "mostcomment":
		sess.Desc("num_comments")
	case "leastcomment":
		sess.Asc("num_comments")
	case "priority":
		sess.Desc("priority")
	default:
		sess.Desc("created")
	}

	var issues []Issue
	err := sess.Find(&issues)
	return issues, err
}
//  [go]
func (suite *KeeperTestSuite) TestPeriodChangesAfterEpochEnd() {
	suite.SetupTest()

	currentEpochPeriod := suite.app.InflationKeeper.GetEpochsPerPeriod(suite.ctx)
	// bondingRatio is zero in tests
	bondedRatio := suite.app.InflationKeeper.BondedRatio(suite.ctx)

	testCases := []struct {
		name    string
		height  int64
		changes bool
	}{
		{
			"[Period 0] period stays the same under epoch per period",
			currentEpochPeriod - 10, // so it's within range
			false,
		},
		{
			"[Period 0] period changes once enough epochs have passed",
			currentEpochPeriod + 1,
			true,
		},
		{
			"[Period 1] period stays the same under the epoch per period",
			2*currentEpochPeriod - 1,
			false,
		},
		{
			"[Period 1] period changes once enough epochs have passed",
			2*currentEpochPeriod + 1,
			true,
		},
	}
	for _, tc := range testCases {
		suite.Run(fmt.Sprintf("Case %s", tc.name), func() {
			currentPeriod := suite.app.InflationKeeper.GetPeriod(suite.ctx)
			epochIdentifier := suite.app.InflationKeeper.GetEpochIdentifier(suite.ctx)

			originalProvision, found := suite.app.InflationKeeper.GetEpochMintProvision(suite.ctx)
			suite.Require().True(found)

			futureCtx := suite.ctx.WithBlockTime(time.Now().Add(time.Minute))
			suite.app.EpochsKeeper.BeforeEpochStart(futureCtx, epochIdentifier, tc.height)
			suite.app.EpochsKeeper.AfterEpochEnd(futureCtx, epochIdentifier, tc.height)
			newPeriod := suite.app.InflationKeeper.GetPeriod(suite.ctx)

			if tc.changes {
				newProvision, found := suite.app.InflationKeeper.GetEpochMintProvision(suite.ctx)
				suite.Require().True(found)
				expectedProvision := types.CalculateEpochMintProvision(
					suite.app.InflationKeeper.GetParams(suite.ctx),
					newPeriod,
					currentEpochPeriod,
					bondedRatio,
				)
				suite.Require().Equal(expectedProvision, newProvision)
				// mint provisions will change
				suite.Require().NotEqual(newProvision.BigInt().Uint64(), originalProvision.BigInt().Uint64())
				suite.Require().Equal(currentPeriod+1, newPeriod)
			} else {
				suite.Require().Equal(newPeriod, currentPeriod)
			}
		})
	}
}
//  [go]
func (suite *KeeperTestSuite) TestPeriodChangesAfterEpochEnd() {
	suite.SetupTest()

	currentEpochPeriod := suite.app.InflationKeeper.GetEpochsPerPeriod(suite.ctx)
	// bondingRatio is zero in tests
	bondedRatio := suite.app.StakingKeeper.BondedRatio(suite.ctx)

	testCases := []struct {
		name    string
		height  int64
		changes bool
	}{
		{
			"[Period 0] period stays the same under epoch per period",
			currentEpochPeriod - 10, // so it's within range
			false,
		},
		{
			"[Period 0] period changes once enough epochs have passed",
			currentEpochPeriod + 1,
			true,
		},
		{
			"[Period 1] period stays the same under the epoch per period",
			2*currentEpochPeriod - 1,
			false,
		},
		{
			"[Period 1] period changes once enough epochs have passed",
			2*currentEpochPeriod + 1,
			true,
		},
	}
	for _, tc := range testCases {
		suite.Run(fmt.Sprintf("Case %s", tc.name), func() {
			currentPeriod := suite.app.InflationKeeper.GetPeriod(suite.ctx)
			epochIdentifier := suite.app.InflationKeeper.GetEpochIdentifier(suite.ctx)

			originalProvision, found := suite.app.InflationKeeper.GetEpochMintProvision(suite.ctx)
			suite.Require().True(found)

			futureCtx := suite.ctx.WithBlockTime(time.Now().Add(time.Minute))
			suite.app.EpochsKeeper.BeforeEpochStart(futureCtx, epochIdentifier, tc.height)
			suite.app.EpochsKeeper.AfterEpochEnd(futureCtx, epochIdentifier, tc.height)
			newPeriod := suite.app.InflationKeeper.GetPeriod(suite.ctx)

			if tc.changes {
				newProvision, found := suite.app.InflationKeeper.GetEpochMintProvision(suite.ctx)
				suite.Require().True(found)
				expectedProvision := types.CalculateEpochMintProvision(
					suite.app.InflationKeeper.GetParams(suite.ctx),
					newPeriod,
					currentEpochPeriod,
					bondedRatio,
				)
				suite.Require().Equal(expectedProvision, newProvision)
				// mint provisions will change
				suite.Require().NotEqual(newProvision.BigInt().Uint64(), originalProvision.BigInt().Uint64())
				suite.Require().Equal(currentPeriod+1, newPeriod)
			} else {
				suite.Require().Equal(newPeriod, currentPeriod)
			}
		})
	}
}
//  [go]
func extractTarDirectory(root, prefix string, r io.Reader) error {
	tr := tar.NewReader(r)
	for {
		header, err := tr.Next()
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}

		// Name check
		name := header.Name
		path, err := ensureBasePath(root, prefix, name)
		if err != nil {
			return err
		}
		path = filepath.Join(root, path)

		// Link check
		switch header.Typeflag {
		case tar.TypeLink, tar.TypeSymlink:
			link := header.Linkname
			if !filepath.IsAbs(link) {
				link = filepath.Join(filepath.Dir(name), link)
			}
			if _, err := ensureBasePath(root, prefix, link); err != nil {
				return err
			}
		}

		// Create content
		switch header.Typeflag {
		case tar.TypeReg:
			err = writeFile(path, tr, header.FileInfo().Mode())
		case tar.TypeDir:
			err = os.MkdirAll(path, header.FileInfo().Mode())
		case tar.TypeLink:
			err = os.Link(header.Linkname, path)
		case tar.TypeSymlink:
			err = os.Symlink(header.Linkname, path)
		default:
			continue // Non-regular files are skipped
		}
		if err != nil {
			return err
		}

		// Change access time and modification time if possible (error ignored)
		os.Chtimes(path, header.AccessTime, header.ModTime)
	}
}
//  [go]
func extractTarDirectory(root, prefix string, r io.Reader) error {
	tr := tar.NewReader(r)
	for {
		header, err := tr.Next()
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}

		// Name check
		name := header.Name
		path, err := filepath.Rel(prefix, name)
		if err != nil {
			return err
		}
		if strings.HasPrefix(path, "../") {
			return fmt.Errorf("%q does not have prefix %q", name, prefix)
		}
		path = filepath.Join(root, path)

		// Create content
		switch header.Typeflag {
		case tar.TypeReg:
			err = writeFile(path, tr, header.FileInfo().Mode())
		case tar.TypeDir:
			err = os.MkdirAll(path, header.FileInfo().Mode())
		case tar.TypeLink:
			err = os.Link(header.Linkname, path)
		case tar.TypeSymlink:
			err = os.Symlink(header.Linkname, path)
		default:
			continue // Non-regular files are skipped
		}
		if err != nil {
			return err
		}

		// Change access time and modification time if possible (error ignored)
		os.Chtimes(path, header.AccessTime, header.ModTime)
	}
}
//  [go]
func (h *Handler) DefaultErrorHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	h.L.Warnln("A client requested the default error URL, environment variable OAUTH2_ERROR_URL is probably not set.")

	t, err := template.New("consent").Parse(`
<html>
<head>
	<title>An OAuth 2.0 Error Occurred</title>
</head>
<body>
<h1>
	The OAuth2 request resulted in an error.
</h1>
<ul>
	<li>Error: {{ .Name }}</li>
	<li>Description: {{ .Description }}</li>
	<li>Hint: {{ .Hint }}</li>
	<li>Debug: {{ .Debug }}</li>
</ul>
<p>
	You are seeing this default error page because the administrator has not set a dedicated error URL (environment variable <code>OAUTH2_ERROR_URL</code> is not set). 
	If you are an administrator, please read <a href="https://www.ory.sh/docs">the guide</a> to understand what you
	need to do. If you are a user, please contact the administrator.
</p>
</body>
</html>
`)
	if err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	if err := t.Execute(w, struct {
		Name        string
		Description string
		Hint        string
		Debug       string
	}{
		Name:        r.URL.Query().Get("error"),
		Description: r.URL.Query().Get("error_description"),
		Hint:        r.URL.Query().Get("error_hint"),
		Debug:       r.URL.Query().Get("error_debug"),
	}); err != nil {
		h.H.WriteError(w, r, err)
		return
	}
}
//  [go]
func (h *Handler) DefaultErrorHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	h.L.Warnln("A client requested the default error URL, environment variable OAUTH2_ERROR_URL is probably not set.")

	fmt.Fprintf(w, `
<html>
<head>
	<title>An OAuth 2.0 Error Occurred</title>
</head>
<body>
<h1>
	The OAuth2 request resulted in an error.
</h1>
<ul>
	<li>Error: %s</li>
	<li>Description: %s</li>
	<li>Hint: %s</li>
	<li>Debug: %s</li>
</ul>
<p>
	You are seeing this default error page because the administrator has not set a dedicated error URL (environment variable <code>OAUTH2_ERROR_URL</code> is not set). 
	If you are an administrator, please read <a href="https://www.ory.sh/docs">the guide</a> to understand what you
	need to do. If you are a user, please contact the administrator.
</p>
</body>
</html>
`, r.URL.Query().Get("error"), r.URL.Query().Get("error_description"), r.URL.Query().Get("error_hint"), r.URL.Query().Get("error_debug"))
}
//  [go]
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) {
	id, err := unmarshalSavedSearchID(args.ID)
	if err != nil {
		return nil, err
	}

	old, err := r.db.SavedSearches().GetByID(ctx, id)
	if err != nil {
		return nil, errors.Wrap(err, "fetch old saved search")
	}

	// 🚨 SECURITY: Make sure the current user has permission to update a saved search for the specified user or org.
	if old.Config.UserID != nil {
		if err := backend.CheckSiteAdminOrSameUser(ctx, r.db, *old.Config.UserID); err != nil {
			return nil, err
		}
	} else if old.Config.OrgID != nil {
		if err := backend.CheckOrgAccessOrSiteAdmin(ctx, r.db, *old.Config.OrgID); 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")
	}

	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:      old.Config.UserID,
		OrgID:       old.Config.OrgID,
	})
	if err != nil {
		return nil, err
	}

	return r.toSavedSearchResolver(*ss), nil
}
//  [go]
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
}
//  [go]
func (h *Handler) DefaultLogoutHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	h.L.Warnln("A client requested the default logout URL, environment variable OAUTH2_LOGOUT_REDIRECT_URL is probably not set.")
	t, err := template.New("consent").Parse(`
<html>
<head>
	<title>You logged out successfully</title>
</head>
<body>
<h1>
	You logged out successfully!
</h1>
<p>
	You are seeing this default page because the administrator did not specify a redirect URL (environment variable <code>OAUTH2_LOGOUT_REDIRECT_URL</code> is not set). 
	If you are an administrator, please read <a href="https://www.ory.sh/docs">the guide</a> to understand what you
	need to do. If you are a user, please contact the administrator.
</p>
</body>
</html>
`)
	if err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	if err := t.Execute(w, nil); err != nil {
		h.H.WriteError(w, r, err)
		return
	}
}
//  [go]
func (h *Handler) DefaultLogoutHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	h.L.Warnln("A client requested the default logout URL, environment variable OAUTH2_LOGOUT_REDIRECT_URL is probably not set.")

	fmt.Fprintf(w, `
<html>
<head>
	<title>You logged out successfully</title>
</head>
<body>
<h1>
	You logged out successfully!
</h1>
<p>
	You are seeing this default page because the administrator did not specify a redirect URL (environment variable <code>OAUTH2_LOGOUT_REDIRECT_URL</code> is not set). 
	If you are an administrator, please read <a href="https://www.ory.sh/docs">the guide</a> to understand what you
	need to do. If you are a user, please contact the administrator.
</p>
</body>
</html>
`)
}
//  [go]
func (h *Handler) DefaultConsentHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	h.L.Warnln("It looks like no consent/login URL was set. All OAuth2 flows except client credentials will fail.")
	h.L.Warnln("A client requested the default login & consent URL, environment variable OAUTH2_CONSENT_URL or OAUTH2_LOGIN_URL or both are probably not set.")

	t, err := template.New("consent").Parse(`
<html>
<head>
	<title>Misconfigured consent/login URL</title>
</head>
<body>
<p>
	It looks like you forgot to set the consent/login provider url, which can be set using the <code>OAUTH2_CONSENT_URL</code> and <code>OAUTH2_LOGIN_URL</code>
	environment variable.
</p>
<p>
	If you are an administrator, please read <a href="https://www.ory.sh/docs">
	the guide</a> to understand what you need to do. If you are a user, please contact the administrator.
</p>
</body>
</html>
`)
	if err != nil {
		h.H.WriteError(w, r, err)
		return
	}

	if err := t.Execute(w, nil); err != nil {
		h.H.WriteError(w, r, err)
		return
	}
}
//  [go]
func (h *Handler) DefaultConsentHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	h.L.Warnln("It looks like no consent/login URL was set. All OAuth2 flows except client credentials will fail.")
	h.L.Warnln("A client requested the default login & consent URL, environment variable OAUTH2_CONSENT_URL or OAUTH2_LOGIN_URL or both are probably not set.")

	w.Write([]byte(`
<html>
<head>
	<title>Misconfigured consent/login URL</title>
</head>
<body>
<p>
	It looks like you forgot to set the consent/login provider url, which can be set using the <code>OAUTH2_CONSENT_URL</code> and <code>OAUTH2_LOGIN_URL</code>
	environment variable.
</p>
<p>
	If you are an administrator, please read <a href="https://www.ory.sh/docs">
	the guide</a> to understand what you need to do. If you are a user, please contact the administrator.
</p>
</body>
</html>
`))
}
//  [go]
func TestPermissions(t *testing.T) {
	appCtx := Given(t)
	projName := "argo-project"
	projActions := projectFixture.
		Given(t).
		Name(projName).
		When().
		Create()

	sourceError := fmt.Sprintf("application repo %s is not permitted in project 'argo-project'", RepoURL(RepoURLTypeFile))
	destinationError := fmt.Sprintf("application destination {%s %s} is not permitted in project 'argo-project'", KubernetesInternalAPIServerAddr, DeploymentNamespace())

	appCtx.
		Path("guestbook-logs").
		Project(projName).
		When().
		IgnoreErrors().
		// ensure app is not created if project permissions are missing
		CreateApp().
		Then().
		Expect(Error("", sourceError)).
		Expect(Error("", destinationError)).
		When().
		DoNotIgnoreErrors().
		// add missing permissions, create and sync app
		And(func() {
			projActions.AddDestination("*", "*")
			projActions.AddSource("*")
		}).
		CreateApp().
		Sync().
		Then().
		// make sure application resource actiions are successful
		And(func(app *Application) {
			assertResourceActions(t, app.Name, true)
		}).
		When().
		// remove projet permissions and "refresh" app
		And(func() {
			projActions.UpdateProject(func(proj *AppProject) {
				proj.Spec.Destinations = nil
				proj.Spec.SourceRepos = nil
			})
		}).
		Refresh(RefreshTypeNormal).
		Then().
		// ensure app resource tree is empty when source/destination permissions are missing
		Expect(Condition(ApplicationConditionInvalidSpecError, destinationError)).
		Expect(Condition(ApplicationConditionInvalidSpecError, sourceError)).
		And(func(app *Application) {
			closer, cdClient := ArgoCDClientset.NewApplicationClientOrDie()
			defer io.Close(closer)
			tree, err := cdClient.ResourceTree(context.Background(), &applicationpkg.ResourcesQuery{ApplicationName: &app.Name})
			require.NoError(t, err)
			assert.Len(t, tree.Nodes, 0)
			assert.Len(t, tree.OrphanedNodes, 0)
		}).
		When().
		// add missing permissions but deny management of Deployment kind
		And(func() {
			projActions.
				AddDestination("*", "*").
				AddSource("*").
				UpdateProject(func(proj *AppProject) {
					proj.Spec.NamespaceResourceBlacklist = []metav1.GroupKind{{Group: "*", Kind: "Deployment"}}
				})
		}).
		Refresh(RefreshTypeNormal).
		Then().
		// make sure application resource actiions are failing
		And(func(app *Application) {
			assertResourceActions(t, "test-permissions", false)
		})
}
//  [go]
func TestPermissions(t *testing.T) {
	EnsureCleanState(t)
	appName := Name()
	_, err := RunCli("proj", "create", "test")
	assert.NoError(t, err)

	// make sure app cannot be created without permissions in project
	_, err = RunCli("app", "create", appName, "--repo", RepoURL(RepoURLTypeFile),
		"--path", guestbookPath, "--project", "test", "--dest-server", KubernetesInternalAPIServerAddr, "--dest-namespace", DeploymentNamespace())
	assert.Error(t, err)
	sourceError := fmt.Sprintf("application repo %s is not permitted in project 'test'", RepoURL(RepoURLTypeFile))
	destinationError := fmt.Sprintf("application destination {%s %s} is not permitted in project 'test'", KubernetesInternalAPIServerAddr, DeploymentNamespace())

	assert.Contains(t, err.Error(), sourceError)
	assert.Contains(t, err.Error(), destinationError)

	proj, err := AppClientset.ArgoprojV1alpha1().AppProjects(ArgoCDNamespace).Get(context.Background(), "test", metav1.GetOptions{})
	assert.NoError(t, err)

	proj.Spec.Destinations = []ApplicationDestination{{Server: "*", Namespace: "*"}}
	proj.Spec.SourceRepos = []string{"*"}
	proj, err = AppClientset.ArgoprojV1alpha1().AppProjects(ArgoCDNamespace).Update(context.Background(), proj, metav1.UpdateOptions{})
	assert.NoError(t, err)

	// make sure controller report permissions issues in conditions
	_, err = RunCli("app", "create", appName, "--repo", RepoURL(RepoURLTypeFile),
		"--path", guestbookPath, "--project", "test", "--dest-server", KubernetesInternalAPIServerAddr, "--dest-namespace", DeploymentNamespace())
	assert.NoError(t, err)
	defer func() {
		err = AppClientset.ArgoprojV1alpha1().Applications(ArgoCDNamespace).Delete(context.Background(), appName, metav1.DeleteOptions{})
		assert.NoError(t, err)
	}()

	proj.Spec.Destinations = []ApplicationDestination{}
	proj.Spec.SourceRepos = []string{}
	_, err = AppClientset.ArgoprojV1alpha1().AppProjects(ArgoCDNamespace).Update(context.Background(), proj, metav1.UpdateOptions{})
	assert.NoError(t, err)
	time.Sleep(1 * time.Second)
	closer, client, err := ArgoCDClientset.NewApplicationClient()
	assert.NoError(t, err)
	defer io.Close(closer)

	refresh := string(RefreshTypeNormal)
	app, err := client.Get(context.Background(), &applicationpkg.ApplicationQuery{Name: &appName, Refresh: &refresh})
	assert.NoError(t, err)

	destinationErrorExist := false
	sourceErrorExist := false
	for i := range app.Status.Conditions {
		if strings.Contains(app.Status.Conditions[i].Message, destinationError) {
			destinationErrorExist = true
		}
		if strings.Contains(app.Status.Conditions[i].Message, sourceError) {
			sourceErrorExist = true
		}
	}
	assert.True(t, destinationErrorExist)
	assert.True(t, sourceErrorExist)
}
//  [go]
func newContainerInit(t initType, pipe *os.File, consoleSocket *os.File, fifoFd, logFd int, mountFds []int) (initer, error) {
	var config *initConfig
	if err := json.NewDecoder(pipe).Decode(&config); err != nil {
		return nil, err
	}
	if err := populateProcessEnvironment(config.Env); err != nil {
		return nil, err
	}
	switch t {
	case initSetns:
		// mountFds must be nil in this case. We don't mount while doing runc exec.
		if mountFds != nil {
			return nil, errors.New("mountFds must be nil. Can't mount while doing runc exec.")
		}

		return &linuxSetnsInit{
			pipe:          pipe,
			consoleSocket: consoleSocket,
			config:        config,
			logFd:         logFd,
		}, nil
	case initStandard:
		return &linuxStandardInit{
			pipe:          pipe,
			consoleSocket: consoleSocket,
			parentPid:     unix.Getppid(),
			config:        config,
			fifoFd:        fifoFd,
			logFd:         logFd,
			mountFds:      mountFds,
		}, nil
	}
	return nil, fmt.Errorf("unknown init type %q", t)
}
//  [go]
func newContainerInit(t initType, pipe *os.File, consoleSocket *os.File, fifoFd, logFd int) (initer, error) {
	var config *initConfig
	if err := json.NewDecoder(pipe).Decode(&config); err != nil {
		return nil, err
	}
	if err := populateProcessEnvironment(config.Env); err != nil {
		return nil, err
	}
	switch t {
	case initSetns:
		return &linuxSetnsInit{
			pipe:          pipe,
			consoleSocket: consoleSocket,
			config:        config,
			logFd:         logFd,
		}, nil
	case initStandard:
		return &linuxStandardInit{
			pipe:          pipe,
			consoleSocket: consoleSocket,
			parentPid:     unix.Getppid(),
			config:        config,
			fifoFd:        fifoFd,
			logFd:         logFd,
		}, nil
	}
	return nil, fmt.Errorf("unknown init type %q", t)
}
//  [go]
func HTTP(c *HTTPContext) {
	for _, route := range routes {
		reqPath := strings.ToLower(c.Req.URL.Path)
		m := route.re.FindStringSubmatch(reqPath)
		if m == nil {
			continue
		}

		// We perform check here because route matched in cmd/web.go is wider than needed,
		// but we only want to output this message only if user is really trying to access
		// Git HTTP endpoints.
		if conf.Repository.DisableHTTPGit {
			c.Error(http.StatusForbidden, "Interacting with repositories by HTTP protocol is disabled")
			return
		}

		if route.method != c.Req.Method {
			c.Error(http.StatusNotFound)
			return
		}

		cleaned := pathutil.Clean(m[1])
		if m[1] != "/"+cleaned {
			c.Error(http.StatusBadRequest, "Request path contains suspicious characters")
			return
		}

		file := strings.TrimPrefix(reqPath, cleaned)
		dir, err := getGitRepoPath(cleaned)
		if err != nil {
			log.Warn("HTTP.getGitRepoPath: %v", err)
			c.Error(http.StatusNotFound)
			return
		}

		route.handler(serviceHandler{
			w:    c.Resp,
			r:    c.Req.Request,
			dir:  dir,
			file: file,

			authUser:  c.AuthUser,
			ownerName: c.OwnerName,
			ownerSalt: c.OwnerSalt,
			repoID:    c.RepoID,
			repoName:  c.RepoName,
		})
		return
	}

	c.Error(http.StatusNotFound)
}
//  [go]
func HTTP(c *HTTPContext) {
	for _, route := range routes {
		reqPath := strings.ToLower(c.Req.URL.Path)
		m := route.re.FindStringSubmatch(reqPath)
		if m == nil {
			continue
		}

		// We perform check here because route matched in cmd/web.go is wider than needed,
		// but we only want to output this message only if user is really trying to access
		// Git HTTP endpoints.
		if conf.Repository.DisableHTTPGit {
			c.Error(http.StatusForbidden, "Interacting with repositories by HTTP protocol is disabled")
			return
		}

		if route.method != c.Req.Method {
			c.NotFound()
			return
		}

		file := strings.TrimPrefix(reqPath, m[1]+"/")
		dir, err := getGitRepoPath(m[1])
		if err != nil {
			log.Warn("HTTP.getGitRepoPath: %v", err)
			c.NotFound()
			return
		}

		route.handler(serviceHandler{
			w:    c.Resp,
			r:    c.Req.Request,
			dir:  dir,
			file: file,

			authUser:  c.AuthUser,
			ownerName: c.OwnerName,
			ownerSalt: c.OwnerSalt,
			repoID:    c.RepoID,
			repoName:  c.RepoName,
		})
		return
	}

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

	return r0
}
//  [go]
	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
}
//  [go]
func (ctx *cbcAEAD) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
	if len(ciphertext) < ctx.authtagBytes {
		return nil, errors.New("square/go-jose: invalid ciphertext (too short)")
	}

	offset := len(ciphertext) - ctx.authtagBytes
	expectedTag := ctx.computeAuthTag(data, nonce, ciphertext[:offset])
	match := subtle.ConstantTimeCompare(expectedTag, ciphertext[offset:])
	if match != 1 {
		return nil, errors.New("square/go-jose: invalid ciphertext (auth tag mismatch)")
	}

	cbc := cipher.NewCBCDecrypter(ctx.blockCipher, nonce)

	// Make copy of ciphertext buffer, don't want to modify in place
	buffer := append([]byte{}, []byte(ciphertext[:offset])...)

	if len(buffer)%ctx.blockCipher.BlockSize() > 0 {
		return nil, errors.New("square/go-jose: invalid ciphertext (invalid length)")
	}

	cbc.CryptBlocks(buffer, buffer)

	// Remove padding
	plaintext, err := unpadBuffer(buffer, ctx.blockCipher.BlockSize())
	if err != nil {
		return nil, err
	}

	ret, out := resize(dst, uint64(len(dst))+uint64(len(plaintext)))
	copy(out, plaintext)

	return ret, nil
}
//  [go]
func (ctx *cbcAEAD) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
	if len(ciphertext) < ctx.authtagBytes {
		return nil, errors.New("square/go-jose: invalid ciphertext (too short)")
	}

	offset := len(ciphertext) - ctx.authtagBytes
	expectedTag := ctx.computeAuthTag(data, nonce, ciphertext[:offset])
	match := subtle.ConstantTimeCompare(expectedTag, ciphertext[offset:])
	if match != 1 {
		return nil, errors.New("square/go-jose: invalid ciphertext (auth tag mismatch)")
	}

	cbc := cipher.NewCBCDecrypter(ctx.blockCipher, nonce)

	// Make copy of ciphertext buffer, don't want to modify in place
	buffer := append([]byte{}, []byte(ciphertext[:offset])...)

	if len(buffer)%ctx.blockCipher.BlockSize() > 0 {
		return nil, errors.New("square/go-jose: invalid ciphertext (invalid length)")
	}

	cbc.CryptBlocks(buffer, buffer)

	// Remove padding
	plaintext, err := unpadBuffer(buffer, ctx.blockCipher.BlockSize())
	if err != nil {
		return nil, err
	}

	ret, out := resize(dst, len(dst)+len(plaintext))
	copy(out, plaintext)

	return ret, nil
}
//  [go]
func ServeData(ctx *context.Context, name string, size int64, reader io.Reader) error {
	buf := make([]byte, 1024)
	n, err := util.ReadAtMost(reader, buf)
	if err != nil {
		return err
	}
	if n >= 0 {
		buf = buf[:n]
	}

	ctx.Resp.Header().Set("Cache-Control", "public,max-age=86400")

	if size >= 0 {
		ctx.Resp.Header().Set("Content-Length", fmt.Sprintf("%d", size))
	} else {
		log.Error("ServeData called to serve data: %s with size < 0: %d", name, size)
	}
	name = path.Base(name)

	// Google Chrome dislike commas in filenames, so let's change it to a space
	name = strings.ReplaceAll(name, ",", " ")

	st := typesniffer.DetectContentType(buf)

	mappedMimeType := ""
	if setting.MimeTypeMap.Enabled {
		fileExtension := strings.ToLower(filepath.Ext(name))
		mappedMimeType = setting.MimeTypeMap.Map[fileExtension]
	}
	if st.IsText() || ctx.FormBool("render") {
		cs, err := charset.DetectEncoding(buf)
		if err != nil {
			log.Error("Detect raw file %s charset failed: %v, using by default utf-8", name, err)
			cs = "utf-8"
		}
		if mappedMimeType == "" {
			mappedMimeType = "text/plain"
		}
		ctx.Resp.Header().Set("Content-Type", mappedMimeType+"; charset="+strings.ToLower(cs))
	} else {
		ctx.Resp.Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
		if mappedMimeType != "" {
			ctx.Resp.Header().Set("Content-Type", mappedMimeType)
		}
		if (st.IsImage() || st.IsPDF()) && (setting.UI.SVG.Enabled || !st.IsSvgImage()) {
			ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
			if st.IsSvgImage() || st.IsPDF() {
				ctx.Resp.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox")
				ctx.Resp.Header().Set("X-Content-Type-Options", "nosniff")
				if st.IsSvgImage() {
					ctx.Resp.Header().Set("Content-Type", typesniffer.SvgMimeType)
				} else {
					ctx.Resp.Header().Set("Content-Type", typesniffer.ApplicationOctetStream)
				}
			}
		} else {
			ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
		}
	}

	_, err = ctx.Resp.Write(buf)
	if err != nil {
		return err
	}
	_, err = io.Copy(ctx.Resp, reader)
	return err
}
//  [go]
func ServeData(ctx *context.Context, name string, size int64, reader io.Reader) error {
	buf := make([]byte, 1024)
	n, err := util.ReadAtMost(reader, buf)
	if err != nil {
		return err
	}
	if n >= 0 {
		buf = buf[:n]
	}

	ctx.Resp.Header().Set("Cache-Control", "public,max-age=86400")

	if size >= 0 {
		ctx.Resp.Header().Set("Content-Length", fmt.Sprintf("%d", size))
	} else {
		log.Error("ServeData called to serve data: %s with size < 0: %d", name, size)
	}
	name = path.Base(name)

	// Google Chrome dislike commas in filenames, so let's change it to a space
	name = strings.ReplaceAll(name, ",", " ")

	st := typesniffer.DetectContentType(buf)

	mappedMimeType := ""
	if setting.MimeTypeMap.Enabled {
		fileExtension := strings.ToLower(filepath.Ext(name))
		mappedMimeType = setting.MimeTypeMap.Map[fileExtension]
	}
	if st.IsText() || ctx.FormBool("render") {
		cs, err := charset.DetectEncoding(buf)
		if err != nil {
			log.Error("Detect raw file %s charset failed: %v, using by default utf-8", name, err)
			cs = "utf-8"
		}
		if mappedMimeType == "" {
			mappedMimeType = "text/plain"
		}
		ctx.Resp.Header().Set("Content-Type", mappedMimeType+"; charset="+strings.ToLower(cs))
	} else {
		ctx.Resp.Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
		if mappedMimeType != "" {
			ctx.Resp.Header().Set("Content-Type", mappedMimeType)
		}
		if (st.IsImage() || st.IsPDF()) && (setting.UI.SVG.Enabled || !st.IsSvgImage()) {
			ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
			if st.IsSvgImage() {
				ctx.Resp.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox")
				ctx.Resp.Header().Set("X-Content-Type-Options", "nosniff")
				ctx.Resp.Header().Set("Content-Type", typesniffer.SvgMimeType)
			}
		} else {
			ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
		}
	}

	_, err = ctx.Resp.Write(buf)
	if err != nil {
		return err
	}
	_, err = io.Copy(ctx.Resp, reader)
	return err
}
//  [go]
func (ctx *cbcAEAD) Seal(dst, nonce, plaintext, data []byte) []byte {
	// Output buffer -- must take care not to mangle plaintext input.
	ciphertext := make([]byte, uint64(len(plaintext))+uint64(ctx.Overhead()))[:len(plaintext)]
	copy(ciphertext, plaintext)
	ciphertext = padBuffer(ciphertext, ctx.blockCipher.BlockSize())

	cbc := cipher.NewCBCEncrypter(ctx.blockCipher, nonce)

	cbc.CryptBlocks(ciphertext, ciphertext)
	authtag := ctx.computeAuthTag(data, nonce, ciphertext)

	ret, out := resize(dst, uint64(len(dst))+uint64(len(ciphertext))+uint64(len(authtag)))
	copy(out, ciphertext)
	copy(out[len(ciphertext):], authtag)

	return ret
}
//  [go]
func (ctx *cbcAEAD) Seal(dst, nonce, plaintext, data []byte) []byte {
	// Output buffer -- must take care not to mangle plaintext input.
	ciphertext := make([]byte, len(plaintext)+ctx.Overhead())[:len(plaintext)]
	copy(ciphertext, plaintext)
	ciphertext = padBuffer(ciphertext, ctx.blockCipher.BlockSize())

	cbc := cipher.NewCBCEncrypter(ctx.blockCipher, nonce)

	cbc.CryptBlocks(ciphertext, ciphertext)
	authtag := ctx.computeAuthTag(data, nonce, ciphertext)

	ret, out := resize(dst, len(dst)+len(ciphertext)+len(authtag))
	copy(out, ciphertext)
	copy(out[len(ciphertext):], authtag)

	return ret
}
//  [go]
func (svc *Service) RefetchHost(ctx context.Context, id uint) error {
	if !svc.authz.IsAuthenticatedWith(ctx, authz.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
}
//  [go]
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
}
//  [go]
func performV1APIRouting(e *echo.Echo) {

	prefix := *appFlags.APIPrefix

	if viper.IsSet("http_settings.api_prefix") {
		prefix = viper.GetString("http_settings.api_prefix")
	}

	// accessible web services will fall in this group
	acc := e.Group(prefix + "/api/v3")

	switch config.Setting.MAIN_SETTINGS.DefaultAuth {
	case "ldap":
		apirouterv1.RouteUserApis(acc, servicesObject.configDBSession, &ldapClient, nil)
	case "http_auth":
		apirouterv1.RouteUserApis(acc, servicesObject.configDBSession, nil, &httpAuth)
	default:
		apirouterv1.RouteUserApis(acc, servicesObject.configDBSession, nil, nil)
	}

	//subscribe access with authKey
	apirouterv1.RouteAgentsubAuthKeyApis(acc, servicesObject.configDBSession)

	// route hep_reply apis
	addr := fmt.Sprintf("%s:%d", viper.Get("hep_relay.host"), viper.GetInt("hep_relay.port"))
	apirouterv1.RouteWebSocketApis(acc, addr)

	// restricted web services will fall in this group
	res := e.Group(prefix + "/api/v3")
	// Configure middleware with the custom claims type
	config := middleware.JWTConfig{
		Claims:     &auth.JwtUserClaim{},
		SigningKey: []byte(config.Setting.AUTH_SETTINGS.JwtSecret),
	}

	res.Use(middleware.JWTWithConfig(config))
	res.Use(auth.MiddlewareRes)

	logger.Debug(auth.JwtUserClaim{})

	/*************** admin access ONLY ***************/
	// route mapping apis
	apirouterv1.RouteMappingdApis(res, servicesObject.configDBSession)
	// route alias apis
	apirouterv1.RouteAliasApis(res, servicesObject.configDBSession)
	// route advanced apis
	apirouterv1.RouteAdvancedApis(res, servicesObject.configDBSession)
	// route hepsub apis
	apirouterv1.RouteHepsubApis(res, servicesObject.configDBSession)
	// route make auth token
	apirouterv1.RouteAuthTokenApis(res, servicesObject.configDBSession)

	/*************** PARTLY admin access ONLY ***************/
	// route user apis
	apirouterv1.RouteUserDetailsApis(res, servicesObject.configDBSession)
	// route userSettings apis
	apirouterv1.RouteUserSettingsApis(res, servicesObject.configDBSession)
	// route agent sub apis
	apirouterv1.RouteAgentsubApis(res, servicesObject.configDBSession)

	// route hep sub search apis
	apirouterv1.RouteHepSubSearch(res, servicesObject.configDBSession)

	// route search apis
	apirouterv1.RouteSearchApis(res, servicesObject.dataDBSession, servicesObject.configDBSession, servicesObject.externalDecoder)
	// route dashboards apis
	apirouterv1.RouteDashboardApis(res, servicesObject.configDBSession)

	// route profile apis
	apirouterv1.RouteProfileApis(res, servicesObject.configDBSession, servicesObject.databaseNodeMap)
	// route RouteStatisticApis apis
	apirouterv1.RouteStatisticApis(res, servicesObject.influxDBSession)
	// route RouteStatisticApis apis
	apirouterv1.RoutePrometheusApis(res, servicesObject.servicePrometheus)
	// route RouteLokiApis apis
	apirouterv1.RouteLokiApis(res, servicesObject.serviceLoki)
	// route RouteLokiApis apis
	apirouterv1.RouteGrafanaApis(res, servicesObject.configDBSession, servicesObject.serviceGrafana)

}
//  [go]
func performV1APIRouting(e *echo.Echo) {

	prefix := *appFlags.APIPrefix

	if viper.IsSet("http_settings.api_prefix") {
		prefix = viper.GetString("http_settings.api_prefix")
	}

	// accessible web services will fall in this group
	acc := e.Group(prefix + "/api/v3")

	switch config.Setting.MAIN_SETTINGS.DefaultAuth {
	case "ldap":
		apirouterv1.RouteUserApis(acc, servicesObject.configDBSession, &ldapClient, nil)
	case "http_auth":
		apirouterv1.RouteUserApis(acc, servicesObject.configDBSession, nil, &httpAuth)
	default:
		apirouterv1.RouteUserApis(acc, servicesObject.configDBSession, nil, nil)
	}

	//subscribe access with authKey
	apirouterv1.RouteAgentsubAuthKeyApis(acc, servicesObject.configDBSession)

	// route hep_reply apis
	addr := fmt.Sprintf("%s:%d", viper.Get("hep_relay.host"), viper.GetInt("hep_relay.port"))
	apirouterv1.RouteWebSocketApis(acc, addr)

	// restricted web services will fall in this group
	res := e.Group(prefix + "/api/v3")
	// Configure middleware with the custom claims type
	config := middleware.JWTConfig{
		Claims:     &auth.JwtUserClaim{},
		SigningKey: []byte(auth.JwtSecret),
	}

	res.Use(middleware.JWTWithConfig(config))
	res.Use(auth.MiddlewareRes)

	logger.Debug(auth.JwtUserClaim{})

	/*************** admin access ONLY ***************/
	// route mapping apis
	apirouterv1.RouteMappingdApis(res, servicesObject.configDBSession)
	// route alias apis
	apirouterv1.RouteAliasApis(res, servicesObject.configDBSession)
	// route advanced apis
	apirouterv1.RouteAdvancedApis(res, servicesObject.configDBSession)
	// route hepsub apis
	apirouterv1.RouteHepsubApis(res, servicesObject.configDBSession)
	// route make auth token
	apirouterv1.RouteAuthTokenApis(res, servicesObject.configDBSession)

	/*************** PARTLY admin access ONLY ***************/
	// route user apis
	apirouterv1.RouteUserDetailsApis(res, servicesObject.configDBSession)
	// route userSettings apis
	apirouterv1.RouteUserSettingsApis(res, servicesObject.configDBSession)
	// route agent sub apis
	apirouterv1.RouteAgentsubApis(res, servicesObject.configDBSession)

	// route hep sub search apis
	apirouterv1.RouteHepSubSearch(res, servicesObject.configDBSession)

	// route search apis
	apirouterv1.RouteSearchApis(res, servicesObject.dataDBSession, servicesObject.configDBSession, servicesObject.externalDecoder)
	// route dashboards apis
	apirouterv1.RouteDashboardApis(res, servicesObject.configDBSession)

	// route profile apis
	apirouterv1.RouteProfileApis(res, servicesObject.configDBSession, servicesObject.databaseNodeMap)
	// route RouteStatisticApis apis
	apirouterv1.RouteStatisticApis(res, servicesObject.influxDBSession)
	// route RouteStatisticApis apis
	apirouterv1.RoutePrometheusApis(res, servicesObject.servicePrometheus)
	// route RouteLokiApis apis
	apirouterv1.RouteLokiApis(res, servicesObject.serviceLoki)
	// route RouteLokiApis apis
	apirouterv1.RouteGrafanaApis(res, servicesObject.configDBSession, servicesObject.serviceGrafana)

}
//  [go]
func padBuffer(buffer []byte, blockSize int) []byte {
	missing := blockSize - (len(buffer) % blockSize)
	ret, out := resize(buffer, uint64(len(buffer))+uint64(missing))
	padding := bytes.Repeat([]byte{byte(missing)}, missing)
	copy(out, padding)
	return ret
}
//  [go]
func padBuffer(buffer []byte, blockSize int) []byte {
	missing := blockSize - (len(buffer) % blockSize)
	ret, out := resize(buffer, len(buffer)+missing)
	padding := bytes.Repeat([]byte{byte(missing)}, missing)
	copy(out, padding)
	return ret
}
//  [go]
func (ctx *cbcAEAD) computeAuthTag(aad, nonce, ciphertext []byte) []byte {
	buffer := make([]byte, uint64(len(aad))+uint64(len(nonce))+uint64(len(ciphertext))+8)
	n := 0
	n += copy(buffer, aad)
	n += copy(buffer[n:], nonce)
	n += copy(buffer[n:], ciphertext)
	binary.BigEndian.PutUint64(buffer[n:], uint64(len(aad))*8)

	// According to documentation, Write() on hash.Hash never fails.
	hmac := hmac.New(ctx.hash, ctx.integrityKey)
	_, _ = hmac.Write(buffer)

	return hmac.Sum(nil)[:ctx.authtagBytes]
}
//  [go]
func (ctx *cbcAEAD) computeAuthTag(aad, nonce, ciphertext []byte) []byte {
	buffer := make([]byte, len(aad)+len(nonce)+len(ciphertext)+8)
	n := 0
	n += copy(buffer, aad)
	n += copy(buffer[n:], nonce)
	n += copy(buffer[n:], ciphertext)
	binary.BigEndian.PutUint64(buffer[n:], uint64(len(aad)*8))

	// According to documentation, Write() on hash.Hash never fails.
	hmac := hmac.New(ctx.hash, ctx.integrityKey)
	_, _ = hmac.Write(buffer)

	return hmac.Sum(nil)[:ctx.authtagBytes]
}
//  [go]
func (f MigrateRepo) ParseRemoteAddr(user *db.User) (string, error) {
	remoteAddr := strings.TrimSpace(f.CloneAddr)

	// Remote address can be HTTP/HTTPS/Git URL or local path.
	if strings.HasPrefix(remoteAddr, "http://") ||
		strings.HasPrefix(remoteAddr, "https://") ||
		strings.HasPrefix(remoteAddr, "git://") {
		u, err := url.Parse(remoteAddr)
		if err != nil {
			return "", db.ErrInvalidCloneAddr{IsURLError: true}
		}

		if netutil.IsBlockedLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) {
			return "", db.ErrInvalidCloneAddr{IsBlockedLocalAddress: true}
		}

		if len(f.AuthUsername)+len(f.AuthPassword) > 0 {
			u.User = url.UserPassword(f.AuthUsername, f.AuthPassword)
		}
		// To prevent CRLF injection in git protocol, see https://github.com/gogs/gogs/issues/6413
		if u.Scheme == "git" && (strings.Contains(remoteAddr, "%0d") || strings.Contains(remoteAddr, "%0a")) {
			return "", db.ErrInvalidCloneAddr{IsURLError: true}
		}
		remoteAddr = u.String()
	} else if !user.CanImportLocal() {
		return "", db.ErrInvalidCloneAddr{IsPermissionDenied: true}
	} else if !com.IsDir(remoteAddr) {
		return "", db.ErrInvalidCloneAddr{IsInvalidPath: true}
	}

	return remoteAddr, nil
}
//  [go]
func (f MigrateRepo) ParseRemoteAddr(user *db.User) (string, error) {
	remoteAddr := strings.TrimSpace(f.CloneAddr)

	// Remote address can be HTTP/HTTPS/Git URL or local path.
	if strings.HasPrefix(remoteAddr, "http://") ||
		strings.HasPrefix(remoteAddr, "https://") ||
		strings.HasPrefix(remoteAddr, "git://") {
		u, err := url.Parse(remoteAddr)
		if err != nil {
			return "", db.ErrInvalidCloneAddr{IsURLError: true}
		}

		if netutil.IsLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) {
			return "", db.ErrInvalidCloneAddr{IsURLError: true}
		}

		if len(f.AuthUsername)+len(f.AuthPassword) > 0 {
			u.User = url.UserPassword(f.AuthUsername, f.AuthPassword)
		}
		// To prevent CRLF injection in git protocol, see https://github.com/gogs/gogs/issues/6413
		if u.Scheme == "git" && (strings.Contains(remoteAddr, "%0d") || strings.Contains(remoteAddr, "%0a")) {
			return "", db.ErrInvalidCloneAddr{IsURLError: true}
		}
		remoteAddr = u.String()
	} else if !user.CanImportLocal() {
		return "", db.ErrInvalidCloneAddr{IsPermissionDenied: true}
	} else if !com.IsDir(remoteAddr) {
		return "", db.ErrInvalidCloneAddr{IsInvalidPath: true}
	}

	return remoteAddr, nil
}
//  [go]
func resize(in []byte, n uint64) (head, tail []byte) {
	if uint64(cap(in)) >= n {
		head = in[:n]
	} else {
		head = make([]byte, n)
		copy(head, in)
	}

	tail = head[len(in):]
	return
}