Skip to content

Commit

Permalink
Merge issue/#31/secure-git-token into master
Browse files Browse the repository at this point in the history
Closes #31
Merge of PR #32
  • Loading branch information
SteveRuble committed Apr 2, 2019
2 parents 086270e + 1c48a92 commit dcb0062
Show file tree
Hide file tree
Showing 16 changed files with 370 additions and 71 deletions.
17 changes: 12 additions & 5 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,20 @@ before:
builds:
- env:
- CGO_ENABLED=0
ldflags:
- -s -w -X github.com/naveego/bosun/cmd.Version={{.Version}} -X github.com/naveego/bosun/cmd.Timestamp={{.Timestamp}} -X github.com/naveego/bosun/cmd.Commit={{.ShortCommit}}
goos:
- windows
- linux
- darwin
goarch:
- amd64
archive:
replacements:
darwin: Darwin
linux: Linux
windows: Windows
386: i386
amd64: x86_64
darwin: darwin
linux: linux
windows: windows
amd64: amd64
checksum:
name_template: 'checksums.txt'
snapshot:
Expand Down
12 changes: 10 additions & 2 deletions bosun.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ environments: []
appRefs: {}
apps:
- name: bosun
version: 0.5.0
version: 0.5.1
images: []
scripts:
- name: publish
Expand All @@ -11,4 +11,12 @@ apps:
args: []
flags: {}
literal:
command: [mage, -v, publish]
script: |-
set -e
if [[ -n "$(git status --porcelain)" ]] ; then
echo "directory is dirty"
exit 1
fi
git tag $(bosun app version bosun)
git push --tags
goreleaser --rm-dist
47 changes: 39 additions & 8 deletions cmd/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,48 @@ func init() {
rootCmd.AddCommand(gitCmd)
}

func getGitClient() *github.Client {
func mustGetGithubClient() *github.Client {
b := mustGetBosun()
ws := b.GetWorkspace()
ctx := b.NewContext().WithDir(ws.Path)
if ws.GithubToken == nil {
fmt.Println("Github token was not found. Please provide a command that can be run to obtain a github token.")
fmt.Println(`Simple example: echo "9uha09h39oenhsir98snegcu"`)
fmt.Println(`Better example: cat $HOME/.tokens/github.token"`)
fmt.Println(`Secure example: lpass show "Tokens/GithubCLIForBosun" --notes"`)
script := pkg.RequestStringFromUser("Command")

ws.GithubToken = &bosun.CommandValue{
Command: bosun.Command{
Script:script,
},
}

_, err := ws.GithubToken.Resolve(ctx)
if err != nil {
log.Fatalf("script failed: %s\nscript:\n%s", err, script)
}

err = b.Save()
if err != nil {
log.Fatalf("save failed: %s", err)
}
}

token, err := ws.GithubToken.Resolve(ctx)
if err != nil {
log.Fatal("")
}

token, ok := os.LookupEnv("GITHUB_TOKEN")
if !ok {
log.Fatal("GITHUB_TOKEN must be set")
}

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

client := github.NewClient(tc)

Expand All @@ -63,7 +94,7 @@ var gitDeployStartCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
Short: "Notifies github that a deploy has happened.",
RunE: func(cmd *cobra.Command, args []string) error {
client := getGitClient()
client := mustGetGithubClient()

cluster := args[0]
sha := pkg.NewCommand("git rev-parse HEAD").MustOut()
Expand Down Expand Up @@ -95,7 +126,7 @@ var gitDeployUpdateCmd = &cobra.Command{
Args: cobra.ExactArgs(2),
Short: "Notifies github that a deploy has happened.",
RunE: func(cmd *cobra.Command, args []string) error {
client := getGitClient()
client := mustGetGithubClient()

org, repo := getOrgAndRepo()

Expand Down Expand Up @@ -164,7 +195,7 @@ type GitPullRequestCommand struct {
}

func (c GitPullRequestCommand) Execute() (prNumber int, err error) {
client := getGitClient()
client := mustGetGithubClient()

repoPath := c.LocalRepoPath
org, repo := git.GetOrgAndRepoFromPath(repoPath)
Expand Down Expand Up @@ -285,7 +316,7 @@ func (c GitAcceptPRCommand) Execute() error {
var err error
var out string

client := getGitClient()
client := mustGetGithubClient()
repoPath, err := git.GetRepoPath(c.RepoDirectory)
if err != nil {
return err
Expand Down Expand Up @@ -444,7 +475,7 @@ var gitTaskCmd = addCommand(gitCmd, &cobra.Command{

body := viper.GetString(ArgGitBody)
taskName := args[0]
client := getGitClient()
client := mustGetGithubClient()
issueRequest := &github.IssueRequest{
Title: github.String(taskName),
}
Expand Down
150 changes: 150 additions & 0 deletions cmd/meta.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
// Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"context"
"encoding/json"
"fmt"
"github.com/coreos/go-semver/semver"
"github.com/google/go-github/v20/github"
"github.com/pkg/errors"
"io/ioutil"
"os"
"path/filepath"
"gopkg.in/inconshreveable/go-update.v0"
"runtime"

"github.com/naveego/bosun/pkg"
"github.com/hashicorp/go-getter"
"github.com/spf13/cobra"
"strings"
"time"
)

var metaCmd = addCommand(rootCmd, &cobra.Command{
Use: "meta",
Short: "Commands for managing bosun itself.",

})

var metaVersionCmd = addCommand(metaCmd, &cobra.Command{
Use: "version",
Short: "Shows bosun version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf(`Version: %s\n
Timestamp: %s\n
Commit: %s\n
`, Version, Timestamp, Commit)
},
})

var metaUpgradeCmd = addCommand(metaCmd, &cobra.Command{
Use:"upgrade",
Short:"Upgrades bosun if a newer release is available",
SilenceUsage:true,
RunE: func(cmd *cobra.Command, args []string) error {

client := mustGetGithubClient()
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
var err error
if Version == "" {
Version, err = pkg.NewCommand("bosun", "app", "version", "bosun").RunOut()
if err != nil {
return errors.Wrap(err, "could not get version")
}
}

currentVersion, err := semver.NewVersion(Version)

releases, _, err := client.Repositories.ListReleases(ctx, "naveego", "bosun", nil)
if err != nil {
return err
}
var release *github.RepositoryRelease
var upgradeAvailable bool
for _, release = range releases {
tag := release.GetTagName()
tagVersion, err := semver.NewVersion(strings.TrimLeft(tag, "v"))
if err != nil{
continue
}
if currentVersion.LessThan(*tagVersion){
upgradeAvailable = true
break
}
}

if !upgradeAvailable {
fmt.Printf("Current version (%s) is up-to-date.\n", Version)
return nil
}

pkg.Log.Infof("Found upgrade: %s", release.GetTagName())


expectedAssetName := fmt.Sprintf("bosun_%s_%s_%s.tar.gz", release.GetTagName(), runtime.GOOS, runtime.GOARCH)
var foundAsset bool
var asset github.ReleaseAsset
for _, asset = range release.Assets {
name := asset.GetName()
if name == expectedAssetName {
foundAsset = true
break
}
}
if !foundAsset {
return errors.Errorf("could not find an asset with name %q", expectedAssetName)
}

j, _ := json.MarshalIndent(asset, "", " ")
fmt.Println(string(j))


tempDir, err := ioutil.TempDir(os.TempDir(), "bosun-upgrade")
if err != nil {
return err
}
defer os.RemoveAll(tempDir)

downloadURL := asset.GetBrowserDownloadURL()
pkg.Log.Infof("Found upgrade asset, will download from %q to %q", downloadURL, tempDir)


err = getter.Get(tempDir, "http::"+downloadURL)
if err != nil {
return errors.Errorf("error downloading from %q: %s", downloadURL, err)
}

executable, err := os.Executable()
if err != nil {
return errors.WithStack(err)
}

newVersion := filepath.Join(tempDir, filepath.Base(executable))

err, errRecover := update.New().FromFile(newVersion)
if err != nil {
return err
}
if errRecover != nil {
return errRecover
}

fmt.Println("Upgrade completed.")

return nil
},
})
11 changes: 6 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,20 @@ var cfgFile string

var step int

var version string
var timestamp string
var commit string
var Version string
var Timestamp string
var Commit string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "bosun",
Short: "Devops tool.",
SilenceErrors: true,
Version: fmt.Sprintf(`Version: %s
Version: fmt.Sprintf(`
Version: %s
Timestamp: %s
Commit: %s
`, version, timestamp, commit),
`, Version, Timestamp, Commit),
Long: `This is our tool for for devops. If you have some scripts for
building, deploying, or monitoring apps you may want to add them to this tool.`,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
Expand Down
12 changes: 5 additions & 7 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ require (
github.com/containerd/continuity v0.0.0-20181203112020-004b46473808 // indirect
github.com/coreos/bbolt v1.3.2 // indirect
github.com/coreos/go-oidc v2.0.0+incompatible // indirect
github.com/coreos/go-semver v0.2.0
github.com/coreos/go-systemd v0.0.0-20190212144455-93d5ec2c7f76 // indirect
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f // indirect
github.com/dancannon/gorethink v4.0.0+incompatible // indirect
Expand Down Expand Up @@ -61,11 +62,9 @@ require (
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef // indirect
github.com/golang/lint v0.0.0-20181217174547-8f45f776aaf1 // indirect
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c // indirect
github.com/google/go-github/v20 v20.0.0
github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf // indirect
github.com/google/uuid v1.1.0
github.com/googleapis/gax-go v2.0.2+incompatible // indirect
github.com/gorhill/cronexpr v0.0.0-20180427100037-88b0669f7d75 // indirect
github.com/gorilla/websocket v1.4.0 // indirect
github.com/gotestyourself/gotestyourself v2.2.0+incompatible // indirect
Expand All @@ -74,6 +73,7 @@ require (
github.com/grpc-ecosystem/grpc-gateway v1.8.1 // indirect
github.com/hashicorp/consul v1.4.0 // indirect
github.com/hashicorp/go-gcp-common v0.0.0-20180425173946-763e39302965 // indirect
github.com/hashicorp/go-getter v1.2.0
github.com/hashicorp/go-hclog v0.0.0-20181001195459-61d530d6c27f // indirect
github.com/hashicorp/go-immutable-radix v1.0.0 // indirect
github.com/hashicorp/go-memdb v0.0.0-20181108192425-032f93b25bec // indirect
Expand All @@ -84,7 +84,6 @@ require (
github.com/hashicorp/go-rootcerts v1.0.0 // indirect
github.com/hashicorp/go-sockaddr v0.0.0-20190103214136-e92cdb5343bb // indirect
github.com/hashicorp/go-uuid v1.0.0
github.com/hashicorp/go-version v1.0.0 // indirect
github.com/hashicorp/memberlist v0.1.0 // indirect
github.com/hashicorp/nomad v0.8.7 // indirect
github.com/hashicorp/raft v1.0.0 // indirect
Expand Down Expand Up @@ -112,7 +111,9 @@ require (
github.com/jessevdk/go-flags v1.4.0 // indirect
github.com/jonboulle/clockwork v0.1.0 // indirect
github.com/json-iterator/go v1.1.5 // indirect
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 // indirect
github.com/keybase/go-crypto v0.0.0-20181127160227-255a5089e85a // indirect
github.com/kr/binarydist v0.1.0 // indirect
github.com/lib/pq v1.0.0 // indirect
github.com/magefile/mage v1.8.0
github.com/manifoldco/promptui v0.3.2
Expand All @@ -121,7 +122,6 @@ require (
github.com/miekg/dns v1.1.1 // indirect
github.com/mitchellh/copystructure v1.0.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/go-testing-interface v1.0.0 // indirect
github.com/mitchellh/hashstructure v1.0.0 // indirect
github.com/mitchellh/pointerstructure v0.0.0-20170205204203-f2329fcfa9e2 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
Expand Down Expand Up @@ -169,14 +169,12 @@ require (
golang.org/x/crypto v0.0.0-20190103213133-ff983b9c42bc
golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890
golang.org/x/sys v0.0.0-20190102155601-82a175fd1598 // indirect
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c // indirect
google.golang.org/api v0.1.0 // indirect
google.golang.org/appengine v1.4.0 // indirect
google.golang.org/genproto v0.0.0-20181221175505-bd9b4fb69e2f // indirect
gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20180810215634-df19058c872c // indirect
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect
gopkg.in/eapache/go-resiliency.v1 v1.1.0
gopkg.in/gorethink/gorethink.v4 v4.1.0 // indirect
gopkg.in/inconshreveable/go-update.v0 v0.0.0-20150814200126-d8b0b1d421aa
gopkg.in/ldap.v2 v2.5.1 // indirect
gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce
gopkg.in/ory-am/dockertest.v2 v2.2.3 // indirect
Expand Down
Loading

0 comments on commit dcb0062

Please sign in to comment.