generated from cloudoperators/repository-template
/
apikey.go
255 lines (234 loc) · 7.42 KB
/
apikey.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Greenhouse contributors
// SPDX-License-Identifier: Apache-2.0
package headscalectl
import (
"context"
"fmt"
"strings"
"time"
headscalev1 "github.com/juanfont/headscale/gen/go/headscale/v1"
"github.com/prometheus/common/model"
"github.com/spf13/cobra"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
"sigs.k8s.io/controller-runtime/pkg/log"
)
const (
defaultAPIKeyExpiry = "90d"
apiPrefixLength = 10
)
var (
apiKeyExpiry string
socketPath string
socketCall bool
prefix string
secretName string
secretNamespace string
)
func init() {
rootCmd.AddCommand(apiKeyCMD)
apiKeyCMD.AddCommand(createAPIKeyCmd())
apiKeyCMD.AddCommand(listAPIKeyCmd())
apiKeyCMD.AddCommand(expireAPIKeyCmd())
}
var apiKeyCMD = &cobra.Command{
Use: "apikey",
Short: "Commands to interact with Headscale API keys",
}
var createAPIKeyCmdUsage = "create"
type createAPIKeyCmdOptions struct {
headscaleGRPCClient headscalev1.HeadscaleServiceClient
outputFormat string
}
func createAPIKeyCmd() *cobra.Command {
c := createAPIKeyCmdOptions{}
cmd := &cobra.Command{
Use: createAPIKeyCmdUsage,
Short: "Creates a new APIKey for Headscale",
RunE: func(cmd *cobra.Command, args []string) error {
var err error
var grpcClient headscalev1.HeadscaleServiceClient
if o, err := cmd.Flags().GetString("output"); err != nil {
return fmt.Errorf("invalid value for flag --output: %w", err)
} else {
c.outputFormat = o
}
if !socketCall {
grpcClient, err = headscaleGRCPClientFunc(headscaleGRPCURL, headscaleAPIKey)
} else {
grpcClient, err = headscaleGRPCSocketClientFunc(socketPath)
if err != nil {
return err
}
}
if err != nil {
return err
}
c.headscaleGRPCClient = grpcClient
return c.run()
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
return validateFlags()
},
}
cmd.Flags().StringVarP(&apiKeyExpiry, "expiration", "e", defaultAPIKeyExpiry, "Expiration time for the apikey")
cmd.Flags().StringVar(&socketPath, "socket-path", "", "Path to the headscale agent socket")
cmd.Flags().BoolVar(&socketCall, "socket", false, "Call the headscale agent socket")
cmd.Flags().StringVar(&secretName, "secret-name", "", "Name of the secret to create")
cmd.Flags().StringVar(&secretNamespace, "secret-namespace", "", "Kubernetes namespace to create the secret in")
return cmd
}
func (o *createAPIKeyCmdOptions) run() error {
duration, err := model.ParseDuration(apiKeyExpiry)
if err != nil {
log.FromContext(context.Background()).Error(err, "error parsing duration")
return err
}
timeDuration := time.Duration(duration)
if timeDuration < time.Hour*24 {
log.FromContext(context.Background()).Info("duration must be greater than 1 day")
timeDuration = time.Hour * 24
}
createResp, err := o.headscaleGRPCClient.CreateApiKey(context.Background(), &headscalev1.CreateApiKeyRequest{
Expiration: timestamppb.New(time.Now().Add(timeDuration)),
})
if err != nil {
errStatus, ok := status.FromError(err)
switch {
case !ok:
return err
case strings.Contains(errStatus.Message(), "Unauthorized"):
return fmt.Errorf("headscale: unauthorized to create APIKey")
default:
return err
}
}
if o.outputFormat == "secret" {
tickerDuration := timeDuration - (time.Hour * 8)
ticker := time.NewTicker(tickerDuration)
for ; true; <-ticker.C {
createOrUpdateSecretInCluster(createResp.ApiKey, secretName, secretNamespace)
log.FromContext(context.Background()).Info("New APIKey would be generated", "at:", time.Now().Add(tickerDuration))
}
}
Output(createResp.ApiKey, createResp.ApiKey, o.outputFormat)
return nil
}
var listAPIKeyCmdUsage = "list"
type listAPIKeyCmdOptions struct {
headscaleGRPCClient headscalev1.HeadscaleServiceClient
outputFormat string
}
func listAPIKeyCmd() *cobra.Command {
c := listAPIKeyCmdOptions{}
cmd := &cobra.Command{
Use: listAPIKeyCmdUsage,
Short: "Lists all APIKey for Headscale",
RunE: func(cmd *cobra.Command, args []string) error {
var err error
var grpcClient headscalev1.HeadscaleServiceClient
if o, err := cmd.Flags().GetString("output"); err != nil {
return fmt.Errorf("invalid value for flag --output: %w", err)
} else {
c.outputFormat = o
}
if !socketCall {
grpcClient, err = headscaleGRCPClientFunc(headscaleGRPCURL, headscaleAPIKey)
} else {
grpcClient, err = headscaleGRPCSocketClientFunc(socketPath)
}
if err != nil {
return err
}
c.headscaleGRPCClient = grpcClient
return c.run()
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
return validateFlags()
},
}
cmd.Flags().StringVar(&socketPath, "socket-path", "", "Path to the headscale agent socket")
cmd.Flags().BoolVar(&socketCall, "socket", false, "Call the headscale agent socket")
return cmd
}
func (o *listAPIKeyCmdOptions) run() error {
listResp, err := o.headscaleGRPCClient.ListApiKeys(context.Background(), &headscalev1.ListApiKeysRequest{})
if err != nil {
errStatus, ok := status.FromError(err)
switch {
case !ok:
return err
case strings.Contains(errStatus.Message(), "Unauthorized"):
return fmt.Errorf("headscale: unauthorized to list APIKey")
default:
return err
}
}
if o.outputFormat != "" {
Output(listResp.ApiKeys, "", o.outputFormat)
return nil
}
log.FromContext(context.Background()).Info("APIKey", "apikey", listResp.ApiKeys)
return nil
}
var expireAPIKeyCmdUsage = "expire"
type expireAPIKeyCmdOptions struct {
headscaleGRPCClient headscalev1.HeadscaleServiceClient
outputFormat string
}
func expireAPIKeyCmd() *cobra.Command {
c := expireAPIKeyCmdOptions{}
cmd := &cobra.Command{
Use: expireAPIKeyCmdUsage,
Short: "Expire an APIKey for Headscale",
RunE: func(cmd *cobra.Command, args []string) error {
var err error
var grpcClient headscalev1.HeadscaleServiceClient
if o, err := cmd.Flags().GetString("output"); err != nil {
return fmt.Errorf("invalid value for flag --output: %w", err)
} else {
c.outputFormat = o
}
if !socketCall {
grpcClient, err = headscaleGRCPClientFunc(headscaleGRPCURL, headscaleAPIKey)
} else {
grpcClient, err = headscaleGRPCSocketClientFunc(socketPath)
}
if err != nil {
return err
}
c.headscaleGRPCClient = grpcClient
return c.run()
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
return validateFlags()
},
}
cmd.Flags().StringVar(&prefix, "prefix", "", "Prefix of the apikey to expire")
cmd.Flags().StringVar(&socketPath, "socket-path", "", "Path to the headscale agent socket")
cmd.Flags().BoolVar(&socketCall, "socket", false, "Call the headscale agent socket")
return cmd
}
func (o *expireAPIKeyCmdOptions) run() error {
if len(prefix) != apiPrefixLength {
return fmt.Errorf("prefix must be exactly %d characters long", apiPrefixLength)
}
expResp, err := o.headscaleGRPCClient.ExpireApiKey(context.Background(), &headscalev1.ExpireApiKeyRequest{
Prefix: prefix,
})
if err != nil {
errStatus, ok := status.FromError(err)
switch {
case !ok:
return err
case strings.Contains(errStatus.Message(), "Unauthorized"):
return fmt.Errorf("headscale: unauthorized to expire APIKey")
case strings.Contains(errStatus.Message(), "record not found"):
return fmt.Errorf("headscale: APIKey not found")
default:
return err
}
}
Output(expResp, "APIKey expired", o.outputFormat)
return nil
}