// CreateTelegrafConfig checks to see if the authorizer on context has write access to the global telegraf config resource.
164911
func (s *TelegrafConfigService) CreateTelegrafConfig(ctx context.Context, tc *influxdb.TelegrafConfig, userID influxdb.ID) error {
	p, err := influxdb.NewPermission(influxdb.WriteAction, influxdb.TelegrafsResourceType, tc.OrganizationID)
	if err != nil {
		return err
	}

	if err := IsAllowed(ctx, *p); err != nil {
		return err
	}

	return s.s.CreateTelegrafConfig(ctx, tc, userID)
}
1353719
func createAuthorizer(name string, config *server.Config) (server.Authorizer, error) {
	switch name {
	case "alwaysallow":
		return alwaysallow.NewAuthorizer()
	case "aws":
		return aws.NewAuthorizer(config)
	}

	return nil, errors.New("unknown authorizer")
}
971513
func (f *MockInfraProvider) CreatePeerFromConfig(peerCfg *fab.NetworkPeer) (fab.Peer, error) {
	if peerCfg != nil {
		p := NewMockPeer(peerCfg.MSPID, peerCfg.URL)
		p.SetMSPID(peerCfg.MSPID)

		return p, nil
	}
	return &MockPeer{}, nil
}
910747
func (pm *Manager) CreateFromContext(ctx context.Context, tarCtx io.ReadCloser, options *types.PluginCreateOptions) (err error) {
	pm.muGC.RLock()
	defer pm.muGC.RUnlock()

	ref, err := reference.ParseNormalizedNamed(options.RepoName)
	if err != nil {
		return errors.Wrapf(err, "failed to parse reference %v", options.RepoName)
	}
	if _, ok := ref.(reference.Canonical); ok {
		return errors.Errorf("canonical references are not permitted")
	}
	name := reference.FamiliarString(reference.TagNameOnly(ref))

	if err := pm.config.Store.validateName(name); err != nil { // fast check, real check is in createPlugin()
		return err
	}

	tmpRootFSDir, err := ioutil.TempDir(pm.tmpDir(), ".rootfs")
	if err != nil {
		return errors.Wrap(err, "failed to create temp directory")
	}
	defer os.RemoveAll(tmpRootFSDir)

	var configJSON []byte
	rootFS := splitConfigRootFSFromTar(tarCtx, &configJSON)

	rootFSBlob, err := pm.blobStore.New()
	if err != nil {
		return err
	}
	defer rootFSBlob.Close()
	gzw := gzip.NewWriter(rootFSBlob)
	layerDigester := digest.Canonical.Digester()
	rootFSReader := io.TeeReader(rootFS, io.MultiWriter(gzw, layerDigester.Hash()))

	if err := chrootarchive.Untar(rootFSReader, tmpRootFSDir, nil); err != nil {
		return err
	}
	if err := rootFS.Close(); err != nil {
		return err
	}

	if configJSON == nil {
		return errors.New("config not found")
	}

	if err := gzw.Close(); err != nil {
		return errors.Wrap(err, "error closing gzip writer")
	}

	var config types.PluginConfig
	if err := json.Unmarshal(configJSON, &config); err != nil {
		return errors.Wrap(err, "failed to parse config")
	}

	if err := pm.validateConfig(config); err != nil {
		return err
	}

	pm.mu.Lock()
	defer pm.mu.Unlock()

	rootFSBlobsum, err := rootFSBlob.Commit()
	if err != nil {
		return err
	}
	defer func() {
		if err != nil {
			go pm.GC()
		}
	}()

	config.Rootfs = &types.PluginConfigRootfs{
		Type:    "layers",
		DiffIds: []string{layerDigester.Digest().String()},
	}

	config.DockerVersion = dockerversion.Version

	configBlob, err := pm.blobStore.New()
	if err != nil {
		return err
	}
	defer configBlob.Close()
	if err := json.NewEncoder(configBlob).Encode(config); err != nil {
		return errors.Wrap(err, "error encoding json config")
	}
	configBlobsum, err := configBlob.Commit()
	if err != nil {
		return err
	}

	p, err := pm.createPlugin(name, configBlobsum, []digest.Digest{rootFSBlobsum}, tmpRootFSDir, nil)
	if err != nil {
		return err
	}
	p.PluginObj.PluginReference = name

	pm.publisher.Publish(EventCreate{Plugin: p.PluginObj})
	pm.config.LogPluginEvent(p.PluginObj.ID, name, "create")

	return nil
}
897475
func (env *maasEnviron) Create(ctx context.ProviderCallContext, p environs.CreateParams) error {
	if err := verifyCredentials(env, ctx); err != nil {
		return err
	}
	return nil
}
571333
func (s *notificationServiceImpl) createClientWithContextSigner(ctx context.Context, options ...rest.HTTPClientOption) (*client.Client, error) {
	c, err := s.createClient(options...)
	if err != nil {
		return nil, err
	}
	sgn := signer.NewSATokenSigner(ctx)
	saTokenSigner, err := sgn.Signer()
	if err != nil {
		return nil, err
	}
	c.SetJWTSigner(saTokenSigner)
	return c, nil
}
790640
func createTLSConfig() (tlsConfig *tls.Config, err error) {
	tlsConfig = &tls.Config{}

	// use stronger TLS settings if enabled
	// TODO: perhaps this should be default setting
	if os.Getenv(envTLSHardening) == "true" {
		tlsConfig.InsecureSkipVerify = false
		tlsConfig.MinVersion = hardenedMinVersion
		tlsConfig.CipherSuites = hardenedCiphers
		tlsConfig.CurvePreferences = hardenedCurvePreferences
	}

	// load possible TLS CA chain(s) for server certificate validation
	// starting with an empty pool
	tlsConfig.RootCAs = x509.NewCertPool()

	// load system root CA trust store by default, unless configured not to
	// if we cannot, then it's fatal.
	// NOTE that we ONLY fail if SystemCertPool returns an error,
	// not if our system trust store is empty or doesn't exist!
	if os.Getenv(envDisableSystemRoots) != "true" {
		tlsConfig.RootCAs, err = x509.SystemCertPool()
		if err != nil {
			return
		}
	}

	// load custom certificates specified by configuration:
	// we expect a comma separated list of certificate file paths
	// if we fail to load a certificate, we should treat this to be fatal
	// as the user may not wish to send logs through an untrusted TLS connection
	// also note that each file specified above can contain one or more certificates
	// and we also _DO NOT_ check if they are CA certificates (in case of self-signed)
	if certsEnv := os.Getenv(envCaCerts); certsEnv != "" {
		certFilePaths := strings.Split(certsEnv, ",")
		for _, certFilePath := range certFilePaths {
			// each pem file may contain more than one certficate
			var certBytes []byte
			certBytes, err = ioutil.ReadFile(certFilePath)
			if err != nil {
				return
			}
			if !tlsConfig.RootCAs.AppendCertsFromPEM(certBytes) {
				err = fmt.Errorf("failed to load CA certificate(s): %s", certFilePath)
				return
			}
		}
	}

	// load a client certificate and key if enabled
	// we should only attempt this if BOTH cert and key are defined
	clientCertFilePath := os.Getenv(envClientCert)
	clientKeyFilePath := os.Getenv(envClientKey)
	if clientCertFilePath != "" && clientKeyFilePath != "" {
		var clientCert tls.Certificate
		clientCert, err = tls.LoadX509KeyPair(clientCertFilePath, clientKeyFilePath)
		// we should fail if unable to load the keypair since the user intended mutual authentication
		if err != nil {
			return
		}
		// according to TLS spec (RFC 5246 appendix F.1.1) the certificate message
		// must provide a valid certificate chain leading to an acceptable certificate authority.
		// We will make this optional; the client cert pem file can contain more than one certificate
		tlsConfig.Certificates = []tls.Certificate{clientCert}
	}
	return
}
904477
func Config(config *tls.Config) p.Plugin {
	return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
		// Assert http.Transport to work with the instance
		transport, ok := ctx.Client.Transport.(*http.Transport)
		if !ok {
			// If using a custom transport, just ignore it
			h.Next(ctx)
			return
		}

		// Override the http.Client transport
		transport.TLSClientConfig = config
		ctx.Client.Transport = transport

		h.Next(ctx)
	})
}
433264
func makeTeleportClientConfig(ctx *SessionContext) (*client.Config, error) {
	agent, cert, err := ctx.GetAgent()
	if err != nil {
		return nil, trace.BadParameter("failed to get user credentials: %v", err)
	}

	signers, err := agent.Signers()
	if err != nil {
		return nil, trace.BadParameter("failed to get user credentials: %v", err)
	}

	tlsConfig, err := ctx.ClientTLSConfig()
	if err != nil {
		return nil, trace.BadParameter("failed to get client TLS config: %v", err)
	}

	config := &client.Config{
		Username:         ctx.user,
		Agent:            agent,
		SkipLocalAuth:    true,
		TLS:              tlsConfig,
		AuthMethods:      []ssh.AuthMethod{ssh.PublicKeys(signers...)},
		DefaultPrincipal: cert.ValidPrincipals[0],
		HostKeyCallback:  func(string, net.Addr, ssh.PublicKey) error { return nil },
	}

	return config, nil
}
823159
func (env *environ) Create(ctx context.ProviderCallContext, args environs.CreateParams) error {
	if err := verifyCredentials(env, ctx); err != nil {
		return err
	}
	vpcID := env.ecfg().vpcID()
	if err := validateModelVPC(env.ec2, ctx, env.name, vpcID); err != nil {
		return errors.Trace(maybeConvertCredentialError(err, ctx))
	}
	// TODO(axw) 2016-08-04 #1609643
	// Create global security group(s) here.
	return nil
}
426818
func (c *oAuthClientAuthorizations) Create(oAuthClientAuthorization *oauth.OAuthClientAuthorization) (result *oauth.OAuthClientAuthorization, err error) {
	result = &oauth.OAuthClientAuthorization{}
	err = c.client.Post().
		Resource("oauthclientauthorizations").
		Body(oAuthClientAuthorization).
		Do().
		Into(result)
	return
}
524992
func Create(conf *Config) (*Serf, error) {
	conf.Init()
	if conf.ProtocolVersion < ProtocolVersionMin {
		return nil, fmt.Errorf("Protocol version '%d' too low. Must be in range: [%d, %d]",
			conf.ProtocolVersion, ProtocolVersionMin, ProtocolVersionMax)
	} else if conf.ProtocolVersion > ProtocolVersionMax {
		return nil, fmt.Errorf("Protocol version '%d' too high. Must be in range: [%d, %d]",
			conf.ProtocolVersion, ProtocolVersionMin, ProtocolVersionMax)
	}

	if conf.UserEventSizeLimit > UserEventSizeLimit {
		return nil, fmt.Errorf("user event size limit exceeds limit of %d bytes", UserEventSizeLimit)
	}

	logger := conf.Logger
	if logger == nil {
		logOutput := conf.LogOutput
		if logOutput == nil {
			logOutput = os.Stderr
		}
		logger = log.New(logOutput, "", log.LstdFlags)
	}

	serf := &Serf{
		config:        conf,
		logger:        logger,
		members:       make(map[string]*memberState),
		queryResponse: make(map[LamportTime]*QueryResponse),
		shutdownCh:    make(chan struct{}),
		state:         SerfAlive,
	}
	serf.eventJoinIgnore.Store(false)

	// Check that the meta data length is okay
	if len(serf.encodeTags(conf.Tags)) > memberlist.MetaMaxSize {
		return nil, fmt.Errorf("Encoded length of tags exceeds limit of %d bytes", memberlist.MetaMaxSize)
	}

	// Check if serf member event coalescing is enabled
	if conf.CoalescePeriod > 0 && conf.QuiescentPeriod > 0 && conf.EventCh != nil {
		c := &memberEventCoalescer{
			lastEvents:   make(map[string]EventType),
			latestEvents: make(map[string]coalesceEvent),
		}

		conf.EventCh = coalescedEventCh(conf.EventCh, serf.shutdownCh,
			conf.CoalescePeriod, conf.QuiescentPeriod, c)
	}

	// Check if user event coalescing is enabled
	if conf.UserCoalescePeriod > 0 && conf.UserQuiescentPeriod > 0 && conf.EventCh != nil {
		c := &userEventCoalescer{
			events: make(map[string]*latestUserEvents),
		}

		conf.EventCh = coalescedEventCh(conf.EventCh, serf.shutdownCh,
			conf.UserCoalescePeriod, conf.UserQuiescentPeriod, c)
	}

	// Listen for internal Serf queries. This is setup before the snapshotter, since
	// we want to capture the query-time, but the internal listener does not passthrough
	// the queries
	outCh, err := newSerfQueries(serf, serf.logger, conf.EventCh, serf.shutdownCh)
	if err != nil {
		return nil, fmt.Errorf("Failed to setup serf query handler: %v", err)
	}
	conf.EventCh = outCh

	// Set up network coordinate client.
	if !conf.DisableCoordinates {
		serf.coordClient, err = coordinate.NewClient(coordinate.DefaultConfig())
		if err != nil {
			return nil, fmt.Errorf("Failed to create coordinate client: %v", err)
		}
	}

	// Try access the snapshot
	var oldClock, oldEventClock, oldQueryClock LamportTime
	var prev []*PreviousNode
	if conf.SnapshotPath != "" {
		eventCh, snap, err := NewSnapshotter(
			conf.SnapshotPath,
			snapshotSizeLimit,
			conf.RejoinAfterLeave,
			serf.logger,
			&serf.clock,
			conf.EventCh,
			serf.shutdownCh)
		if err != nil {
			return nil, fmt.Errorf("Failed to setup snapshot: %v", err)
		}
		serf.snapshotter = snap
		conf.EventCh = eventCh
		prev = snap.AliveNodes()
		oldClock = snap.LastClock()
		oldEventClock = snap.LastEventClock()
		oldQueryClock = snap.LastQueryClock()
		serf.eventMinTime = oldEventClock + 1
		serf.queryMinTime = oldQueryClock + 1
	}

	// Set up the coordinate cache. We do this after we read the snapshot to
	// make sure we get a good initial value from there, if we got one.
	if !conf.DisableCoordinates {
		serf.coordCache = make(map[string]*coordinate.Coordinate)
		serf.coordCache[conf.NodeName] = serf.coordClient.GetCoordinate()
	}

	// Setup the various broadcast queues, which we use to send our own
	// custom broadcasts along the gossip channel.
	serf.broadcasts = &memberlist.TransmitLimitedQueue{
		NumNodes:       serf.NumNodes,
		RetransmitMult: conf.MemberlistConfig.RetransmitMult,
	}
	serf.eventBroadcasts = &memberlist.TransmitLimitedQueue{
		NumNodes:       serf.NumNodes,
		RetransmitMult: conf.MemberlistConfig.RetransmitMult,
	}
	serf.queryBroadcasts = &memberlist.TransmitLimitedQueue{
		NumNodes:       serf.NumNodes,
		RetransmitMult: conf.MemberlistConfig.RetransmitMult,
	}

	// Create the buffer for recent intents
	serf.recentIntents = make(map[string]nodeIntent)

	// Create a buffer for events and queries
	serf.eventBuffer = make([]*userEvents, conf.EventBuffer)
	serf.queryBuffer = make([]*queries, conf.QueryBuffer)

	// Ensure our lamport clock is at least 1, so that the default
	// join LTime of 0 does not cause issues
	serf.clock.Increment()
	serf.eventClock.Increment()
	serf.queryClock.Increment()

	// Restore the clock from snap if we have one
	serf.clock.Witness(oldClock)
	serf.eventClock.Witness(oldEventClock)
	serf.queryClock.Witness(oldQueryClock)

	// Modify the memberlist configuration with keys that we set
	conf.MemberlistConfig.Events = &eventDelegate{serf: serf}
	conf.MemberlistConfig.Conflict = &conflictDelegate{serf: serf}
	conf.MemberlistConfig.Delegate = &delegate{serf: serf}
	conf.MemberlistConfig.DelegateProtocolVersion = conf.ProtocolVersion
	conf.MemberlistConfig.DelegateProtocolMin = ProtocolVersionMin
	conf.MemberlistConfig.DelegateProtocolMax = ProtocolVersionMax
	conf.MemberlistConfig.Name = conf.NodeName
	conf.MemberlistConfig.ProtocolVersion = ProtocolVersionMap[conf.ProtocolVersion]
	if !conf.DisableCoordinates {
		conf.MemberlistConfig.Ping = &pingDelegate{serf: serf}
	}

	// Setup a merge delegate if necessary
	if conf.Merge != nil {
		md := &mergeDelegate{serf: serf}
		conf.MemberlistConfig.Merge = md
		conf.MemberlistConfig.Alive = md
	}

	// Create the underlying memberlist that will manage membership
	// and failure detection for the Serf instance.
	memberlist, err := memberlist.Create(conf.MemberlistConfig)
	if err != nil {
		return nil, fmt.Errorf("Failed to create memberlist: %v", err)
	}

	serf.memberlist = memberlist

	// Create a key manager for handling all encryption key changes
	serf.keyManager = &KeyManager{serf: serf}

	// Start the background tasks. See the documentation above each method
	// for more information on their role.
	go serf.handleReap()
	go serf.handleReconnect()
	go serf.checkQueueDepth("Intent", serf.broadcasts)
	go serf.checkQueueDepth("Event", serf.eventBroadcasts)
	go serf.checkQueueDepth("Query", serf.queryBroadcasts)

	// Attempt to re-join the cluster if we have known nodes
	if len(prev) != 0 {
		go serf.handleRejoin(prev)
	}

	return serf, nil
}
193728
func (c *Client) CreateTelegrafConfig(ctx context.Context, tc *platform.TelegrafConfig, userID platform.ID) error {
	op := OpPrefix + platform.OpCreateTelegrafConfig
	return c.db.Update(func(tx *bolt.Tx) error {
		tc.ID = c.IDGenerator.ID()

		pErr := c.putTelegrafConfig(ctx, tx, tc)
		if pErr != nil {
			pErr.Op = op
			return pErr
		}

		urm := &platform.UserResourceMapping{
			ResourceID:   tc.ID,
			UserID:       userID,
			UserType:     platform.Owner,
			ResourceType: platform.TelegrafsResourceType,
		}
		if err := c.createUserResourceMapping(ctx, tx, urm); err != nil {
			return err
		}

		return nil
	})
}
1242954
func (rootCA RootCA) CreateSecurityConfig(ctx context.Context, krw *KeyReadWriter, config CertificateRequestConfig) (*SecurityConfig, func() error, error) {
	ctx = log.WithModule(ctx, "tls")

	// Create a new random ID for this certificate
	cn := identity.NewID()
	org := config.Organization
	if config.Organization == "" {
		org = identity.NewID()
	}

	proposedRole := ManagerRole
	tlsKeyPair, issuerInfo, err := rootCA.IssueAndSaveNewCertificates(krw, cn, proposedRole, org)
	switch errors.Cause(err) {
	case ErrNoValidSigner:
		config.RetryInterval = GetCertRetryInterval
		// Request certificate issuance from a remote CA.
		// Last argument is nil because at this point we don't have any valid TLS creds
		tlsKeyPair, issuerInfo, err = rootCA.RequestAndSaveNewCertificates(ctx, krw, config)
		if err != nil {
			log.G(ctx).WithError(err).Error("failed to request and save new certificate")
			return nil, nil, err
		}
	case nil:
		log.G(ctx).WithFields(logrus.Fields{
			"node.id":   cn,
			"node.role": proposedRole,
		}).Debug("issued new TLS certificate")
	default:
		log.G(ctx).WithFields(logrus.Fields{
			"node.id":   cn,
			"node.role": proposedRole,
		}).WithError(err).Errorf("failed to issue and save new certificate")
		return nil, nil, err
	}

	secConfig, cleanup, err := NewSecurityConfig(&rootCA, krw, tlsKeyPair, issuerInfo)
	if err == nil {
		log.G(ctx).WithFields(logrus.Fields{
			"node.id":   secConfig.ClientTLSCreds.NodeID(),
			"node.role": secConfig.ClientTLSCreds.Role(),
		}).Debugf("new node credentials generated: %s", krw.Target())
	}
	return secConfig, cleanup, err
}
40807
func (_m *APIClient) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) {
	ret := _m.Called(ctx, config)

	var r0 types.ConfigCreateResponse
	if rf, ok := ret.Get(0).(func(context.Context, swarm.ConfigSpec) types.ConfigCreateResponse); ok {
		r0 = rf(ctx, config)
	} else {
		r0 = ret.Get(0).(types.ConfigCreateResponse)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, swarm.ConfigSpec) error); ok {
		r1 = rf(ctx, config)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
381963
func NewConfigLocal(mode InitMode,
	loggerFn func(module string) logger.Logger,
	storageRoot string, diskCacheMode DiskCacheMode,
	kbCtx Context) *ConfigLocal {
	config := &ConfigLocal{
		loggerFn:        loggerFn,
		storageRoot:     storageRoot,
		mode:            mode,
		diskCacheMode:   diskCacheMode,
		kbCtx:           kbCtx,
		tlfClearCancels: make(map[tlf.ID]context.CancelFunc),
	}
	config.SetCodec(kbfscodec.NewMsgpack())
	if diskCacheMode == DiskCacheModeLocal {
		config.loadSyncedTlfsLocked()
	}
	config.SetClock(data.WallClock{})
	config.SetReporter(NewReporterSimple(config.Clock(), 10))
	config.SetConflictRenamer(WriterDeviceDateConflictRenamer{config})
	config.ResetCaches()
	config.SetKeyOps(libkey.NewKeyOpsStandard(keyOpsConfigWrapper{config}))
	config.SetRekeyQueue(NewRekeyQueueStandard(config))
	uhLog := config.MakeLogger("HIS")
	config.SetUserHistory(kbfsedits.NewUserHistory(
		uhLog, config.MakeVLogger(uhLog)))

	config.maxNameBytes = data.MaxNameBytesDefault
	config.rwpWaitTime = rekeyWithPromptWaitTimeDefault

	config.delayedCancellationGracePeriod = delayedCancellationGracePeriodDefault
	// Don't bother creating the registry if UseNilMetrics is set, or
	// if we're in minimal mode.
	if !metrics.UseNilMetrics && config.Mode().MetricsEnabled() {
		registry := metrics.NewRegistry()
		config.SetMetricsRegistry(registry)
	}

	config.tlfValidDuration = tlfValidDurationDefault
	config.bgFlushDirOpBatchSize = bgFlushDirOpBatchSizeDefault
	config.bgFlushPeriod = bgFlushPeriodDefault
	config.metadataVersion = defaultClientMetadataVer
	config.defaultBlockType = defaultBlockTypeDefault
	config.quotaUsage =
		make(map[keybase1.UserOrTeamID]*EventuallyConsistentQuotaUsage)
	config.rekeyFSMLimiter = NewOngoingWorkLimiter(config.Mode().RekeyWorkers())
	config.diskBlockCacheFraction = defaultDiskBlockCacheFraction
	config.syncBlockCacheFraction = defaultSyncBlockCacheFraction

	config.blockCryptVersion = defaultBlockCryptVersion

	config.conflictResolutionDB = openCRDB(config)

	return config
}
1037025
func (s *Service) UpdateTelegrafConfig(ctx context.Context, id platform.ID, tc *platform.TelegrafConfig, userID platform.ID) (*platform.TelegrafConfig, error) {
	var err error
	op := OpPrefix + platform.OpUpdateTelegrafConfig
	current, pErr := s.findTelegrafConfigByID(ctx, id)
	if pErr != nil {
		pErr.Op = op
		err = pErr
		return nil, err
	}
	tc.ID = id
	// OrganizationID can not be updated
	tc.OrganizationID = current.OrganizationID
	pErr = s.putTelegrafConfig(ctx, tc)
	if pErr != nil {
		pErr.Op = op
		err = pErr
	}

	return tc, err
}