-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathauth_transfer.go
More file actions
605 lines (569 loc) · 16.9 KB
/
Copy pathauth_transfer.go
File metadata and controls
605 lines (569 loc) · 16.9 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
package launchdock
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
authpkg "github.com/nghiahoang/launchdock/internal/auth"
httpxpkg "github.com/nghiahoang/launchdock/internal/httpx"
)
type authExportPayload struct {
Version int `json:"version"`
ExportedAt string `json:"exported_at"`
Credentials []authpkg.ConfigCredential `json:"credentials"`
}
func exportableCredentials(ids []string) ([]authpkg.ConfigCredential, error) {
lookup := map[string]bool{}
if len(ids) > 0 {
for _, id := range ids {
lookup[id] = true
}
}
var out []authpkg.ConfigCredential
seen := map[string]bool{}
appendCred := func(cc authpkg.ConfigCredential) {
key := cc.Provider + "|" + cc.AccountID + "|" + cc.Email + "|" + cc.Label
if seen[key] {
return
}
seen[key] = true
out = append(out, cc)
}
// Managed credentials first.
managed, err := managedConfigCredentials(nil)
if err == nil {
for _, cc := range managed {
if len(lookup) > 0 && !lookup[cc.ID] {
continue
}
appendCred(cc)
delete(lookup, cc.ID)
}
}
// Export local OAuth credentials too.
for _, cred := range authpkg.LoadAllCredentials() {
if cred.AuthType != authpkg.AuthOAuth {
continue
}
if cred.RefreshToken == "" {
continue
}
if len(lookup) > 0 && cred.ID != "" && !lookup[cred.ID] {
continue
}
appendCred(authpkg.ConfigCredential{
ID: authpkg.GenerateCredentialID(),
Label: cred.Label,
Provider: cred.Provider,
Kind: cred.Kind,
AccessToken: cred.AccessToken,
ExpiresAt: authpkg.FormatExpiresAt(cred.ExpiresAt),
RefreshToken: cred.RefreshToken,
AccountID: cred.AccountID,
Email: cred.Email,
Disabled: false,
})
if cred.ID != "" {
delete(lookup, cred.ID)
}
}
if len(ids) > 0 && len(lookup) > 0 {
var missing []string
for id := range lookup {
missing = append(missing, id)
}
return nil, fmt.Errorf("unknown credential ids: %s", strings.Join(missing, ", "))
}
if len(out) == 0 {
return nil, fmt.Errorf("no credentials to export")
}
return out, nil
}
func managedConfigCredentials(ids []string) ([]authpkg.ConfigCredential, error) {
cfg := authpkg.LoadConfig()
if len(ids) == 0 {
if len(cfg.Credentials) == 0 {
return nil, fmt.Errorf("no managed credentials to export")
}
return cfg.Credentials, nil
}
lookup := map[string]bool{}
for _, id := range ids {
lookup[id] = true
}
var out []authpkg.ConfigCredential
for _, cc := range cfg.Credentials {
if lookup[cc.ID] {
out = append(out, cc)
delete(lookup, cc.ID)
}
}
if len(lookup) > 0 {
var missing []string
for id := range lookup {
missing = append(missing, id)
}
return nil, fmt.Errorf("unknown credential ids: %s", strings.Join(missing, ", "))
}
return out, nil
}
func exportManagedCredentials(ids []string) ([]byte, error) {
creds, err := exportableCredentials(ids)
if err != nil {
return nil, err
}
payload := authExportPayload{
Version: 1,
ExportedAt: nowRFC3339(),
Credentials: creds,
}
return json.MarshalIndent(payload, "", " ")
}
func importManagedCredentials(r io.Reader) (int, error) {
var payload authExportPayload
if err := json.NewDecoder(r).Decode(&payload); err != nil {
return 0, fmt.Errorf("parse import payload: %w", err)
}
if payload.Version != 1 {
return 0, fmt.Errorf("unsupported payload version: %d", payload.Version)
}
if len(payload.Credentials) == 0 {
return 0, fmt.Errorf("no credentials in import payload")
}
return mergeImportedCredentials(payload.Credentials)
}
func mergeImportedCredentials(imported []authpkg.ConfigCredential) (int, error) {
cfg := authpkg.LoadConfig()
count := 0
for _, cc := range imported {
if cc.ID == "" {
cc.ID = authpkg.GenerateCredentialID()
}
match := -1
for i, existing := range cfg.Credentials {
if strings.EqualFold(existing.Provider, cc.Provider) {
if cc.AccountID != "" && existing.AccountID != "" && cc.AccountID == existing.AccountID {
match = i
break
}
if match == -1 && cc.Email != "" && existing.Email != "" && strings.EqualFold(cc.Email, existing.Email) {
match = i
}
}
}
if match >= 0 {
cc.ID = cfg.Credentials[match].ID
cfg.Credentials[match] = cc
} else {
if i := findByID(cfg.Credentials, cc.ID); i >= 0 {
cfg.Credentials[i] = cc
} else {
cfg.Credentials = append(cfg.Credentials, cc)
}
}
count++
}
return count, authpkg.SaveConfig(cfg)
}
func findByID(creds []authpkg.ConfigCredential, id string) int {
for i, cc := range creds {
if cc.ID == id {
return i
}
}
return -1
}
func handleAuthExport() {
if isTerminal(int(os.Stdout.Fd())) {
fmt.Fprintln(os.Stderr, "Refusing to print credential export to an interactive terminal.")
fmt.Fprintln(os.Stderr, "Pipe it to a file or another command, for example:")
fmt.Fprintln(os.Stderr, " launchdock auth export > launchdock-auth.json")
fmt.Fprintln(os.Stderr, " launchdock auth push user@server.example.com")
os.Exit(1)
}
data, err := exportManagedCredentials(os.Args[3:])
if err != nil {
fmt.Fprintf(os.Stderr, "Export failed: %v\n", err)
os.Exit(1)
}
_, _ = os.Stdout.Write(data)
_, _ = os.Stdout.Write([]byte("\n"))
}
func handleAuthImport() {
n, err := importManagedCredentials(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "Import failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Imported %d managed credential(s).\n", n)
}
func handleAuthPush() {
if len(os.Args) < 4 {
fmt.Fprintln(os.Stderr, "Usage: launchdock auth push <ssh-target> [credential-id ...]")
os.Exit(1)
}
target := os.Args[3]
ids := os.Args[4:]
payload, err := exportManagedCredentials(ids)
if err != nil {
fmt.Fprintf(os.Stderr, "Push failed: %v\n", err)
os.Exit(1)
}
if err := ensureRemoteLaunchdock(target); err != nil {
fmt.Fprintf(os.Stderr, "Remote install failed: %v\n", err)
os.Exit(1)
}
cmd := exec.Command("ssh", target, "$HOME/.local/bin/launchdock auth import")
cmd.Stdin = bytes.NewReader(payload)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Push failed: %v\n", err)
os.Exit(1)
}
if err := restartRemoteLaunchdock(target); err != nil {
fmt.Fprintf(os.Stderr, "Remote restart failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Pushed credential(s) to %s\n", target)
}
func restartRemoteLaunchdock(target string) error {
script := `set -e
BIN="$HOME/.local/bin/launchdock"
STATUS="$($BIN ps 2>/dev/null || true)"
if printf '%s' "$STATUS" | grep -q 'status: running (unmanaged)'; then
PORT="${PORT:-8090}"
PID=""
if command -v ss >/dev/null 2>&1; then
PID=$(ss -ltnp 2>/dev/null | awk -v port=":${PORT}" '$4 ~ port { if (match($0, /pid=[0-9]+/)) { print substr($0, RSTART+4, RLENGTH-4); exit } }')
fi
if [ -z "$PID" ] && command -v lsof >/dev/null 2>&1; then
PID=$(lsof -tiTCP:"$PORT" -sTCP:LISTEN 2>/dev/null | head -n 1)
fi
if [ -z "$PID" ] && command -v netstat >/dev/null 2>&1; then
PID=$(netstat -ltnp 2>/dev/null | awk -v port=":${PORT}" '$4 ~ port { split($7, a, "/"); if (a[1] != "-") { print a[1]; exit } }')
fi
if [ -n "$PID" ] && ps -p "$PID" -o cmd= 2>/dev/null | grep -q '[l]aunchdock'; then
kill "$PID"
sleep 1
fi
"$BIN" start >/dev/null
else
"$BIN" restart >/dev/null 2>&1 || "$BIN" start >/dev/null
fi`
cmd := exec.Command("ssh", target, script)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func ensureRemoteLaunchdock(target string) error {
if err := installCurrentBinary(target); err == nil {
return nil
}
version := currentVersion()
if version == "" || version == "dev" {
version = latestReleaseVersion()
}
check := exec.Command("ssh", target, "$HOME/.local/bin/launchdock version 2>/dev/null || launchdock version 2>/dev/null || true")
out, _ := check.Output()
remoteVersion := strings.TrimSpace(string(out))
if remoteVersion == version && remoteVersion != "" {
return nil
}
return installRemoteLaunchdock(target, version)
}
func installCurrentBinary(target string) error {
bin, cleanup, err := buildBinaryForRemote(target)
if err != nil {
return err
}
defer cleanup()
tmp := "/tmp/launchdock-upload"
copy := exec.Command("scp", bin, target+":"+tmp)
copy.Stdout = os.Stdout
copy.Stderr = os.Stderr
if err := copy.Run(); err != nil {
return err
}
install := exec.Command("ssh", target, "mkdir -p $HOME/.local/bin && install "+tmp+" $HOME/.local/bin/launchdock && $HOME/.local/bin/launchdock version >/dev/null")
install.Stdout = os.Stdout
install.Stderr = os.Stderr
return install.Run()
}
func buildBinaryForRemote(target string) (string, func(), error) {
out, err := exec.Command("ssh", target, "uname -s && uname -m").Output()
if err != nil {
return "", func() {}, err
}
parts := strings.Fields(string(out))
if len(parts) < 2 {
return "", func() {}, fmt.Errorf("could not detect remote platform")
}
osName := strings.ToLower(parts[0])
arch := strings.ToLower(parts[1])
switch arch {
case "x86_64", "amd64":
arch = "amd64"
case "aarch64", "arm64":
arch = "arm64"
}
tmp := filepath.Join(os.TempDir(), fmt.Sprintf("launchdock-%s-%s", osName, arch))
cmd := exec.Command("go", "build", "-o", tmp, "./cmd/launchdock")
cmd.Env = append(os.Environ(), "GOOS="+osName, "GOARCH="+arch)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = mustGetwd()
if err := cmd.Run(); err != nil {
return "", func() {}, err
}
return tmp, func() { _ = os.Remove(tmp) }, nil
}
func mustGetwd() string {
wd, err := os.Getwd()
if err != nil {
return "."
}
return wd
}
func installRemoteLaunchdock(target, version string) error {
if version == "" {
return fmt.Errorf("could not resolve launchdock release version")
}
installScript := fmt.Sprintf(`set -e
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case "$ARCH" in
x86_64|amd64) ARCH=amd64 ;;
arm64|aarch64) ARCH=arm64 ;;
*) echo "unsupported arch: $ARCH" >&2; exit 1 ;;
esac
NAME="launchdock-%s-${OS}-${ARCH}"
URL="https://github.com/nghyane/launchdock/releases/download/%s/${NAME}.tar.gz"
CHECKSUM_URL="https://github.com/nghyane/launchdock/releases/download/%s/checksums-${OS}-${ARCH}.txt"
mkdir -p "$HOME/.local/bin" "$HOME/.cache/launchdock"
command -v curl >/dev/null 2>&1 || { echo "missing required command: curl" >&2; exit 1; }
command -v tar >/dev/null 2>&1 || { echo "missing required command: tar" >&2; exit 1; }
command -v install >/dev/null 2>&1 || { echo "missing required command: install" >&2; exit 1; }
ARCHIVE_PATH="$HOME/.cache/launchdock/${NAME}.tar.gz"
ASSET_NAME="${NAME}.tar.gz"
curl -fsSL "$URL" -o "$ARCHIVE_PATH"
curl -fsSL "$CHECKSUM_URL" -o "$HOME/.cache/launchdock/checksums.txt"
cd "$HOME/.cache/launchdock"
if command -v sha256sum >/dev/null 2>&1; then
sha256sum -c checksums.txt --ignore-missing
elif command -v shasum >/dev/null 2>&1; then
EXPECTED=$(awk -v asset="$ASSET_NAME" '$2 == asset {print $1}' checksums.txt)
ACTUAL=$(shasum -a 256 "$ARCHIVE_PATH" | awk '{print $1}')
[ "$EXPECTED" = "$ACTUAL" ] || { echo "checksum mismatch" >&2; exit 1; }
elif command -v openssl >/dev/null 2>&1; then
EXPECTED=$(awk -v asset="$ASSET_NAME" '$2 == asset {print $1}' checksums.txt)
ACTUAL=$(openssl dgst -sha256 "$ARCHIVE_PATH" | awk '{print $NF}')
[ "$EXPECTED" = "$ACTUAL" ] || { echo "checksum mismatch" >&2; exit 1; }
else
echo "missing checksum tool: sha256sum, shasum, or openssl" >&2
exit 1
fi
rm -rf "$HOME/.cache/launchdock/unpack"
mkdir -p "$HOME/.cache/launchdock/unpack"
tar -xzf "$ARCHIVE_PATH" -C "$HOME/.cache/launchdock/unpack"
install "$HOME/.cache/launchdock/unpack/launchdock" "$HOME/.local/bin/launchdock"
$HOME/.local/bin/launchdock version >/dev/null
`, version, version, version)
cmd := exec.Command("ssh", target, installScript)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func currentVersion() string {
if version != "" && version != "dev" {
return version
}
cmd := exec.Command("git", "describe", "--tags", "--exact-match")
out, err := cmd.Output()
if err == nil {
return string(bytes.TrimSpace(out))
}
return version
}
func latestReleaseVersion() string {
req, err := http.NewRequest(http.MethodGet, "https://api.github.com/repos/nghyane/launchdock/releases/latest", nil)
if err != nil {
return ""
}
req.Header.Set("User-Agent", "launchdock/"+currentVersion())
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := httpxpkg.APIClient.Do(req)
if err != nil {
return ""
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return ""
}
var result struct {
TagName string `json:"tag_name"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return ""
}
return result.TagName
}
func handleUpdateCommand() {
version := ""
args := os.Args[2:]
for i, arg := range args {
if arg == "--version" && i+1 < len(args) {
version = args[i+1]
}
}
current := currentVersion()
if version == "" {
version = latestReleaseVersion()
}
if version == "" {
fmt.Fprintln(os.Stderr, "Update failed: could not resolve release version")
os.Exit(1)
}
fmt.Printf("Current: %s\nLatest: %s\n", current, version)
if current == version && current != "dev" {
fmt.Println("Already up to date.")
return
}
if runtime.GOOS == "windows" {
fmt.Fprintln(os.Stderr, "Update is not supported automatically on Windows yet.")
os.Exit(1)
}
if err := installLocalLaunchdock(version); err != nil {
fmt.Fprintf(os.Stderr, "Update failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Updated launchdock to %s\n", version)
}
func handleVersionCommand() {
fmt.Println(currentVersion())
}
func installLocalLaunchdock(version string) error {
asset := releaseAssetName(version, runtime.GOOS, runtime.GOARCH)
if asset == "" {
return fmt.Errorf("unsupported platform: %s/%s", runtime.GOOS, runtime.GOARCH)
}
url := fmt.Sprintf("https://github.com/nghyane/launchdock/releases/download/%s/%s", version, asset)
checksumURL := fmt.Sprintf("https://github.com/nghyane/launchdock/releases/download/%s/%s", version, releaseChecksumAsset(runtime.GOOS, runtime.GOARCH))
tmpDir, err := os.MkdirTemp("", "launchdock-update-")
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
archivePath := filepath.Join(tmpDir, asset)
if err := downloadFile(url, archivePath); err != nil {
return err
}
checksumPath := filepath.Join(tmpDir, "checksums.txt")
if err := downloadFile(checksumURL, checksumPath); err != nil {
return err
}
if err := verifyChecksum(archivePath, checksumPath); err != nil {
return err
}
binPath, err := extractReleaseBinary(archivePath, tmpDir)
if err != nil {
return err
}
execPath, err := os.Executable()
if err != nil {
return err
}
if err := os.Rename(binPath, execPath+".new"); err != nil {
return err
}
return os.Rename(execPath+".new", execPath)
}
func releaseChecksumAsset(goos, goarch string) string {
return fmt.Sprintf("checksums-%s-%s.txt", goos, goarch)
}
func releaseAssetName(version, goos, goarch string) string {
switch goos {
case "linux", "darwin":
if goarch == "amd64" || goarch == "arm64" {
return fmt.Sprintf("launchdock-%s-%s-%s.tar.gz", version, goos, goarch)
}
case "windows":
if goarch == "amd64" {
return fmt.Sprintf("launchdock-%s-%s-%s.zip", version, goos, goarch)
}
}
return ""
}
func downloadFile(url, path string) error {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
req.Header.Set("User-Agent", "launchdock/"+currentVersion())
resp, err := httpxpkg.APIClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
return fmt.Errorf("download failed: %s: %s", resp.Status, strings.TrimSpace(string(body)))
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, resp.Body)
return err
}
func extractReleaseBinary(archivePath, dir string) (string, error) {
cmd := exec.Command("tar", "-xzf", archivePath, "-C", dir)
if err := cmd.Run(); err != nil {
return "", err
}
path := filepath.Join(dir, "launchdock")
if _, err := os.Stat(path); err == nil {
return path, nil
}
return "", fmt.Errorf("launchdock binary not found in archive")
}
func verifyChecksum(archivePath, checksumPath string) error {
archiveName := filepath.Base(archivePath)
checksums, err := os.ReadFile(checksumPath)
if err != nil {
return err
}
expected := ""
for _, line := range strings.Split(string(checksums), "\n") {
fields := strings.Fields(line)
if len(fields) >= 2 && fields[1] == archiveName {
expected = fields[0]
break
}
}
if expected == "" {
return fmt.Errorf("checksum not found for %s", archiveName)
}
data, err := os.ReadFile(archivePath)
if err != nil {
return err
}
sum := fmt.Sprintf("%x", sha256.Sum256(data))
if sum != expected {
return fmt.Errorf("checksum mismatch for %s", archiveName)
}
return nil
}
func nowRFC3339() string {
return nowFunc().UTC().Format("2006-01-02T15:04:05Z07:00")
}
var nowFunc = func() time.Time { return time.Now() }