// NewAuthorizer returns new authorizer using backends
5718
func NewAuthorizer(access services.Access, identity services.UserGetter, trust services.Trust) (Authorizer, error) {
	if access == nil {
		return nil, trace.BadParameter("missing parameter access")
	}
	if identity == nil {
		return nil, trace.BadParameter("missing parameter identity")
	}
	if trust == nil {
		return nil, trace.BadParameter("missing parameter trust")
	}
	return &authorizer{access: access, identity: identity, trust: trust}, nil
}
1057885
func newCredentialAuthorityWithEngine(log logger.Logger, api UserKeyAPIer, eng engine) *CredentialAuthority {
	ret := &CredentialAuthority{
		log:          log,
		api:          api,
		invalidateCh: make(chan keybase1.UID, 100),
		checkCh:      make(chan checkArg),
		shutdownCh:   make(chan struct{}),
		users:        make(map[keybase1.UID](*userWrapper)),
		cleanItemCh:  make(chan cleanItem),
		eng:          eng,
	}
	ret.run()
	return ret
}
450991
func (s *Service) CreateAuthorization(ctx context.Context, a *platform.Authorization) error {
	op := OpPrefix + platform.OpCreateAuthorization

	_, pErr := s.FindUserByID(ctx, a.UserID)
	if pErr != nil {
		return platform.ErrUnableToCreateToken
	}

	_, pErr = s.FindOrganizationByID(ctx, a.OrgID)
	if pErr != nil {
		return platform.ErrUnableToCreateToken
	}

	var err error
	a.Token, err = s.TokenGenerator.Token()
	if err != nil {
		return &platform.Error{
			Err: err,
			Op:  op,
		}
	}

	a.ID = s.IDGenerator.ID()
	a.Status = platform.Active

	return s.PutAuthorization(ctx, a)
}
425261
func (settings EnvironmentSettings) GetAuthorizer() (autorest.Authorizer, error) {
	//1.Client Credentials
	if c, e := settings.GetClientCredentials(); e == nil {
		return c.Authorizer()
	}

	//2. Client Certificate
	if c, e := settings.GetClientCertificate(); e == nil {
		return c.Authorizer()
	}

	//3. Username Password
	if c, e := settings.GetUsernamePassword(); e == nil {
		return c.Authorizer()
	}

	// 4. MSI
	return settings.GetMSI().Authorizer()
}
209255
func NewKeyManagerAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*KeyManagerAPI, error) {
	// Only clients can access the key manager service.
	if !authorizer.AuthClient() {
		return nil, common.ErrPerm
	}
	m, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &KeyManagerAPI{
		state:      st,
		model:      m,
		resources:  resources,
		authorizer: authorizer,
		apiUser:    authorizer.GetAuthTag().(names.UserTag),
		check:      common.NewBlockChecker(st),
	}, nil
}
1219757
func NewPolicyAuthorizer(parent Authorizer, policies []*Policy, sentinel sentinel.Evaluator) (*PolicyAuthorizer, error) {
	p := &PolicyAuthorizer{
		parent:             parent,
		agentRules:         radix.New(),
		intentionRules:     radix.New(),
		keyRules:           radix.New(),
		nodeRules:          radix.New(),
		serviceRules:       radix.New(),
		sessionRules:       radix.New(),
		eventRules:         radix.New(),
		preparedQueryRules: radix.New(),
		sentinel:           sentinel,
	}

	policy := MergePolicies(policies)

	// Load the agent policy (exact matches)
	for _, ap := range policy.Agents {
		insertPolicyIntoRadix(ap.Node, p.agentRules, ap.Policy, nil)
	}

	// Load the agent policy (prefix matches)
	for _, ap := range policy.AgentPrefixes {
		insertPolicyIntoRadix(ap.Node, p.agentRules, nil, ap.Policy)
	}

	// Load the key policy (exact matches)
	for _, kp := range policy.Keys {
		policyRule := RulePolicy{
			aclPolicy:      kp.Policy,
			sentinelPolicy: kp.Sentinel,
		}
		insertPolicyIntoRadix(kp.Prefix, p.keyRules, policyRule, nil)
	}

	// Load the key policy (prefix matches)
	for _, kp := range policy.KeyPrefixes {
		policyRule := RulePolicy{
			aclPolicy:      kp.Policy,
			sentinelPolicy: kp.Sentinel,
		}
		insertPolicyIntoRadix(kp.Prefix, p.keyRules, nil, policyRule)
	}

	// Load the node policy (exact matches)
	for _, np := range policy.Nodes {
		policyRule := RulePolicy{
			aclPolicy:      np.Policy,
			sentinelPolicy: np.Sentinel,
		}
		insertPolicyIntoRadix(np.Name, p.nodeRules, policyRule, nil)
	}

	// Load the node policy (prefix matches)
	for _, np := range policy.NodePrefixes {
		policyRule := RulePolicy{
			aclPolicy:      np.Policy,
			sentinelPolicy: np.Sentinel,
		}
		insertPolicyIntoRadix(np.Name, p.nodeRules, nil, policyRule)
	}

	// Load the service policy (exact matches)
	for _, sp := range policy.Services {
		policyRule := RulePolicy{
			aclPolicy:      sp.Policy,
			sentinelPolicy: sp.Sentinel,
		}
		insertPolicyIntoRadix(sp.Name, p.serviceRules, policyRule, nil)

		intention := sp.Intentions
		if intention == "" {
			switch sp.Policy {
			case PolicyRead, PolicyWrite:
				intention = PolicyRead
			default:
				intention = PolicyDeny
			}
		}

		policyRule = RulePolicy{
			aclPolicy:      intention,
			sentinelPolicy: sp.Sentinel,
		}
		insertPolicyIntoRadix(sp.Name, p.intentionRules, policyRule, nil)
	}

	// Load the service policy (prefix matches)
	for _, sp := range policy.ServicePrefixes {
		policyRule := RulePolicy{
			aclPolicy:      sp.Policy,
			sentinelPolicy: sp.Sentinel,
		}
		insertPolicyIntoRadix(sp.Name, p.serviceRules, nil, policyRule)

		intention := sp.Intentions
		if intention == "" {
			switch sp.Policy {
			case PolicyRead, PolicyWrite:
				intention = PolicyRead
			default:
				intention = PolicyDeny
			}
		}

		policyRule = RulePolicy{
			aclPolicy:      intention,
			sentinelPolicy: sp.Sentinel,
		}
		insertPolicyIntoRadix(sp.Name, p.intentionRules, nil, policyRule)
	}

	// Load the session policy (exact matches)
	for _, sp := range policy.Sessions {
		insertPolicyIntoRadix(sp.Node, p.sessionRules, sp.Policy, nil)
	}

	// Load the session policy (prefix matches)
	for _, sp := range policy.SessionPrefixes {
		insertPolicyIntoRadix(sp.Node, p.sessionRules, nil, sp.Policy)
	}

	// Load the event policy (exact matches)
	for _, ep := range policy.Events {
		insertPolicyIntoRadix(ep.Event, p.eventRules, ep.Policy, nil)
	}

	// Load the event policy (prefix matches)
	for _, ep := range policy.EventPrefixes {
		insertPolicyIntoRadix(ep.Event, p.eventRules, nil, ep.Policy)
	}

	// Load the prepared query policy (exact matches)
	for _, qp := range policy.PreparedQueries {
		insertPolicyIntoRadix(qp.Prefix, p.preparedQueryRules, qp.Policy, nil)
	}

	// Load the prepared query policy (prefix matches)
	for _, qp := range policy.PreparedQueryPrefixes {
		insertPolicyIntoRadix(qp.Prefix, p.preparedQueryRules, nil, qp.Policy)
	}

	// Load the acl policy
	p.aclRule = policy.ACL

	// Load the keyring policy
	p.keyringRule = policy.Keyring

	// Load the operator policy
	p.operatorRule = policy.Operator

	return p, nil
}
953765
func NewAPI(
	backend Backend,
	precheckBackend migration.PrecheckBackend,
	pool migration.Pool,
	resources facade.Resources,
	authorizer facade.Authorizer,
	presence facade.Presence,
) (*API, error) {
	if !authorizer.AuthController() {
		return nil, common.ErrPerm
	}
	return &API{
		backend:         backend,
		precheckBackend: precheckBackend,
		pool:            pool,
		authorizer:      authorizer,
		resources:       resources,
		presence:        presence,
	}, nil
}
1234875
func NewAPI(
	st *state.State,
	resources facade.Resources,
	authorizer facade.Authorizer,
) (*API, error) {
	if !authorizer.AuthClient() {
		return nil, common.ErrPerm
	}
	m, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}

	return &API{
		access:     getState(st, m),
		authorizer: authorizer,
	}, nil
}
394360
func NewAPI(backend Backend, resources facade.Resources, authorizer facade.Authorizer) (*API, error) {
	isControllerAdmin, err := authorizer.HasPermission(permission.SuperuserAccess, backend.ControllerTag())
	if err != nil && !errors.IsNotFound(err) {
		return nil, errors.Trace(err)
	}

	if !authorizer.AuthClient() || !isControllerAdmin {
		return nil, common.ErrPerm
	}

	// For now, backup operations are only permitted on the controller model.
	if !backend.IsController() {
		return nil, errors.New("backups are only supported from the controller model\nUse juju switch to select the controller model")
	}

	if backend.ModelType() == state.ModelTypeCAAS {
		return nil, errors.NotSupportedf("backups on kubernetes controllers")
	}

	// Get the backup paths.
	dataDir, err := extractResourceValue(resources, "dataDir")
	if err != nil {
		return nil, errors.Trace(err)
	}
	logsDir, err := extractResourceValue(resources, "logDir")
	if err != nil {
		return nil, errors.Trace(err)
	}

	config, err := backend.ModelConfig()
	if err != nil {
		return nil, errors.Trace(err)
	}
	backupDir := config.BackupDir()

	paths := backups.Paths{
		BackupDir: backupDir,
		DataDir:   dataDir,
		LogsDir:   logsDir,
	}

	// Build the API.
	machineID, err := extractResourceValue(resources, "machineID")
	if err != nil {
		return nil, errors.Trace(err)
	}
	b := API{
		backend:   backend,
		paths:     &paths,
		machineID: machineID,
	}
	return &b, nil
}
868263
func (c *Client) NewAuthorization(accountKey interface{}, typ, val string) (auth Authorization, authURL string, err error) {
	type Identifier struct {
		Type  string `json:"type"`
		Value string `json:"value"`
	}

	data := struct {
		Resource   string     `json:"resource"`
		Identifier Identifier `json:"identifier"`
	}{
		resourceNewAuthorization,
		Identifier{typ, val},
	}
	payload, err := c.signObject(accountKey, &data)
	if err != nil {
		return auth, "", err
	}
	resp, err := c.client.Post(c.resources.NewAuthorization, jwsContentType, strings.NewReader(payload))
	if err != nil {
		return auth, "", err
	}
	defer resp.Body.Close()
	if err = checkHTTPError(resp, http.StatusCreated); err != nil {
		return auth, "", err
	}

	if err := json.NewDecoder(resp.Body).Decode(&auth); err != nil {
		return auth, "", fmt.Errorf("decoding response body: %v", err)
	}
	return auth, resp.Header.Get("Location"), nil
}
1213238
func NewAPI(
	backend Backend,
	resources facade.Resources,
	authorizer facade.Authorizer,
) (*API, error) {
	if !(authorizer.AuthMachineAgent() || authorizer.AuthUnitAgent() || authorizer.AuthApplicationAgent()) {
		return nil, common.ErrPerm
	}
	return &API{
		backend:    backend,
		authorizer: authorizer,
		resources:  resources,
	}, nil
}
102885
func (c Client) authorizer() Authorizer {
	if c.Authorizer == nil {
		return NullAuthorizer{}
	}
	return c.Authorizer
}
546640
func NewAPIKeyAuthorizer(headers map[string]interface{}, queryParameters map[string]interface{}) *APIKeyAuthorizer {
	return &APIKeyAuthorizer{headers: headers, queryParameters: queryParameters}
}
1345449
func NewAuthorizer(graph *Graph, identifier nodeidentifier.NodeIdentifier, rules []rbacv1.PolicyRule) authorizer.Authorizer {
	return &NodeAuthorizer{
		graph:      graph,
		identifier: identifier,
		nodeRules:  rules,
		features:   utilfeature.DefaultFeatureGate,
	}
}
1163954
func newBypassAuthorizer(auth kauthorizer.Authorizer, paths ...string) kauthorizer.Authorizer {
	return bypassAuthorizer{paths: sets.NewString(paths...), authorizer: auth}
}
957411
func (c *Client) CreateAuthorization(ctx context.Context, a *platform.Authorization) error {
	op := getOp(platform.OpCreateAuthorization)
	if err := a.Valid(); err != nil {
		return &platform.Error{
			Err: err,
			Op:  op,
		}
	}

	return c.db.Update(func(tx *bolt.Tx) error {
		_, pErr := c.findUserByID(ctx, tx, a.UserID)
		if pErr != nil {
			return platform.ErrUnableToCreateToken
		}

		_, pErr = c.findOrganizationByID(ctx, tx, a.OrgID)
		if pErr != nil {
			return platform.ErrUnableToCreateToken
		}

		if unique := c.uniqueAuthorizationToken(ctx, tx, a); !unique {
			return platform.ErrUnableToCreateToken
		}

		if a.Token == "" {
			token, err := c.TokenGenerator.Token()
			if err != nil {
				return &platform.Error{
					Err: err,
					Op:  op,
				}
			}
			a.Token = token
		}

		a.ID = c.IDGenerator.ID()

		pe := c.putAuthorization(ctx, tx, a)
		if pe != nil {
			pe.Op = op
			return pe
		}

		return nil
	})
}
594166
func NewCloudAPI(backend, ctlrBackend Backend, pool ModelPoolBackend, authorizer facade.Authorizer, callCtx environscontext.ProviderCallContext) (*CloudAPI, error) {
	if !authorizer.AuthClient() {
		return nil, common.ErrPerm
	}

	authUser, _ := authorizer.GetAuthTag().(names.UserTag)
	getUserAuthFunc := func() (common.AuthFunc, error) {
		isAdmin, err := authorizer.HasPermission(permission.SuperuserAccess, backend.ControllerTag())
		if err != nil && !errors.IsNotFound(err) {
			return nil, err
		}
		return func(tag names.Tag) bool {
			userTag, ok := tag.(names.UserTag)
			if !ok {
				return false
			}
			return isAdmin || userTag == authUser
		}, nil
	}
	return &CloudAPI{
		backend:                backend,
		ctlrBackend:            ctlrBackend,
		authorizer:             authorizer,
		getCredentialsAuthFunc: getUserAuthFunc,
		apiUser:                authUser,
		callContext:            callCtx,
		pool:                   pool,
	}, nil
}