This repository has been archived by the owner on Apr 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
238 lines (203 loc) · 5.83 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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"time"
jwt "github.com/dgrijalva/jwt-go"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
coreV1 "k8s.io/api/core/v1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
coreV1Types "k8s.io/client-go/kubernetes/typed/core/v1"
)
/*
n - namespace
s - secret
t - token
un - username
*/
var (
appID = flag.String("a", "", "Github app ID.")
installID = flag.Uint("i", 0, "Github app installation ID.")
pem = flag.String("k", "", "Path to github app private key file.")
namespace = flag.String("n", "default", "K8S secret namespace.")
secretname = flag.String("s", "", "K8S secret name.")
tokenUserName = flag.String("u", "token", "K8S token user name.")
ttl = flag.Int64("t", 600, "Key expiration time in seconds.")
secretsClient coreV1Types.SecretInterface
)
func errChk(e error) {
if e != nil {
panic(e.Error())
}
}
func getInstToken(f string, iss string, exp int64) (signedToken string, err error) {
pem, err := os.ReadFile(f)
errChk(err)
pk, err := jwt.ParseRSAPrivateKeyFromPEM(pem)
errChk(err)
claims := jwt.StandardClaims{
//iss: GitHub App's identifier
Issuer: iss,
IssuedAt: time.Now().Unix() - 60,
ExpiresAt: time.Now().Unix() + exp,
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
signedToken, err = token.SignedString(pk)
errChk(err)
return
}
// id is application installation id, t is a token
func getAccToken(id uint, t string) map[string]interface{} {
var gat map[string]interface{}
ghApi := fmt.Sprintf("https://api.github.com/app/installations/%d/access_tokens", id)
req, err := http.NewRequest("POST", ghApi, nil)
errChk(err)
req.Header.Add("Authorization", "Bearer "+t)
req.Header.Add("Accept", "application/vnd.github.v3+json")
client := &http.Client{}
resp, err := client.Do(req)
errChk(err)
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&gat)
errChk(err)
return gat
}
func initK8SClient(n string) {
// creates the in-cluster config
config, err := rest.InClusterConfig()
errChk(err)
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
errChk(err)
secretsClient = clientset.CoreV1().Secrets(n)
}
func readSecret(ctx context.Context, sc coreV1Types.SecretInterface, n string) *coreV1.Secret {
secret, err := sc.Get(ctx, n, metaV1.GetOptions{})
if err != nil {
if err.Error() == fmt.Sprintf("secrets \"%s\" not found", n) {
fmt.Printf("Secret %s not found, creating a new one.", n)
} else {
panic(err.Error())
}
}
return secret
}
func updateSecretBasicAuth(ctx context.Context, sc coreV1Types.SecretInterface, un, t, n, s string) {
secret := coreV1.Secret{
TypeMeta: metaV1.TypeMeta{
Kind: "Secret",
APIVersion: "apps/v1",
},
ObjectMeta: metaV1.ObjectMeta{
Name: s,
Namespace: n,
Annotations: map[string]string{
"tekton.dev/git-0": "https://github.com",
},
},
StringData: map[string]string{
"username": un,
"password": t,
},
Type: "kubernetes.io/basic-auth",
}
_, err := sc.Update(ctx, &secret, metaV1.UpdateOptions{FieldManager: "tokenGetter"})
errChk(err)
}
func createSecretBasicAuth(ctx context.Context, sc coreV1Types.SecretInterface, un, t, n, s string) {
secret := coreV1.Secret{
TypeMeta: metaV1.TypeMeta{
Kind: "Secret",
APIVersion: "apps/v1",
},
ObjectMeta: metaV1.ObjectMeta{
Name: s,
Namespace: n,
Annotations: map[string]string{
"tekton.dev/git-0": "https://github.com",
},
},
StringData: map[string]string{
"username": un,
"password": t,
},
Type: "kubernetes.io/basic-auth",
}
_, err := sc.Create(ctx, &secret, metaV1.CreateOptions{FieldManager: "tokenGetter"})
errChk(err)
}
func updateSecret(ctx context.Context, sc coreV1Types.SecretInterface, t, n, s string) {
secret := coreV1.Secret{
TypeMeta: metaV1.TypeMeta{
Kind: "Secret",
APIVersion: "apps/v1",
},
ObjectMeta: metaV1.ObjectMeta{
Name: s,
Namespace: n,
Annotations: map[string]string{
"tekton.dev/git-0": "https://github.com",
},
},
StringData: map[string]string{
"token": t,
},
Type: "Opaque",
}
_, err := sc.Update(ctx, &secret, metaV1.UpdateOptions{FieldManager: "tokenGetter"})
errChk(err)
}
func createSecret(ctx context.Context, sc coreV1Types.SecretInterface, t, n, s string) {
secret := coreV1.Secret{
TypeMeta: metaV1.TypeMeta{
Kind: "Secret",
APIVersion: "apps/v1",
},
ObjectMeta: metaV1.ObjectMeta{
Name: s,
Namespace: n,
Annotations: map[string]string{
"tekton.dev/git-0": "https://github.com",
},
},
StringData: map[string]string{
"token": t,
},
Type: "Opaque",
}
_, err := sc.Create(ctx, &secret, metaV1.CreateOptions{FieldManager: "tokenGetter"})
errChk(err)
}
func main() {
flag.Parse()
// Init k8s in-cluster client
initK8SClient(*namespace)
ctx, cancelFn := context.WithTimeout(context.Background(), time.Minute*5)
defer cancelFn()
//Get github install token
iTkn, err := getInstToken(*pem, *appID, *ttl)
errChk(err)
//Get github access token
switch aTkn := getAccToken(*installID, iTkn)["token"].(type) {
case string:
if readSecret(ctx, secretsClient, *secretname+"-opaque").Data != nil {
updateSecret(ctx, secretsClient, aTkn, *namespace, *secretname+"-opaque")
fmt.Printf("Token was updated at %v\n", time.Now())
} else {
createSecret(ctx, secretsClient, aTkn, *namespace, *secretname+"-opaque")
}
if readSecret(ctx, secretsClient, *secretname).Data != nil {
updateSecretBasicAuth(ctx, secretsClient, *tokenUserName, aTkn, *namespace, *secretname)
fmt.Printf("Token for basic auth was updated at %v\n", time.Now())
} else {
createSecretBasicAuth(ctx, secretsClient, *tokenUserName, aTkn, *namespace, *secretname)
}
default:
fmt.Printf("Token expects to be a string type but received %T!\n", aTkn)
}
}