// RestrictDelegationPathPrefixes returns the list of valid delegationPaths that are prefixed by parentPaths
503482
func RestrictDelegationPathPrefixes(parentPaths, delegationPaths []string) []string {
	validPaths := []string{}
	if len(delegationPaths) == 0 {
		return validPaths
	}

	// Validate each individual delegation path
	for _, delgPath := range delegationPaths {
		isPrefixed := false
		for _, parentPath := range parentPaths {
			if strings.HasPrefix(delgPath, parentPath) {
				isPrefixed = true
				break
			}
		}
		// If the delegation path did not match prefix against any parent path, it is not valid
		if isPrefixed {
			validPaths = append(validPaths, delgPath)
		}
	}
	return validPaths
}
996372
func validateDelegationCfg(ctx *validation.Context, cfg *admin.DelegationPermissions) {
	names := stringset.New(0)
	for i, rule := range cfg.Rules {
		if rule.Name != "" {
			if names.Has(rule.Name) {
				ctx.Errorf("two rules with identical name %q", rule.Name)
			}
			names.Add(rule.Name)
		}
		validateRule(ctx, fmt.Sprintf("rule #%d: %q", i+1, rule.Name), rule)
	}
}
385515
func NewDelegations() *Delegations {
	return &Delegations{
		Keys:  make(map[string]PublicKey),
		Roles: make([]*Role, 0),
	}
}
1348794
func (r *repository) GetDelegationRoles() ([]data.Role, error) {
	if err := r.updateTUF(false); err != nil {
		return nil, err
	}
	return NewReadOnly(r.tufRepo).GetDelegationRoles()
}
1224070
func restrictAPIRoot(
	srv *Server,
	apiRoot rpc.Root,
	model *state.Model,
	auth authResult,
) (rpc.Root, error) {
	if !auth.controllerMachineLogin {
		// Controller agents are allowed to
		// connect even during maintenance.
		restrictedRoot, err := restrictAPIRootDuringMaintenance(
			srv, apiRoot, model, auth.tag, auth.controllerMachineLogin,
		)
		if err != nil {
			return nil, errors.Trace(err)
		}
		apiRoot = restrictedRoot
	}
	if auth.controllerOnlyLogin {
		apiRoot = restrictRoot(apiRoot, controllerFacadesOnly)
	} else {
		apiRoot = restrictRoot(apiRoot, modelFacadesOnly)
		if model.Type() == state.ModelTypeCAAS {
			apiRoot = restrictRoot(apiRoot, caasModelFacadesOnly)
		}
	}
	return apiRoot, nil
}
472258
func (r *repository) RemoveDelegationKeysAndPaths(name data.RoleName, keyIDs, paths []string) error {
	if len(paths) > 0 {
		err := r.RemoveDelegationPaths(name, paths)
		if err != nil {
			return err
		}
	}
	if len(keyIDs) > 0 {
		err := r.RemoveDelegationKeys(name, keyIDs)
		if err != nil {
			return err
		}
	}
	return nil
}
1163871
func (c DelegateUiCtlClient) RegisterGregorFirehoseFiltered(ctx context.Context, systems []string) (err error) {
	__arg := RegisterGregorFirehoseFilteredArg{Systems: systems}
	err = c.Cli.Call(ctx, "keybase.1.delegateUiCtl.registerGregorFirehoseFiltered", []interface{}{__arg}, nil)
	return
}
779245
func (s *RegistrarService) ChangeDomainDelegationToVanity(accountID string, domainName string, newDelegation *Delegation) (*vanityDelegationResponse, error) {
	path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/delegation/vanity", accountID, domainName))
	delegationResponse := &vanityDelegationResponse{}

	resp, err := s.client.put(path, newDelegation, delegationResponse)
	if err != nil {
		return nil, err
	}

	delegationResponse.HttpResponse = resp
	return delegationResponse, nil
}
717730
func PackagePaths(root string, exclude *regexp.Regexp) ([]string, error) {
	if strings.HasSuffix(root, "...") {
		root = root[0 : len(root)-3]
	} else {
		return []string{root}, nil
	}
	paths := map[string]bool{}
	err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
		if filepath.Ext(path) == ".go" {
			path = filepath.Dir(path)
			if exclude != nil && exclude.MatchString(path) {
				return nil
			}
			paths[path] = true
		}
		return nil
	})
	if err != nil {
		return []string{}, err
	}

	result := []string{}
	for path := range paths {
		result = append(result, path)
	}
	return result, nil
}
172802
func (s *DomainsService) ListDelegationSignerRecords(accountID string, domainIdentifier string, options *ListOptions) (*delegationSignerRecordsResponse, error) {
	path := versioned(delegationSignerRecordPath(accountID, domainIdentifier, 0))
	dsRecordsResponse := &delegationSignerRecordsResponse{}

	path, err := addURLQueryOptions(path, options)
	if err != nil {
		return nil, err
	}

	resp, err := s.client.get(path, dsRecordsResponse)
	if err != nil {
		return nil, err
	}

	dsRecordsResponse.HttpResponse = resp
	return dsRecordsResponse, nil
}
591402
func (rule *delegationRule) matchesDelegator(c context.Context, q *RulesQuery) (bool, error) {
	if rule.addProjectsAsDelegators && q.Delegator.Kind() == identity.Project {
		return true, nil
	}
	allowedDelegators := rule.delegators
	if rule.addRequestorAsDelegator {
		allowedDelegators = identityset.Extend(allowedDelegators, q.Requestor)
	}
	return allowedDelegators.IsMember(c, q.Delegator)
}
1120300
func (tr *Repo) PurgeDelegationKeys(role data.RoleName, removeKeys []string) error {
	if !data.IsWildDelegation(role) {
		return data.ErrInvalidRole{
			Role:   role,
			Reason: "only wildcard roles can be used in a purge",
		}
	}

	removeIDs := make(map[string]struct{})
	for _, id := range removeKeys {
		removeIDs[id] = struct{}{}
	}

	start := role.Parent()
	tufIDToCanon := make(map[string]string)

	purgeKeys := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
		var (
			deleteCandidates []string
			err              error
		)
		for id, key := range tgt.Signed.Delegations.Keys {
			var (
				canonID string
				ok      bool
			)
			if canonID, ok = tufIDToCanon[id]; !ok {
				canonID, err = utils.CanonicalKeyID(key)
				if err != nil {
					return err
				}
				tufIDToCanon[id] = canonID
			}
			if _, ok := removeIDs[canonID]; ok {
				deleteCandidates = append(deleteCandidates, id)
			}
		}
		if len(deleteCandidates) == 0 {
			// none of the interesting keys were present. We're done with this role
			return nil
		}
		// now we know there are changes, check if we'll be able to sign them in
		if err := tr.VerifyCanSign(validRole.Name); err != nil {
			logrus.Warnf(
				"role %s contains keys being purged but you do not have the necessary keys present to sign it; keys will not be purged from %s or its immediate children",
				validRole.Name,
				validRole.Name,
			)
			return nil
		}
		// we know we can sign in the changes, delete the keys
		for _, id := range deleteCandidates {
			delete(tgt.Signed.Delegations.Keys, id)
		}
		// delete candidate keys from all roles.
		for _, role := range tgt.Signed.Delegations.Roles {
			role.RemoveKeys(deleteCandidates)
			if len(role.KeyIDs) < role.Threshold {
				logrus.Warnf("role %s has fewer keys than its threshold of %d; it will not be usable until keys are added to it", role.Name, role.Threshold)
			}
		}
		tgt.Dirty = true
		return nil
	}
	return tr.WalkTargets("", start, purgeKeys)
}
635758
func (s *GetHostedZoneOutput) SetDelegationSet(v *DelegationSet) *GetHostedZoneOutput {
	s.DelegationSet = v
	return s
}
492934
func (e *Endpoint) runPreCompilationSteps(owner Owner, regenContext *regenerationContext) (preCompilationError error) {
	stats := &regenContext.Stats
	datapathRegenCtxt := regenContext.datapathRegenerationContext

	stats.waitingForLock.Start()
	err := e.LockAlive()
	stats.waitingForLock.End(err == nil)
	if err != nil {
		return err
	}

	defer e.Unlock()

	currentDir := datapathRegenCtxt.currentDir
	nextDir := datapathRegenCtxt.nextDir

	// In the first ever regeneration of the endpoint, the conntrack table
	// is cleaned from the new endpoint IPs as it is guaranteed that any
	// pre-existing connections using that IP are now invalid.
	if !e.ctCleaned {
		go func() {
			if !option.Config.DryMode {
				ipv4 := option.Config.EnableIPv4
				ipv6 := option.Config.EnableIPv6
				created := ctmap.Exists(nil, ipv4, ipv6)
				if e.ConntrackLocal() {
					created = ctmap.Exists(e, ipv4, ipv6)
				}
				if created {
					e.scrubIPsInConntrackTable()
				}
			}
			close(datapathRegenCtxt.ctCleaned)
		}()
	} else {
		close(datapathRegenCtxt.ctCleaned)
	}

	if e.realizedPolicy == nil {
		e.realizedPolicy = &policy.EndpointPolicy{}
	}

	// If dry mode is enabled, no further changes to BPF maps are performed
	if option.Config.DryMode {

		// Compute policy for this endpoint.
		if err = e.regeneratePolicy(owner); err != nil {
			return fmt.Errorf("Unable to regenerate policy: %s", err)
		}

		_ = e.updateAndOverrideEndpointOptions(nil)

		// Dry mode needs Network Policy Updates, but the proxy wait group must
		// not be initialized, as there is no proxy ACKing the changes.
		if err, _ = e.updateNetworkPolicy(owner, nil); err != nil {
			return err
		}

		if err = e.writeHeaderfile(nextDir, owner); err != nil {
			return fmt.Errorf("Unable to write header file: %s", err)
		}

		log.WithField(logfields.EndpointID, e.ID).Debug("Skipping bpf updates due to dry mode")
		return nil
	}

	if e.PolicyMap == nil {
		e.PolicyMap, _, err = policymap.OpenOrCreate(e.PolicyMapPathLocked())
		if err != nil {
			return err
		}
		// Clean up map contents
		e.getLogger().Debug("flushing old PolicyMap")
		err = e.PolicyMap.DeleteAll()
		if err != nil {
			return err
		}

		// Also reset the in-memory state of the realized state as the
		// BPF map content is guaranteed to be empty right now.
		e.realizedPolicy.PolicyMapState = make(policy.MapState)
	}

	if e.bpfConfigMap == nil {
		e.bpfConfigMap, _, err = bpfconfig.OpenMapWithName(e.BPFConfigMapPath())
		if err != nil {
			return err
		}
		// Also reset the in-memory state of the realized state as the
		// BPF map content is guaranteed to be empty right now.
		e.realizedBPFConfig = &bpfconfig.EndpointConfig{}
	}

	// Only generate & populate policy map if a security identity is set up for
	// this endpoint.
	if e.SecurityIdentity != nil {
		stats.policyCalculation.Start()
		err = e.regeneratePolicy(owner)
		stats.policyCalculation.End(err == nil)
		if err != nil {
			return fmt.Errorf("unable to regenerate policy for '%s': %s", e.PolicyMap.String(), err)
		}

		_ = e.updateAndOverrideEndpointOptions(nil)

		// realizedBPFConfig may be updated at any point after we figure out
		// whether ingress/egress policy is enabled.
		e.desiredBPFConfig = bpfconfig.GetConfig(e)

		// Synchronously try to update PolicyMap for this endpoint. If any
		// part of updating the PolicyMap fails, bail out and do not generate
		// BPF. Unfortunately, this means that the map will be in an inconsistent
		// state with the current program (if it exists) for this endpoint.
		// GH-3897 would fix this by creating a new map to do an atomic swap
		// with the old one.
		stats.mapSync.Start()
		err := e.syncPolicyMap()
		stats.mapSync.End(err == nil)
		if err != nil {
			return fmt.Errorf("unable to regenerate policy because PolicyMap synchronization failed: %s", err)
		}

		// Synchronously update the BPF ConfigMap for this endpoint.
		// This is unlikely to fail, but will have the same
		// inconsistency issues as above if there is a failure. Long
		// term the solution to this is to templatize this map in the
		// ELF file, but there's no solution to this just yet.
		if err = e.bpfConfigMap.Update(e.desiredBPFConfig); err != nil {
			e.getLogger().WithError(err).Error("unable to update BPF config map")
			return err
		}

		datapathRegenCtxt.revertStack.Push(func() error {
			return e.bpfConfigMap.Update(e.realizedBPFConfig)
		})

		// Configure the new network policy with the proxies.
		stats.proxyPolicyCalculation.Start()
		var networkPolicyRevertFunc revert.RevertFunc
		err, networkPolicyRevertFunc = e.updateNetworkPolicy(owner, datapathRegenCtxt.proxyWaitGroup)
		stats.proxyPolicyCalculation.End(err == nil)
		if err != nil {
			return err
		}

		datapathRegenCtxt.revertStack.Push(networkPolicyRevertFunc)
	}

	stats.proxyConfiguration.Start()
	var finalizeFunc revert.FinalizeFunc
	var revertFunc revert.RevertFunc
	// Walk the L4Policy to add new redirects and update the desired policy map
	// state to set the newly allocated proxy ports.
	var desiredRedirects map[string]bool
	if e.desiredPolicy != nil && e.desiredPolicy.L4Policy != nil {
		desiredRedirects, err, finalizeFunc, revertFunc = e.addNewRedirects(owner, e.desiredPolicy.L4Policy, datapathRegenCtxt.proxyWaitGroup)
		if err != nil {
			stats.proxyConfiguration.End(false)
			return err
		}
		datapathRegenCtxt.finalizeList.Append(finalizeFunc)
		datapathRegenCtxt.revertStack.Push(revertFunc)
	}

	// At this point, traffic is no longer redirected to the proxy for
	// now-obsolete redirects, since we synced the updated policy map above.
	// It's now safe to remove the redirects from the proxy's configuration.
	finalizeFunc, revertFunc = e.removeOldRedirects(owner, desiredRedirects, datapathRegenCtxt.proxyWaitGroup)
	datapathRegenCtxt.finalizeList.Append(finalizeFunc)
	datapathRegenCtxt.revertStack.Push(revertFunc)
	stats.proxyConfiguration.End(true)

	stats.prepareBuild.Start()
	defer func() {
		stats.prepareBuild.End(preCompilationError == nil)
	}()

	// Generate header file specific to this endpoint for use in compiling
	// BPF programs for this endpoint.
	if err = e.writeHeaderfile(nextDir, owner); err != nil {
		return fmt.Errorf("unable to write header file: %s", err)
	}

	// Avoid BPF program compilation and installation if the headerfile for the endpoint
	// or the node have not changed.
	datapathRegenCtxt.bpfHeaderfilesHash, err = loader.EndpointHash(e)
	if err != nil {
		e.getLogger().WithError(err).Warn("Unable to hash header file")
		datapathRegenCtxt.bpfHeaderfilesHash = ""
		datapathRegenCtxt.regenerationLevel = RegenerateWithDatapathRewrite
	} else {
		changed := (datapathRegenCtxt.bpfHeaderfilesHash != e.bpfHeaderfileHash)
		if changed {
			datapathRegenCtxt.regenerationLevel = RegenerateWithDatapathRewrite
		}
		e.getLogger().WithField(logfields.BPFHeaderfileHash, datapathRegenCtxt.bpfHeaderfilesHash).
			Debugf("BPF header file hashed (was: %q)", e.bpfHeaderfileHash)
	}

	// Cache endpoint information so that we can release the endpoint lock.
	if datapathRegenCtxt.regenerationLevel >= RegenerateWithDatapathRewrite {
		datapathRegenCtxt.epInfoCache = e.createEpInfoCache(nextDir)
	} else {
		datapathRegenCtxt.epInfoCache = e.createEpInfoCache(currentDir)
	}
	if datapathRegenCtxt.epInfoCache == nil {
		return fmt.Errorf("Unable to cache endpoint information")
	}

	return nil
}
449603
func (s *CreateDirectConnectGatewayAssociationProposalInput) SetRemoveAllowedPrefixesToDirectConnectGateway(v []*RouteFilterPrefix) *CreateDirectConnectGatewayAssociationProposalInput {
	s.RemoveAllowedPrefixesToDirectConnectGateway = v
	return s
}
112083
func (r *runner) AddDelegates(delegates ...gomit.Delegator) {
	// Append the variadic collection of gomit.RegisterHanlders to r.delegates
	r.delegates = append(r.delegates, delegates...)
}
595186
func checkPrefixAndFetchRelativePath(childpath string, parentpath string) (bool, string) {
	// Windows (local) file systems - NTFS, as well as FAT and variants
	// are case insensitive.
	cp, pp := childpath, parentpath
	if goruntime.GOOS == "windows" {
		cp = strings.ToLower(cp)
		pp = strings.ToLower(pp)
	}

	if strings.HasPrefix(cp, pp) {
		pth, err := filepath.Rel(parentpath, childpath)
		if err != nil {
			log.Fatalln(err)
		}
		return true, pth
	}

	return false, ""

}