// Derived from: https://github.com/fabric8-services/fabric8-tenant/blob/master/openshift/kube_token.go
420715
func (oc *openShiftAPIClient) sendResource(path string, method string, reqBody interface{}) (map[string]interface{}, error) {
	url, err := oc.config.GetAPIURL()
	if err != nil {
		return nil, err
	}
	fullURL := strings.TrimSuffix(*url, "/") + path

	marshalled, err := json.Marshal(reqBody)
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err":          err,
			"url":          fullURL,
			"request_body": reqBody,
		}, "could not marshal %s request", method)
		return nil, errs.WithStack(err)
	}

	req, err := http.NewRequest(method, fullURL, bytes.NewBuffer(marshalled))
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err":          err,
			"url":          fullURL,
			"request_body": reqBody,
		}, "could not create %s request", method)
		return nil, errs.WithStack(err)
	}

	token, err := oc.config.GetAPIToken()
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	req.Header.Set("Authorization", "Bearer "+*token)

	resp, err := oc.httpClient.Do(req)
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err":          err,
			"url":          fullURL,
			"request_body": reqBody,
		}, "could not perform %s request", method)
		return nil, errs.WithStack(err)
	}
	defer resp.Body.Close()

	buf := new(bytes.Buffer)
	_, err = buf.ReadFrom(resp.Body)
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err":          err,
			"url":          fullURL,
			"request_body": reqBody,
		}, "could not read response from %s request", method)
		return nil, errs.WithStack(err)
	}
	respBody := buf.Bytes()

	status := resp.StatusCode
	if status < http.StatusOK || status > http.StatusPartialContent {
		log.Error(nil, map[string]interface{}{
			"url":           fullURL,
			"request_body":  reqBody,
			"response_body": buf,
			"http_status":   status,
		}, "failed to %s request due to HTTP error", method)

		// If response contains a Kubernetes Status object, create a StatusError
		err = parseErrorFromStatus(respBody)
		if err != nil {
			return nil, convertError(errs.WithStack(err), "failed to %s url %s due to status code %d", method, fullURL, status)
		}
		return nil, errs.Errorf("failed to %s url %s: status code %d", method, fullURL, status)
	}

	var respJSON map[string]interface{}
	err = json.Unmarshal(respBody, &respJSON)
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err":           err,
			"url":           fullURL,
			"response_body": buf,
			"http_status":   status,
		}, "error unmarshalling JSON response")
		return nil, errs.WithStack(err)
	}
	return respJSON, nil
}
197823
func OAuth2PKCEFactory(config *Config, storage interface{}, strategy interface{}) interface{} {
	return &pkce.Handler{
		AuthorizeCodeStrategy:      strategy.(oauth2.AuthorizeCodeStrategy),
		Storage:                    storage.(pkce.PKCERequestStorage),
		Force:                      config.EnforcePKCE,
		EnablePlainChallengeMethod: config.EnablePKCEPlainChallengeMethod,
	}
}
1370176
func (c *Client) CreatePublicToken(accessToken string) (resp CreatePublicTokenResponse, err error) {
	if accessToken == "" {
		return resp, errors.New("/item/public_token/create - access token must be specified")
	}

	jsonBody, err := json.Marshal(createPublicTokenRequest{
		ClientID:    c.clientID,
		Secret:      c.secret,
		AccessToken: accessToken,
	})

	if err != nil {
		return resp, err
	}

	err = c.Call("/item/public_token/create", jsonBody, &resp)
	return resp, err
}
1169604
func (b *BearerJWT) Token(username string) (string, error) {
	if b.Now == nil {
		b.Now = time.Now
	}
	return JWT(username, b.SharedSecret, b.Now)
}
1116267
func (p Standard) Token(req []byte) (token []byte, err error) {
	h := hmac.New(sha256.New, p.key)
	h.Write(req)
	h.Write(p.ad)
	return h.Sum(nil), nil
}
982557
func (t *tokenGetter) Token() (string, error) {
	var options gophercloud.AuthOptions
	var err error
	if t.authOpt == nil {
		// reads the config from the environment
		klog.V(4).Info("reading openstack config from the environment variables")
		options, err = openstack.AuthOptionsFromEnv()
		if err != nil {
			return "", fmt.Errorf("failed to read openstack env vars: %s", err)
		}
	} else {
		options = *t.authOpt
	}
	client, err := openstack.AuthenticatedClient(options)
	if err != nil {
		return "", fmt.Errorf("authentication failed: %s", err)
	}
	return client.TokenID, nil
}
503256
func createShortLivedBootstrapToken(client clientset.Interface) (string, error) {
	tokenStr, err := bootstraputil.GenerateBootstrapToken()
	if err != nil {
		return "", errors.Wrap(err, "error generating token to upload certs")
	}
	token, err := kubeadmapi.NewBootstrapTokenString(tokenStr)
	if err != nil {
		return "", errors.Wrap(err, "error creating upload certs token")
	}
	tokens := []kubeadmapi.BootstrapToken{{
		Token:       token,
		Description: "Proxy for managing TTL for the kubeadm-certs secret",
		TTL: &metav1.Duration{
			Duration: kubeadmconstants.DefaultCertTokenDuration,
		},
	}}

	if err := nodebootstraptokenphase.CreateNewTokens(client, tokens); err != nil {
		return "", errors.Wrap(err, "error creating token")
	}
	return tokens[0].Token.ID, nil
}
1359567
func (b OpenshiftControllerClientBuilder) OpenshiftConfigClient(name string) (configclient.Interface, error) {
	clientConfig, err := b.Config(name)
	if err != nil {
		return nil, err
	}
	return configclient.NewForConfig(nonProtobufConfig(clientConfig))
}
1147805
func (b OpenshiftControllerClientBuilder) OpenshiftBuildClientOrDie(name string) buildclient.Interface {
	client, err := b.OpenshiftBuildClient(name)
	if err != nil {
		klog.Fatal(err)
	}
	return client
}
454015
func Token(token string) Option {
	return func(o *Options) error {
		if o.TokenHandler != nil {
			return ErrTokenAlreadySet
		}
		o.Token = token
		return nil
	}
}
744173
func (c *Config) Token(ctx context.Context) (*oauth2.Token, error) {
	return retrieveToken(ctx, c, url.Values{
		"grant_type": {"client_credentials"},
		"scope":      internal.CondVal(strings.Join(c.Scopes, " ")),
	})
}
716880
func Token() ([]byte, error) {
	data, err := ioutil.ReadFile(TokenFile)
	if err != nil {
		return data, err
	}
	data = bytes.TrimSpace(data)
	return data, nil
}
776913
func NewPunktSentenceTokenizer() *PunktSentenceTokenizer {
	var pt PunktSentenceTokenizer
	var err error

	pt.tokenizer, err = newSentenceTokenizer(nil)
	util.CheckError(err)

	return &pt
}
257875
func (i *InitToken) writeTokenRole() error {
	_, err := i.kubernetes.vaultClient.Logical().Write(i.Path(), i.writeData())
	if err != nil {
		return fmt.Errorf("error writing token role %s: %v", i.Path(), err)
	}

	return nil
}
1156657
func (t *ProtokubeBuilder) ProtokubeFlags(k8sVersion semver.Version) (*ProtokubeFlags, error) {
	imageVersion := t.Cluster.Spec.EtcdClusters[0].Version
	// overrides imageVersion if set
	etcdContainerImage := t.Cluster.Spec.EtcdClusters[0].Image

	var leaderElectionTimeout string
	var heartbeatInterval string

	if v := t.Cluster.Spec.EtcdClusters[0].LeaderElectionTimeout; v != nil {
		leaderElectionTimeout = convEtcdSettingsToMs(v)
	}

	if v := t.Cluster.Spec.EtcdClusters[0].HeartbeatInterval; v != nil {
		heartbeatInterval = convEtcdSettingsToMs(v)
	}

	f := &ProtokubeFlags{
		Channels:                  t.NodeupConfig.Channels,
		Containerized:             fi.Bool(true),
		EtcdLeaderElectionTimeout: s(leaderElectionTimeout),
		EtcdHearbeatInterval:      s(heartbeatInterval),
		LogLevel:                  fi.Int32(4),
		Master:                    b(t.IsMaster),
	}

	f.ManageEtcd = false
	if len(t.NodeupConfig.EtcdManifests) == 0 {
		glog.V(4).Infof("no EtcdManifests; protokube will manage etcd")
		f.ManageEtcd = true
	}

	if f.ManageEtcd {
		for _, e := range t.Cluster.Spec.EtcdClusters {
			// Because we can only specify a single EtcdBackupStore at the moment, we only backup main, not events
			if e.Name != "main" {
				continue
			}

			if e.Backups != nil {
				if f.EtcdBackupImage == "" {
					f.EtcdBackupImage = e.Backups.Image
				}

				if f.EtcdBackupStore == "" {
					f.EtcdBackupStore = e.Backups.BackupStore
				}
			}
		}

		// TODO this is duplicate code with etcd model
		image := fmt.Sprintf("k8s.gcr.io/etcd:%s", imageVersion)
		// override image if set as API value
		if etcdContainerImage != "" {
			image = etcdContainerImage
		}
		assets := assets.NewAssetBuilder(t.Cluster, "")
		remapped, err := assets.RemapImage(image)
		if err != nil {
			return nil, fmt.Errorf("unable to remap container %q: %v", image, err)
		}

		image = remapped
		f.EtcdImage = s(image)

		// check if we are using tls and add the options to protokube
		if t.UseEtcdTLS() {
			f.PeerTLSCaFile = s(filepath.Join(t.PathSrvKubernetes(), "ca.crt"))
			f.PeerTLSCertFile = s(filepath.Join(t.PathSrvKubernetes(), "etcd-peer.pem"))
			f.PeerTLSKeyFile = s(filepath.Join(t.PathSrvKubernetes(), "etcd-peer-key.pem"))
			f.TLSCAFile = s(filepath.Join(t.PathSrvKubernetes(), "ca.crt"))
			f.TLSCertFile = s(filepath.Join(t.PathSrvKubernetes(), "etcd.pem"))
			f.TLSKeyFile = s(filepath.Join(t.PathSrvKubernetes(), "etcd-key.pem"))
		}
		if t.UseEtcdTLSAuth() {
			enableAuth := true
			f.TLSAuth = b(enableAuth)
		}
	}

	// initialize rbac on Kubernetes >= 1.6 and master
	if k8sVersion.Major == 1 && k8sVersion.Minor >= 6 {
		f.InitializeRBAC = fi.Bool(true)
	}

	zone := t.Cluster.Spec.DNSZone
	if zone != "" {
		if strings.Contains(zone, ".") {
			// match by name
			f.Zone = append(f.Zone, zone)
		} else {
			// match by id
			f.Zone = append(f.Zone, "*/"+zone)
		}
	} else {
		glog.Warningf("DNSZone not specified; protokube won't be able to update DNS")
		// @TODO: Should we permit wildcard updates if zone is not specified?
		//argv = append(argv, "--zone=*/*")
	}

	if dns.IsGossipHostname(t.Cluster.Spec.MasterInternalName) {
		glog.Warningf("MasterInternalName %q implies gossip DNS", t.Cluster.Spec.MasterInternalName)
		f.DNSProvider = fi.String("gossip")

		// @TODO: This is hacky, but we want it so that we can have a different internal & external name
		internalSuffix := t.Cluster.Spec.MasterInternalName
		internalSuffix = strings.TrimPrefix(internalSuffix, "api.")
		f.DNSInternalSuffix = fi.String(internalSuffix)
	}

	if t.Cluster.Spec.CloudProvider != "" {
		f.Cloud = fi.String(t.Cluster.Spec.CloudProvider)

		if f.DNSProvider == nil {
			switch kops.CloudProviderID(t.Cluster.Spec.CloudProvider) {
			case kops.CloudProviderAWS:
				f.DNSProvider = fi.String("aws-route53")
			case kops.CloudProviderDO:
				f.DNSProvider = fi.String("digitalocean")
				f.ClusterID = fi.String(t.Cluster.Name)
			case kops.CloudProviderGCE:
				f.DNSProvider = fi.String("google-clouddns")
			case kops.CloudProviderVSphere:
				f.DNSProvider = fi.String("coredns")
				f.ClusterID = fi.String(t.Cluster.ObjectMeta.Name)
				f.DNSServer = fi.String(*t.Cluster.Spec.CloudConfig.VSphereCoreDNSServer)
			default:
				glog.Warningf("Unknown cloudprovider %q; won't set DNS provider", t.Cluster.Spec.CloudProvider)
			}
		}
	}

	if f.DNSInternalSuffix == nil {
		f.DNSInternalSuffix = fi.String(".internal." + t.Cluster.ObjectMeta.Name)
	}

	if k8sVersion.Major == 1 && k8sVersion.Minor <= 5 {
		f.ApplyTaints = fi.Bool(true)
	}

	// Remove DNS names if we're using etcd-manager
	if !f.ManageEtcd {
		var names []string

		// Mirroring the logic used to construct DNS names in protokube/pkg/protokube/etcd_cluster.go
		suffix := fi.StringValue(f.DNSInternalSuffix)
		if !strings.HasPrefix(suffix, ".") {
			suffix = "." + suffix
		}

		for _, c := range t.Cluster.Spec.EtcdClusters {
			clusterName := "etcd-" + c.Name
			if clusterName == "etcd-main" {
				clusterName = "etcd"
			}
			for _, m := range c.Members {
				name := clusterName + "-" + m.Name + suffix
				names = append(names, name)
			}
		}

		f.RemoveDNSNames = strings.Join(names, ",")
	}

	return f, nil
}
1069372
func (chat *Chat) ServiceHookToken() string {
	data, _ := chat.getData()
	//TODO: test backward compatibility cases
	for _, hook := range data.Hooks {
		for _, service := range hook.Services {
			if service == chat.ctx.ServiceName {
				return hook.Token
			}
		}
	}
	token := "c" + rndStr.Get(10)
	chat.addHook(serviceHook{
		Token:    token,
		Services: []string{chat.ctx.ServiceName},
	})
	return token
}
1283031
func NewGitHubClient(owner, repo, token, urlStr string) (GitHub, error) {
	if len(owner) == 0 {
		return nil, errors.New("missing GitHub repository owner")
	}

	if len(repo) == 0 {
		return nil, errors.New("missing GitHub repository name")
	}

	if len(token) == 0 {
		return nil, errors.New("missing GitHub API token")
	}

	if len(urlStr) == 0 {
		return nil, errors.New("missing GitHub API URL")
	}

	baseURL, err := url.ParseRequestURI(urlStr)
	if err != nil {
		return nil, errors.Wrap(err, "failed to parse Github API URL")
	}

	ts := oauth2.StaticTokenSource(&oauth2.Token{
		AccessToken: token,
	})
	tc := oauth2.NewClient(context.TODO(), ts)

	client := github.NewClient(tc)
	client.BaseURL = baseURL

	return &GitHubClient{
		Owner:  owner,
		Repo:   repo,
		Client: client,
	}, nil
}