-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
130 lines (111 loc) · 2.73 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package main
import (
"fmt"
"io/ioutil"
"os"
"os/signal"
"syscall"
"time"
"github.com/spf13/cobra"
"github.com/spf13/viper"
iap "github.com/tonglil/iap_curl"
)
var (
// Configuration options
refresh time.Duration
filename string
credentials string
client string
credentialsEnv = "GOOGLE_APPLICATION_CREDENTIALS"
clientEnv = "IAP_CLIENT_ID"
)
func init() {
viper.AutomaticEnv()
flags := rootCmd.Flags()
flags.StringP("credentials", "c", "", fmt.Sprintf("The service account JSON credential [%s]", credentialsEnv))
viper.BindPFlag("credentials", flags.Lookup("credentials"))
viper.BindEnv("credentials", credentialsEnv)
flags.StringP("id", "i", "", fmt.Sprintf("The IAP client ID [%s]", clientEnv))
viper.BindPFlag("client", flags.Lookup("id"))
viper.BindEnv("client", clientEnv)
rootCmd.PersistentFlags().DurationVarP(&refresh, "refresh", "r", time.Duration(0), "Refresh the token on a specified interval")
rootCmd.PersistentFlags().StringVarP(&filename, "filename", "f", "", "Write the token to a file")
}
func main() {
err := rootCmd.Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
}
var rootCmd = &cobra.Command{
Use: "iap-token-generator",
Short: "Generate a Bearer token for making HTTP requests to IAP-protected apps",
SilenceErrors: true,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
i, err := iap.New(viper.GetString("credentials"), viper.GetString("client"))
if err != nil {
return err
}
token, err := i.GetToken()
if err != nil {
return err
}
if filename != "" {
err = ioutil.WriteFile(filename, []byte(token), 0644)
if err != nil {
return err
}
fmt.Printf("Token written to %s\n", filename)
} else {
fmt.Println(token)
}
if refresh > time.Duration(0) {
ticker := time.NewTicker(refresh)
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
errs := make(chan error, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
for {
select {
case <-ticker.C:
token, err := i.GetToken()
if err != nil {
errs <- err
done <- true
return
}
if filename != "" {
err = ioutil.WriteFile(filename, []byte(token), 0644)
if err != nil {
errs <- err
done <- true
return
}
fmt.Printf("Token written to %s\n", filename)
} else {
fmt.Println(token)
}
case sig := <-sigs:
fmt.Println()
fmt.Println(sig)
done <- true
return
}
}
}()
// Wait for signal to stop and quit
<-done
ticker.Stop()
select {
case err := <-errs:
return err
default:
return nil
}
}
return nil
},
}