// AuthController returns whether the authenticated user is a
// machine with running the ManageEnviron job.
513157
func (r *apiHandler) AuthController() bool {
	type hasIsManager interface {
		IsManager() bool
	}
	m, ok := r.entity.(hasIsManager)
	return ok && m.IsManager()
}
950659
func (precondition *ScalePrecondition) ValidateReplicationController(controller *api.ReplicationController) error {
	if precondition.Size != -1 && controller.Spec.Replicas != precondition.Size {
		return PreconditionError{"replicas", strconv.Itoa(precondition.Size), strconv.Itoa(controller.Spec.Replicas)}
	}
	if len(precondition.ResourceVersion) != 0 && controller.ResourceVersion != precondition.ResourceVersion {
		return PreconditionError{"resource version", precondition.ResourceVersion, controller.ResourceVersion}
	}
	return nil
}
202346
func NewAuthenticationHandler() *AuthenticationHandler {
	return &AuthenticationHandler{
		Logger:       zap.NewNop(),
		Handler:      http.DefaultServeMux,
		noAuthRouter: httprouter.New(),
	}
}
1044485
func (e *environ) controllerSecurityGroups(ctx context.ProviderCallContext, controllerUUID string) ([]ec2.SecurityGroup, error) {
	filter := ec2.NewFilter()
	e.addControllerFilter(filter, controllerUUID)
	resp, err := e.ec2.SecurityGroups(nil, filter)
	if err != nil {
		return nil, errors.Annotate(maybeConvertCredentialError(err, ctx), "listing security groups")
	}
	groups := make([]ec2.SecurityGroup, len(resp.Groups))
	for i, info := range resp.Groups {
		groups[i] = ec2.SecurityGroup{Id: info.Id, Name: info.Name}
	}
	return groups, nil
}
879856
func Auth(authorizer Authorizer, next http.Handler) http.HandlerFunc {
	// Heavily inspired by:
	// https://github.com/syncthing/syncthing/blob/161326c5489d000972a6846564f0ce12779bd8f2/cmd/syncthing/gui_auth.go
	return func(w http.ResponseWriter, r *http.Request) {
		cookie, err := r.Cookie(authCookieName)
		if err == nil && cookie != nil {
			// FIXME use RWMutex
			sessionsMut.Lock()
			_, ok := sessions[cookie.Value]
			sessionsMut.Unlock()
			if ok {
				next.ServeHTTP(w, r)
				return
			}
		}
		error := func() {
			// Mitigate risk of timing attacks.
			// https://en.wikipedia.org/wiki/Timing_attack
			// FIXME use crypto/rand
			time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
			w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		}
		username, passwd, ok := r.BasicAuth()
		if !ok {
			error()
			return
		}
		if !authorizer.Verify(username, passwd) {
			error()
			return
		}
		sessionid := randomString(32)
		sessionsMut.Lock()
		sessions[sessionid] = struct{}{}
		sessionsMut.Unlock()
		http.SetCookie(w, &http.Cookie{
			Name:   authCookieName,
			Value:  sessionid,
			MaxAge: 0,
		})
		next.ServeHTTP(w, r)
	}
}
632902
func (vm *VirtualMachine) deleteController(ctx context.Context, controllerDevice types.BaseVirtualDevice, vmDevices object.VirtualDeviceList) error {
	controllerDeviceList := vmDevices.SelectByType(controllerDevice)
	if len(controllerDeviceList) < 1 {
		return ErrNoDevicesFound
	}
	device := controllerDeviceList[len(controllerDeviceList)-1]
	err := vm.RemoveDevice(ctx, true, device)
	if err != nil {
		klog.Errorf("Error occurred while removing device on VM: %q. err: %+v", vm.InventoryPath, err)
		return err
	}
	return nil
}
1338809
func ValidateIaasController(c modelcmd.CommandBase, cmdName, controllerName string, store jujuclient.ClientStore) error {
	// Ensure controller model is cached.
	controllerModel := jujuclient.JoinOwnerModelName(
		names.NewUserTag(environs.AdminUser), bootstrap.ControllerModelName)
	_, err := c.ModelUUIDs(store, controllerName, []string{controllerModel})
	if err != nil {
		return errors.Annotatef(err, "cannot get controller model uuid")
	}

	details, err := store.ModelByName(controllerName, controllerModel)
	if err != nil {
		return errors.Trace(err)
	}
	if details.ModelType == model.IAAS {
		return nil
	}
	return errors.Errorf("Juju command %q not supported on kubernetes controllers", cmdName)
}
1360130
func authHandler(handler http.Handler) http.Handler {
	auth := readBasicAuth()
	if auth.Username != "" && auth.Password != "" {
		log.Infoln("HTTP Basic authentication is enabled.")
		return &basicAuthHandler{basicAuth: *auth, nextHandler: handler}
	}

	return handler
}
766176
func (st *State) isUserSuperuser(user names.UserTag) (bool, error) {
	access, err := st.UserAccess(user, st.controllerTag)
	if err != nil {
		// TODO(jam): 2017-11-27 We weren't suppressing NotFound here so that we would know when someone asked for
		// the list of models of a user that doesn't exist.
		// However, now we will not even check if its a known user if they aren't asking for all=true.
		return false, errors.Trace(err)
	}
	isControllerSuperuser := (access.Access == permission.SuperuserAccess)
	return isControllerSuperuser, nil
}
420417
func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) runtime.Authenticator {
	return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) {
		if request, ok := params.(*http.Request); ok {
			return handler(request)
		}
		if scoped, ok := params.(*ScopedAuthRequest); ok {
			return handler(scoped.Request)
		}
		return false, nil, nil
	})
}
1330823
func NewControllerAPI(
	st *state.State,
	pool *state.StatePool,
	authorizer facade.Authorizer,
	resources facade.Resources,
	presence facade.Presence,
	hub facade.Hub,
) (*ControllerAPI, error) {
	if !authorizer.AuthClient() {
		return nil, errors.Trace(common.ErrPerm)
	}

	// Since we know this is a user tag (because AuthClient is true),
	// we just do the type assertion to the UserTag.
	apiUser, _ := authorizer.GetAuthTag().(names.UserTag)

	model, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &ControllerAPI{
		ControllerConfigAPI: common.NewStateControllerConfig(st),
		ModelStatusAPI: common.NewModelStatusAPI(
			common.NewModelManagerBackend(model, pool),
			authorizer,
			apiUser,
		),
		CloudSpecAPI: cloudspec.NewCloudSpec(
			resources,
			cloudspec.MakeCloudSpecGetter(pool),
			cloudspec.MakeCloudSpecWatcherForModel(st),
			common.AuthFuncForTag(model.ModelTag()),
		),
		state:      st,
		statePool:  pool,
		authorizer: authorizer,
		apiUser:    apiUser,
		resources:  resources,
		presence:   presence,
		hub:        hub,
	}, nil
}
700662
func (u *User) AuthCode() string {
	return u.Data().Get(common.UserKeyAuthCode).Str()
}
624422
func (st *State) AddControllerUser(spec UserAccessSpec) (permission.UserAccess, error) {
	if err := permission.ValidateControllerAccess(spec.Access); err != nil {
		return permission.UserAccess{}, errors.Annotate(err, "adding controller user")
	}
	return st.addUserAccess(spec, userAccessTarget{globalKey: controllerGlobalKey})
}
897630
func (c *Conn) Auth(password string) error {
	c.password = password
	if c.password == "" {
		return nil
	}
	rep, err := NewCommand("AUTH", password).Run(c)
	if err != nil {
		return err
	}
	if !rep.IsOk() {
		return ErrAuth
	}
	return nil
}
1029316
func (m *ModelManagerAPI) authCheck(user names.UserTag) error {
	if m.isAdmin {
		logger.Tracef("%q is a controller admin", m.apiUser.Id())
		return nil
	}

	// We can't just compare the UserTags themselves as the provider part
	// may be unset, and gets replaced with 'local'. We must compare against
	// the Canonical value of the user tag.
	if m.apiUser == user {
		return nil
	}
	return common.ErrPerm
}
1103754
func (ac *accessController) Authorized(ctx context.Context, accessRecords ...auth.Access) (context.Context, error) {
	req, err := dcontext.GetRequest(ctx)
	if err != nil {
		return nil, err
	}

	if req.Header.Get("Authorization") == "" {
		challenge := challenge{
			realm:   ac.realm,
			service: ac.service,
		}

		if len(accessRecords) > 0 {
			var scopes []string
			for _, access := range accessRecords {
				scopes = append(scopes, fmt.Sprintf("%s:%s:%s", access.Type, access.Resource.Name, access.Action))
			}
			challenge.scope = strings.Join(scopes, " ")
		}

		return nil, &challenge
	}

	ctx = auth.WithUser(ctx, auth.UserInfo{Name: "silly"})
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, auth.UserNameKey, auth.UserKey))

	return ctx, nil

}
746547
func (s *Server) AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error) {
	return ctx, nil
}