forked from g0rbe/truenas-acme-hetzner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
355 lines (283 loc) · 8.2 KB
/
main.go
File metadata and controls
355 lines (283 loc) · 8.2 KB
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package main
import (
"context"
"fmt"
"os"
"strings"
"github.com/hetznercloud/hcloud-go/v2/hcloud"
"golang.org/x/net/publicsuffix"
"golang.org/x/sys/unix"
)
// getDomain extracts registrable domain (e.g., "example.com" from "sub.example.com")
func getDomain(fqdn string) string {
domain, _ := publicsuffix.EffectiveTLDPlusOne(strings.TrimSuffix(fqdn, "."))
return domain
}
// getSub extracts subdomain part (e.g., "_acme-challenge.sub" from "_acme-challenge.sub.example.com")
func getSub(fqdn string) string {
domain := getDomain(fqdn)
fqdn = strings.TrimSuffix(fqdn, ".")
if fqdn == domain {
return ""
}
return strings.TrimSuffix(fqdn, "."+domain)
}
func mustGetCommandArg() string {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "Command is missing!\n")
fmt.Printf("Use \"%s help\" for help!\n", os.Args[0])
os.Exit(1)
}
if os.Args[1] != "set" && os.Args[1] != "unset" && os.Args[1] != "init" && os.Args[1] != "test" && os.Args[1] != "help" {
fmt.Fprintf(os.Stderr, "Invalid command: %s!\n", os.Args[1])
fmt.Printf("Use \"%s help\" for help!\n", os.Args[0])
os.Exit(1)
}
return os.Args[1]
}
func mustGetDomainArg() string {
if len(os.Args) < 3 {
fmt.Fprintf(os.Stderr, "domain is missing!\n")
fmt.Printf("Use \"%s help\" for help!\n", os.Args[0])
os.Exit(1)
}
return getDomain(os.Args[2])
}
func mustGetValidationNameArg() string {
if len(os.Args) < 4 {
fmt.Fprintf(os.Stderr, "validation_name is missing!\n")
fmt.Printf("Use \"%s help\" for help!\n", os.Args[0])
os.Exit(1)
}
return getSub(os.Args[3])
}
func mustGetValidationContextArg() string {
if len(os.Args) < 5 {
fmt.Fprintf(os.Stderr, "validation_context is missing!\n")
fmt.Printf("Use \"%s help\" for help!\n", os.Args[0])
os.Exit(1)
}
return os.Args[4]
}
func getToken() (string, error) {
path := os.ExpandEnv("$HOME/.tahtoken")
out, err := os.ReadFile(path)
return strings.Trim(string(out), "\n"), err
}
func testTokenFile() error {
path := os.ExpandEnv("$HOME/.tahtoken")
statT := new(unix.Stat_t)
err := unix.Stat(path, statT)
if err != nil {
return err
}
if statT.Uid != uint32(os.Geteuid()) {
fmt.Printf("Different user for config file: %d/%d\n", statT.Uid, os.Geteuid())
}
if statT.Gid != uint32(os.Getegid()) {
fmt.Printf("Different group for config file: %d/%d\n", statT.Gid, os.Getegid())
}
if statT.Mode != 0o100600 {
fmt.Printf("Dangerous file mode: %o, use 0600!\n", statT.Mode)
}
return nil
}
func newClient(token string) *hcloud.Client {
return hcloud.NewClient(hcloud.WithToken(token))
}
func Set() {
domain := mustGetDomainArg()
validationName := mustGetValidationNameArg()
validationContext := mustGetValidationContextArg()
token, err := getToken()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get token: %s\n", err)
os.Exit(1)
}
ctx := context.Background()
client := newClient(token)
// Get zone by name
zoneName := strings.TrimSuffix(domain, ".")
zone, _, err := client.Zone.GetByName(ctx, zoneName)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get zone: %s\n", err)
os.Exit(1)
}
if zone == nil {
fmt.Fprintf(os.Stderr, "Zone '%s' not found in Hetzner account\n", zoneName)
os.Exit(1)
}
// Quote TXT value per Hetzner API requirements
quotedValue := fmt.Sprintf(`"%s"`, validationContext)
// Check if RRSet exists
rrset, _, err := client.Zone.GetRRSetByNameAndType(ctx, zone, validationName, hcloud.ZoneRRSetTypeTXT)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get RRSet: %s\n", err)
os.Exit(1)
}
ttl := 3600
if rrset == nil {
// Create new RRSet with record
_, _, err := client.Zone.CreateRRSet(ctx, zone, hcloud.ZoneRRSetCreateOpts{
Name: validationName,
Type: hcloud.ZoneRRSetTypeTXT,
TTL: &ttl,
Records: []hcloud.ZoneRRSetRecord{{Value: quotedValue}},
})
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create RRSet: %s\n", err)
os.Exit(1)
}
} else {
// Add to existing RRSet
_, _, err = client.Zone.AddRRSetRecords(ctx, rrset, hcloud.ZoneRRSetAddRecordsOpts{
Records: []hcloud.ZoneRRSetRecord{{Value: quotedValue}},
})
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to add record to RRSet: %s\n", err)
os.Exit(1)
}
}
}
func Unset() {
domain := mustGetDomainArg()
validationName := mustGetValidationNameArg()
validationContext := mustGetValidationContextArg()
token, err := getToken()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get token: %s\n", err)
os.Exit(1)
}
ctx := context.Background()
client := newClient(token)
zoneName := strings.TrimSuffix(domain, ".")
zone, _, err := client.Zone.GetByName(ctx, zoneName)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get zone: %s\n", err)
os.Exit(1)
}
if zone == nil {
fmt.Fprintf(os.Stderr, "Zone '%s' not found in Hetzner account\n", zoneName)
os.Exit(1)
}
rrset, _, err := client.Zone.GetRRSetByNameAndType(ctx, zone, validationName, hcloud.ZoneRRSetTypeTXT)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get RRSet: %s\n", err)
os.Exit(1)
}
if rrset == nil {
fmt.Fprintf(os.Stderr, "RRSet not found\n")
os.Exit(1)
}
// Quote value to match what was stored
quotedValue := fmt.Sprintf(`"%s"`, validationContext)
_, _, err = client.Zone.RemoveRRSetRecords(ctx, rrset, hcloud.ZoneRRSetRemoveRecordsOpts{
Records: []hcloud.ZoneRRSetRecord{{Value: quotedValue}},
})
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to remove record: %s\n", err)
os.Exit(1)
}
}
func Init() {
path := os.ExpandEnv("$HOME/.tahtoken")
fmt.Printf("Creating %s...\n", path)
_, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0600)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create %s: %s\n", path, err)
os.Exit(1)
}
fmt.Printf("Change mode of %s to 0600...\n", path)
err = os.Chmod(path, 0600)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to chmod %s: %s\n", path, err)
os.Exit(1)
}
}
func Test() {
domain := mustGetDomainArg()
err := testTokenFile()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to test token: %s\n", err)
os.Exit(1)
}
token, err := getToken()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get token: %s\n", err)
os.Exit(1)
}
ctx := context.Background()
client := newClient(token)
zoneName := getDomain(domain)
fmt.Printf("Looking up zone: %s\n", zoneName)
zone, _, err := client.Zone.GetByName(ctx, zoneName)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get zone: %s\n", err)
os.Exit(1)
}
if zone == nil {
fmt.Fprintf(os.Stderr, "Zone '%s' not found in Hetzner account\n", zoneName)
os.Exit(1)
}
recordName := "hcdcadclk"
quotedValue := `"TEST-TRUENAS-ACME-HETZNER"`
fmt.Printf("Creating TXT record: %s = %s\n", recordName, quotedValue)
// Create test RRSet
ttl := 3600
_, _, err = client.Zone.CreateRRSet(ctx, zone, hcloud.ZoneRRSetCreateOpts{
Name: recordName,
Type: hcloud.ZoneRRSetTypeTXT,
TTL: &ttl,
Records: []hcloud.ZoneRRSetRecord{{Value: quotedValue}},
})
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create test record: %s\n", err)
os.Exit(1)
}
// Cleanup helper (os.Exit doesn't run defers)
cleanup := func() {
if rs, _, err := client.Zone.GetRRSetByNameAndType(ctx, zone, recordName, hcloud.ZoneRRSetTypeTXT); err == nil && rs != nil {
_, _, _ = client.Zone.DeleteRRSet(ctx, rs)
}
}
fmt.Printf("Deleting test record...\n")
// Get the RRSet we just created to delete it
rrset, _, err := client.Zone.GetRRSetByNameAndType(ctx, zone, recordName, hcloud.ZoneRRSetTypeTXT)
if err != nil {
cleanup()
fmt.Fprintf(os.Stderr, "Failed to get test RRSet: %s\n", err)
os.Exit(1)
}
// Delete the entire RRSet
_, _, err = client.Zone.DeleteRRSet(ctx, rrset)
if err != nil {
cleanup()
fmt.Fprintf(os.Stderr, "Failed to delete test record: %s\n", err)
os.Exit(1)
}
fmt.Printf("Test passed!\n")
}
func Help() {
fmt.Printf("Usage: %s <command> <domain> <validation_name> <validation_context>\n", os.Args[0])
fmt.Printf("\n")
fmt.Printf("Command:\n")
fmt.Printf("\tset\n")
fmt.Printf("\tunset\n")
fmt.Printf("\tinit - Initialize script\n")
fmt.Printf("\ttest - Test script configuration\n")
fmt.Printf("\thelp - Print help\n")
}
func main() {
switch mustGetCommandArg() {
case "set":
Set()
case "unset":
Unset()
case "init":
Init()
case "test":
Test()
case "help":
Help()
}
}