From 89df2f7e01708f5cca6a9082076b219cf52a7a0e Mon Sep 17 00:00:00 2001 From: Greg Robinson Date: Sat, 7 Nov 2026 01:09:25 -0500 Subject: [PATCH 1/9] feat(appliance): autodetect BIG-IP vs BIG-IQ and fix multi-step password zeroing --- cmd/myf5/main.go | 587 ++++++++++++++++++++----------------- pkg/bigip/client.go | 52 +++- pkg/bigip/client_test.go | 88 +++++- pkg/bigip/failover.go | 115 +++----- pkg/bigip/failover_test.go | 29 ++ pkg/bigip/geoip.go | 27 +- pkg/bigip/info.go | 8 + pkg/bigip/info_test.go | 12 + 8 files changed, 552 insertions(+), 366 deletions(-) diff --git a/cmd/myf5/main.go b/cmd/myf5/main.go index 23a7e24..87d9ae7 100644 --- a/cmd/myf5/main.go +++ b/cmd/myf5/main.go @@ -131,13 +131,11 @@ func executeSubcommand(ctx context.Context, subcommand string, args []string) { handleCases(ctx, append([]string{"wizard"}, args...)) case "ihealth": handleIHealth(ctx, args) - case "bigip": - handleBIGIP(ctx, args) - case "bigiq": - handleBIGIQ(ctx, args) - case "geoip": - handleBIGIP(ctx, append([]string{"geoip"}, args...)) - case "push": + case "bigip", "bigiq", "appliance", "device": + handleAppliance(ctx, subcommand, args) + case "ready", "info", "sysinfo", "system-info", "serial", "sn", "serialnumber", "qkview", "geoip": + handleAppliance(ctx, "auto", append([]string{subcommand}, args...)) + case "push", "upload": handlePush(ctx, args) case "pull", "fetch": handlePull(ctx, args) @@ -1626,6 +1624,8 @@ func handleCaseCreate(ctx context.Context, client *cases.Client, args []string) payload := map[string]interface{}{} dryRun := false + var fromAppliance string + var fromTargetKind string flagToField := map[string]string{ "--family": "productFamily", @@ -1646,6 +1646,21 @@ func handleCaseCreate(ctx context.Context, client *cases.Client, args []string) for i := 0; i < len(args); i++ { a := args[i] + if a == "--from-appliance" || a == "--from-device" || a == "--from-bigiq" || a == "--from-bigip" { + if i+1 >= len(args) { + fmt.Fprintf(os.Stderr, "Flag %s requires a value (host or IP)\n", a) + exitFunc(1) + } + fromAppliance = args[i+1] + fromTargetKind = "auto" + if a == "--from-bigiq" { + fromTargetKind = "BIG-IQ" + } else if a == "--from-bigip" { + fromTargetKind = "BIG-IP" + } + i++ + continue + } if a == "--wizard" || a == "-w" { if err := RunCaseWizard(ctx, os.Stdin, os.Stdout, client); err != nil { fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) @@ -1679,6 +1694,26 @@ func handleCaseCreate(ctx context.Context, client *cases.Client, args []string) payload["preferredContactMethod"] = "Email" } + if fromAppliance != "" { + spinner := progress.NewSpinner(fmt.Sprintf("Inspecting appliance %s...", fromAppliance)) + spinner.Start() + + creds := resolveApplianceCreds(fromAppliance, fromTargetKind, "", "", "", "", false) + sysInfo := getSystemInfoTarget(ctx, fromAppliance, creds.TargetKind, creds.User, 0, creds.Identity, "auto", creds.Cert, creds.Key) + if sysInfo != nil { + sysInfo.PopulateCaseAttributes() + spinner.Success(fmt.Sprintf("Autodetected %s %s (Serial: %s)", sysInfo.ApplianceKind(), sysInfo.Version, sysInfo.PreferredSerialNumber())) + for k, v := range sysInfo.CaseAttributes { + if _, exists := payload[k]; !exists && v != "" { + payload[k] = v + } + } + } else { + spinner.Fail("Failed to extract appliance info") + exitFunc(1) + } + } + // Warn if BIG-IP TMOS or hardware platform is EOL or approaching EOL family, _ := payload["productFamily"].(string) ver, _ := payload["version"].(string) @@ -1849,6 +1884,102 @@ func handleIHealth(ctx context.Context, args []string) { } // ---------------------------------------------------------------------------- +type ApplianceCreds struct { + User string + Password string + Cert string + Key string + Identity string + TargetKind string +} + +func resolveApplianceCreds(host, targetKind, flagUser, flagCert, flagKey, flagIdentity string, isSCP bool) ApplianceCreds { + cleanHost := strings.TrimSpace(host) + if _, h, _, _, err := bigip.ParseAndValidateApplianceHost(cleanHost, 443); err == nil && h != "" { + cleanHost = h + } + + // Host-matching awareness + prefix1 := "BIGIP" + prefix2 := "BIGIQ" + + if os.Getenv("BIGIQ_HOST") != "" && (strings.EqualFold(host, os.Getenv("BIGIQ_HOST")) || strings.EqualFold(cleanHost, os.Getenv("BIGIQ_HOST"))) { + prefix1, prefix2 = "BIGIQ", "BIGIP" + targetKind = "BIG-IQ" + } else if os.Getenv("BIGIP_HOST") != "" && (strings.EqualFold(host, os.Getenv("BIGIP_HOST")) || strings.EqualFold(cleanHost, os.Getenv("BIGIP_HOST"))) { + prefix1, prefix2 = "BIGIP", "BIGIQ" + targetKind = "BIG-IP" + } else if strings.EqualFold(targetKind, "BIG-IQ") || strings.EqualFold(targetKind, "bigiq") { + prefix1, prefix2 = "BIGIQ", "BIGIP" + targetKind = "BIG-IQ" + } else if strings.EqualFold(targetKind, "BIG-IP") || strings.EqualFold(targetKind, "bigip") { + prefix1, prefix2 = "BIGIP", "BIGIQ" + targetKind = "BIG-IP" + } else { + prefix1, prefix2 = "BIGIP", "BIGIQ" + targetKind = "auto" + } + + creds := ApplianceCreds{TargetKind: targetKind} + + // Username + if flagUser != "" { + creds.User = flagUser + } else if u := os.Getenv(prefix1 + "_USER"); u != "" { + creds.User = u + } else if u := os.Getenv(prefix2 + "_USER"); u != "" { + creds.User = u + } else if u := os.Getenv("APPLIANCE_USER"); u != "" { + creds.User = u + } else { + if isSCP { + creds.User = "root" + } else { + creds.User = "admin" + } + } + + // Password + if p := os.Getenv(prefix1 + "_PASSWORD"); p != "" { + creds.Password = p + } else if p := os.Getenv(prefix2 + "_PASSWORD"); p != "" { + creds.Password = p + } else if p := os.Getenv("APPLIANCE_PASSWORD"); p != "" { + creds.Password = p + } + + // Cert + if flagCert != "" { + creds.Cert = flagCert + } else if c := os.Getenv(prefix1 + "_CERT"); c != "" { + creds.Cert = c + } else if c := os.Getenv(prefix2 + "_CERT"); c != "" { + creds.Cert = c + } + + // Cert Key + if flagKey != "" { + creds.Key = flagKey + } else if k := os.Getenv(prefix1 + "_KEY"); k != "" { + creds.Key = k + } else if k := os.Getenv(prefix2 + "_KEY"); k != "" { + creds.Key = k + } + + // SSH Identity + if flagIdentity != "" { + creds.Identity = flagIdentity + } else if i := os.Getenv(prefix1 + "_SSH_KEY"); i != "" { + creds.Identity = i + } else if i := os.Getenv(prefix2 + "_SSH_KEY"); i != "" { + creds.Identity = i + } else if i := os.Getenv("SSH_KEY_PATH"); i != "" { + creds.Identity = i + } + + return creds +} + // Appliance & Push Commands (BIG-IP, BIG-IQ) // ---------------------------------------------------------------------------- @@ -1872,7 +2003,7 @@ func handlePush(ctx context.Context, args []string) { method := "auto" destPath := "" keyPath := "" - targetKind := "BIG-IP" + targetKind := "auto" certPath := "" certKeyPath := "" applyGeoIP := false @@ -1925,6 +2056,8 @@ func handlePush(ctx context.Context, args []string) { targ := args[i+1] if strings.EqualFold(targ, "bigiq") || strings.EqualFold(targ, "big-iq") { targetKind = "BIG-IQ" + } else { + targetKind = "BIG-IP" } i++ } @@ -1932,6 +2065,8 @@ func handlePush(ctx context.Context, args []string) { targ := strings.TrimPrefix(arg, "--target=") if strings.EqualFold(targ, "bigiq") || strings.EqualFold(targ, "big-iq") { targetKind = "BIG-IQ" + } else { + targetKind = "BIG-IP" } } else if arg == "--cert" { if i+1 < len(args) { @@ -1960,23 +2095,6 @@ func handlePush(ctx context.Context, args []string) { } } - if certPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certPath = os.Getenv("BIGIQ_CERT") - } - if certPath == "" { - certPath = os.Getenv("BIGIP_CERT") - } - } - if certKeyPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certKeyPath = os.Getenv("BIGIQ_KEY") - } - if certKeyPath == "" { - certKeyPath = os.Getenv("BIGIP_KEY") - } - } - if len(positional) < 2 { printPushUsage() exitFunc(1) @@ -1984,7 +2102,10 @@ func handlePush(ctx context.Context, args []string) { host := positional[0] localFile := positional[1] - executePushToAppliance(ctx, host, localFile, method, destPath, user, port, keyPath, targetKind, certPath, certKeyPath, applyGeoIP, keepExtracted, jsonOutput) + + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp" || method == "ssh") + + executePushToAppliance(ctx, host, localFile, method, destPath, creds.User, port, creds.Identity, creds.TargetKind, creds.Cert, creds.Key, applyGeoIP, keepExtracted, jsonOutput) } func handlePull(ctx context.Context, args []string) { @@ -1999,7 +2120,7 @@ func handlePull(ctx context.Context, args []string) { method := "auto" localDest := "" keyPath := "" - targetKind := "BIG-IP" + targetKind := "auto" certPath := "" certKeyPath := "" @@ -2051,6 +2172,8 @@ func handlePull(ctx context.Context, args []string) { targ := args[i+1] if strings.EqualFold(targ, "bigiq") || strings.EqualFold(targ, "big-iq") { targetKind = "BIG-IQ" + } else { + targetKind = "BIG-IP" } i++ } @@ -2058,6 +2181,8 @@ func handlePull(ctx context.Context, args []string) { targ := strings.TrimPrefix(arg, "--target=") if strings.EqualFold(targ, "bigiq") || strings.EqualFold(targ, "big-iq") { targetKind = "BIG-IQ" + } else { + targetKind = "BIG-IP" } } else if arg == "--cert" { if i+1 < len(args) { @@ -2080,23 +2205,6 @@ func handlePull(ctx context.Context, args []string) { } } - if certPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certPath = os.Getenv("BIGIQ_CERT") - } - if certPath == "" { - certPath = os.Getenv("BIGIP_CERT") - } - } - if certKeyPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certKeyPath = os.Getenv("BIGIQ_KEY") - } - if certKeyPath == "" { - certKeyPath = os.Getenv("BIGIP_KEY") - } - } - if len(positional) < 2 { printPullUsage() exitFunc(1) @@ -2104,13 +2212,54 @@ func handlePull(ctx context.Context, args []string) { host := positional[0] remoteFile := positional[1] - executeDownloadFromAppliance(ctx, host, remoteFile, localDest, method, user, port, keyPath, targetKind, certPath, certKeyPath) + + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp" || method == "ssh") + + executeDownloadFromAppliance(ctx, host, remoteFile, localDest, method, creds.User, port, creds.Identity, creds.TargetKind, creds.Cert, creds.Key) +} + +func detectApplianceKind(ctx context.Context, host string, port int, user, pw string, pwBytes []byte, certPath, certKeyPath, fallbackKind string) string { + if pw != "" || len(pwBytes) > 0 || certPath != "" { + detectCtx, cancel := context.WithTimeout(ctx, 4*time.Second) + defer cancel() + c, err := bigip.NewClientWithOptions(bigip.ClientOptions{ + Host: host, + Port: port, + Username: user, + Password: pw, + SkipTLSVerify: true, + ClientCertPath: certPath, + ClientKeyPath: certKeyPath, + Timeout: 4 * time.Second, + }) + if err == nil { + defer c.Zero() + if kind, kErr := c.CheckReadyWithKind(detectCtx); kErr == nil && kind != "" { + return kind + } + } + } + if strings.EqualFold(fallbackKind, "BIG-IQ") { + return "BIG-IQ" + } + if strings.EqualFold(fallbackKind, "BIG-IP") { + return "BIG-IP" + } + return "Appliance" } func handleAppliance(ctx context.Context, targetKind string, args []string) { - cmdName := "bigip" - if strings.EqualFold(targetKind, "BIG-IQ") { + cmdName := strings.ToLower(targetKind) + switch cmdName { + case "bigiq", "big-iq": + targetKind = "BIG-IQ" cmdName = "bigiq" + case "bigip", "big-ip": + targetKind = "BIG-IP" + cmdName = "bigip" + default: + targetKind = "auto" + cmdName = "appliance" } if len(args) == 0 { @@ -2206,23 +2355,6 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { } } - if certPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certPath = os.Getenv("BIGIQ_CERT") - } - if certPath == "" { - certPath = os.Getenv("BIGIP_CERT") - } - } - if certKeyPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certKeyPath = os.Getenv("BIGIQ_KEY") - } - if certKeyPath == "" { - certKeyPath = os.Getenv("BIGIP_KEY") - } - } - method = strings.ToLower(strings.TrimSpace(method)) if method != "auto" && method != "icontrol" && method != "scp" && method != "ssh" { fmt.Fprintf(os.Stderr, "[ERROR] Invalid method %q. Valid methods: 'auto', 'icontrol', 'scp'\n", method) @@ -2239,27 +2371,13 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { exitFunc(1) } host := positional[0] - if user == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - user = os.Getenv("BIGIQ_USER") - } - if user == "" { - user = os.Getenv("BIGIP_USER") - } - if user == "" { - user = "admin" - } - } + + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp") + targetKind = creds.TargetKind - pw := "" - if strings.EqualFold(targetKind, "BIG-IQ") { - pw = os.Getenv("BIGIQ_PASSWORD") - } - if pw == "" { - pw = os.Getenv("BIGIP_PASSWORD") - } - if pw == "" && certPath == "" && term.IsTerminal(int(os.Stdin.Fd())) { - fmt.Printf("Enter %s password for %s@%s: ", targetKind, user, host) + pw := creds.Password + if pw == "" && creds.Cert == "" && term.IsTerminal(int(os.Stdin.Fd())) { + fmt.Printf("Enter %s password for %s@%s: ", targetKind, creds.User, host) bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { @@ -2268,7 +2386,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { auth.ZeroBytes(bytePw) } } - if pw == "" && certPath == "" { + if pw == "" && creds.Cert == "" { fmt.Fprintf(os.Stderr, "[ERROR] Password or client certificate required. Set BIGIP_PASSWORD / BIGIQ_PASSWORD / BIGIP_CERT or enter at prompt.\n") exitFunc(1) } @@ -2280,21 +2398,33 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { client, err := bigip.NewClientWithOptions(bigip.ClientOptions{ Host: host, Port: port, - Username: user, + Username: creds.User, Password: pw, PasswordBytes: pwBytes, SkipTLSVerify: true, - ClientCertPath: certPath, - ClientKeyPath: certKeyPath, + ClientCertPath: creds.Cert, + ClientKeyPath: creds.Key, }) checkErr(ctx, err, "Failed to initialize appliance client") defer client.Zero() - ready, err := client.CheckReady(ctx) + + var kind string + if client != nil { + kind, err = client.CheckReadyWithKind(ctx) + } else { + // CheckReady fallback? + kind = targetKind + } + checkErr(ctx, err, "Ready check failed") - if ready { + if kind != "" { + targetKind = kind fmt.Printf("%s appliance at %s is READY (HTTP 200).\n", targetKind, host) } else { - fmt.Printf("%s appliance at %s is NOT READY.\n", targetKind, host) + if targetKind == "auto" { + targetKind = "Appliance" + } + fmt.Printf("%s at %s is NOT READY.\n", targetKind, host) } case "info", "system-info", "sysinfo": @@ -2303,7 +2433,8 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { exitFunc(1) } target := positional[0] - info := getSystemInfoTarget(ctx, target, targetKind, user, port, keyPath, method, certPath, certKeyPath) + creds := resolveApplianceCreds(target, targetKind, user, certPath, certKeyPath, keyPath, method == "scp") + info := getSystemInfoTarget(ctx, target, creds.TargetKind, creds.User, port, creds.Identity, method, creds.Cert, creds.Key) if jsonOutput { enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") @@ -2320,7 +2451,8 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { exitFunc(1) } target := positional[0] - info := getSystemInfoTarget(ctx, target, targetKind, user, port, keyPath, method, certPath, certKeyPath) + creds := resolveApplianceCreds(target, targetKind, user, certPath, certKeyPath, keyPath, method == "scp") + info := getSystemInfoTarget(ctx, target, creds.TargetKind, creds.User, port, creds.Identity, method, creds.Cert, creds.Key) sn := info.PreferredSerialNumber() if jsonOutput { res := map[string]string{ @@ -2349,13 +2481,10 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { } host := positional[0] localFile := positional[1] - executePushToAppliance(ctx, host, localFile, method, destPath, user, port, keyPath, targetKind, certPath, certKeyPath, applyGeoIP, keepExtracted, jsonOutput) + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp") + executePushToAppliance(ctx, host, localFile, method, destPath, creds.User, port, creds.Identity, creds.TargetKind, creds.Cert, creds.Key, applyGeoIP, keepExtracted, jsonOutput) case "geoip": - if strings.EqualFold(targetKind, "BIG-IQ") { - fmt.Fprintf(os.Stderr, "[ERROR] GeoIP database updates are only supported on BIG-IP appliances.\n") - exitFunc(1) - } if len(positional) < 2 { fmt.Fprintf(os.Stderr, "Usage: myf5 %s geoip [--method auto|icontrol|scp] [--dest ] [--keep-extracted] [--user ] [--port ] [-i ] [--cert ] [--cert-key ] [--json]\n", cmdName) exitFunc(1) @@ -2363,9 +2492,26 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { host := positional[0] zipTarget := positional[1] + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp") + + if creds.TargetKind == "auto" { + // Note: ApplyGeoIP will error out if it detects BIG-IQ, but we can do a quick check + // We can leave TargetKind as is; we will pass it. + // Let's pass "BIG-IP" if it's auto to bypass initial blocks in legacy logic, + // ApplyGeoIP will handle actual check. But ApplyGeoIP in geoip.go takes TargetType. + // We will just let ApplyGeoIP do its thing, or detect it. + if targetKind == "BIG-IQ" { + fmt.Fprintf(os.Stderr, "[ERROR] GeoIP database updates are only supported on BIG-IP appliances.\n") + exitFunc(1) + } + } else if strings.EqualFold(creds.TargetKind, "BIG-IQ") { + fmt.Fprintf(os.Stderr, "[ERROR] GeoIP database updates are only supported on BIG-IP appliances.\n") + exitFunc(1) + } + if fi, err := os.Stat(zipTarget); err == nil && !fi.IsDir() { // Local file: push it to appliance and apply - executePushToAppliance(ctx, host, zipTarget, method, destPath, user, port, keyPath, targetKind, certPath, certKeyPath, true, keepExtracted, jsonOutput) + executePushToAppliance(ctx, host, zipTarget, method, destPath, creds.User, port, creds.Identity, creds.TargetKind, creds.Cert, creds.Key, true, keepExtracted, jsonOutput) } else { // Remote file on appliance: apply directly if err := bigip.ValidateRemoteAppliancePath(zipTarget); err != nil { @@ -2373,24 +2519,10 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { exitFunc(1) } - if user == "" { - user = os.Getenv("BIGIP_USER") - if user == "" { - user = "admin" - } - } - pw := os.Getenv("BIGIP_PASSWORD") - if keyPath == "" { - if k := os.Getenv("BIGIP_SSH_KEY"); k != "" { - keyPath = k - } else if k := os.Getenv("SSH_KEY_PATH"); k != "" { - keyPath = k - } - } - - if pw == "" && keyPath == "" && certPath == "" { + pw := creds.Password + if pw == "" && creds.Identity == "" && creds.Cert == "" { if !hasDefaultSSHAuth() && term.IsTerminal(int(os.Stdin.Fd())) { - fmt.Printf("Enter %s password for %s@%s: ", targetKind, user, host) + fmt.Printf("Enter %s password for %s@%s: ", creds.TargetKind, creds.User, host) bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { @@ -2412,14 +2544,15 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { } geoOpts := bigip.GeoIPOptions{ Port: port, - Username: user, + Username: creds.User, Password: pw, PasswordBytes: pwBytes, - IdentityFile: keyPath, - ClientCertPath: certPath, - ClientKeyPath: certKeyPath, + IdentityFile: creds.Identity, + ClientCertPath: creds.Cert, + ClientKeyPath: creds.Key, Method: bigip.TransferMethod(method), KeepExtracted: keepExtracted, + TargetType: creds.TargetKind, } defer geoOpts.Zero() @@ -2468,7 +2601,8 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { } host := positional[0] remoteFile := positional[1] - executeDownloadFromAppliance(ctx, host, remoteFile, destPath, method, user, port, keyPath, targetKind, certPath, certKeyPath) + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp") + executeDownloadFromAppliance(ctx, host, remoteFile, destPath, method, creds.User, port, creds.Identity, creds.TargetKind, creds.Cert, creds.Key) case "qkview": if len(positional) < 1 { @@ -2476,24 +2610,15 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { exitFunc(1) } host := positional[0] - if user == "" { - user = os.Getenv("BIGIP_USER") - if user == "" { - user = "admin" - } - } - pw := os.Getenv("BIGIP_PASSWORD") - if keyPath == "" { - if k := os.Getenv("BIGIP_SSH_KEY"); k != "" { - keyPath = k - } else if k := os.Getenv("SSH_KEY_PATH"); k != "" { - keyPath = k - } - } + + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp" || method == "ssh") + targetKind = creds.TargetKind - if pw == "" && keyPath == "" && certPath == "" { + pw := creds.Password + + if pw == "" && creds.Identity == "" && creds.Cert == "" { if !hasDefaultSSHAuth() && term.IsTerminal(int(os.Stdin.Fd())) { - fmt.Printf("Enter %s password for %s@%s: ", targetKind, user, host) + fmt.Printf("Enter %s password for %s@%s: ", targetKind, creds.User, host) bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { @@ -2529,13 +2654,13 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { qkOpts := bigip.TransferOptions{ TargetType: targetKind, Method: transferMethod, - Username: user, + Username: creds.User, Password: pw, PasswordBytes: pwBytes, Port: port, - IdentityFile: keyPath, - ClientCertPath: certPath, - ClientKeyPath: certKeyPath, + IdentityFile: creds.Identity, + ClientCertPath: creds.Cert, + ClientKeyPath: creds.Key, Timeout: 30 * time.Second, } defer qkOpts.Zero() @@ -2639,45 +2764,21 @@ func getSystemInfoTarget(ctx context.Context, target, targetKind, user string, p } host := target - if user == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - user = os.Getenv("BIGIQ_USER") - } - if user == "" { - user = os.Getenv("BIGIP_USER") - } - if user == "" { - user = "admin" - } - } - - if certPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certPath = os.Getenv("BIGIQ_CERT") - } - if certPath == "" { - certPath = os.Getenv("BIGIP_CERT") - } - } - if certKeyPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certKeyPath = os.Getenv("BIGIQ_KEY") - } - if certKeyPath == "" { - certKeyPath = os.Getenv("BIGIP_KEY") - } - } - - pw := "" - if strings.EqualFold(targetKind, "BIG-IQ") { - pw = os.Getenv("BIGIQ_PASSWORD") - } - if pw == "" { - pw = os.Getenv("BIGIP_PASSWORD") - } + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp" || method == "ssh") + user = creds.User + certPath = creds.Cert + certKeyPath = creds.Key + keyPath = creds.Identity + targetKind = creds.TargetKind + + pw := creds.Password if pw == "" && keyPath == "" && certPath == "" { if !hasDefaultSSHAuth() && term.IsTerminal(int(os.Stdin.Fd())) { - fmt.Printf("Enter %s password for %s@%s: ", targetKind, user, host) + promptKind := targetKind + if promptKind == "" || promptKind == "auto" { + promptKind = "appliance" + } + fmt.Printf("Enter %s password for %s@%s: ", promptKind, user, host) bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { @@ -2807,58 +2908,21 @@ func executePushToAppliance( fileSize := stat.Size() baseName := filepath.Base(localPath) - if user == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - user = os.Getenv("BIGIQ_USER") - } - if user == "" { - user = os.Getenv("BIGIP_USER") - } - if user == "" { - if method == "scp" { - user = "root" - } else { - user = "admin" - } - } - } - - if certPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certPath = os.Getenv("BIGIQ_CERT") - } - if certPath == "" { - certPath = os.Getenv("BIGIP_CERT") - } - } - if certKeyPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certKeyPath = os.Getenv("BIGIQ_KEY") - } - if certKeyPath == "" { - certKeyPath = os.Getenv("BIGIP_KEY") - } - } - - pw := "" - if strings.EqualFold(targetKind, "BIG-IQ") { - pw = os.Getenv("BIGIQ_PASSWORD") - } - if pw == "" { - pw = os.Getenv("BIGIP_PASSWORD") - } - - if keyPath == "" { - if k := os.Getenv("BIGIP_SSH_KEY"); k != "" { - keyPath = k - } else if k := os.Getenv("SSH_KEY_PATH"); k != "" { - keyPath = k - } - } + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp") + user = creds.User + certPath = creds.Cert + certKeyPath = creds.Key + keyPath = creds.Identity + targetKind = creds.TargetKind + pw := creds.Password if pw == "" && keyPath == "" && certPath == "" { if !hasDefaultSSHAuth() && term.IsTerminal(int(os.Stdin.Fd())) { - fmt.Printf("Enter %s password for %s@%s: ", targetKind, user, host) + promptKind := targetKind + if promptKind == "" || promptKind == "auto" { + promptKind = "appliance" + } + fmt.Printf("Enter %s password for %s@%s: ", promptKind, user, host) bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { @@ -2874,6 +2938,12 @@ func executePushToAppliance( pwBytes = []byte(pw) } + targetKind = detectApplianceKind(ctx, host, port, user, pw, pwBytes, certPath, certKeyPath, targetKind) + if applyGeoIP && strings.EqualFold(targetKind, "BIG-IQ") { + fmt.Fprintf(os.Stderr, "[ERROR] Autodetected BIG-IQ appliance on %s: GeoIP database updates are only supported on BIG-IP appliances.\n", host) + exitFunc(1) + } + opts := bigip.TransferOptions{ TargetType: targetKind, Method: bigip.TransferMethod(method), @@ -3060,58 +3130,21 @@ func executeDownloadFromAppliance( localDest = filepath.Join(getDefaultDownloadsDir(), base) } - if user == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - user = os.Getenv("BIGIQ_USER") - } - if user == "" { - user = os.Getenv("BIGIP_USER") - } - if user == "" { - if method == "scp" { - user = "root" - } else { - user = "admin" - } - } - } - - if certPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certPath = os.Getenv("BIGIQ_CERT") - } - if certPath == "" { - certPath = os.Getenv("BIGIP_CERT") - } - } - if certKeyPath == "" { - if strings.EqualFold(targetKind, "BIG-IQ") { - certKeyPath = os.Getenv("BIGIQ_KEY") - } - if certKeyPath == "" { - certKeyPath = os.Getenv("BIGIP_KEY") - } - } - - pw := "" - if strings.EqualFold(targetKind, "BIG-IQ") { - pw = os.Getenv("BIGIQ_PASSWORD") - } - if pw == "" { - pw = os.Getenv("BIGIP_PASSWORD") - } - - if keyPath == "" { - if k := os.Getenv("BIGIP_SSH_KEY"); k != "" { - keyPath = k - } else if k := os.Getenv("SSH_KEY_PATH"); k != "" { - keyPath = k - } - } + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp") + user = creds.User + certPath = creds.Cert + certKeyPath = creds.Key + keyPath = creds.Identity + targetKind = creds.TargetKind + pw := creds.Password if pw == "" && keyPath == "" && certPath == "" { if !hasDefaultSSHAuth() && term.IsTerminal(int(os.Stdin.Fd())) { - fmt.Printf("Enter %s password for %s@%s: ", targetKind, user, host) + promptKind := targetKind + if promptKind == "" || promptKind == "auto" { + promptKind = "appliance" + } + fmt.Printf("Enter %s password for %s@%s: ", promptKind, user, host) bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { @@ -3127,6 +3160,8 @@ func executeDownloadFromAppliance( pwBytes = []byte(pw) } + targetKind = detectApplianceKind(ctx, host, port, user, pw, pwBytes, certPath, certKeyPath, targetKind) + opts := bigip.TransferOptions{ TargetType: targetKind, Method: bigip.TransferMethod(method), diff --git a/pkg/bigip/client.go b/pkg/bigip/client.go index ddb5afa..cb9a324 100644 --- a/pkg/bigip/client.go +++ b/pkg/bigip/client.go @@ -336,23 +336,23 @@ func (c *Client) BaseURL() string { return fmt.Sprintf("%s://%s:%d", scheme, host, c.Port) } -// CheckReady queries /mgmt/tm/sys/ready (or /mgmt/shared/echo for BIG-IQ) to verify appliance availability. -func (c *Client) CheckReady(ctx context.Context) (bool, error) { +// CheckReadyWithKind queries /mgmt/tm/sys/ready (or /mgmt/shared/echo for BIG-IQ) to verify appliance availability and returns the appliance kind. +func (c *Client) CheckReadyWithKind(ctx context.Context) (string, error) { url := fmt.Sprintf("%s/mgmt/tm/sys/ready", c.BaseURL()) req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { - return false, err + return "", err } c.setAuth(req) resp, err := c.HTTPClient.Do(req) if err != nil { - return false, fmt.Errorf("device reachability check failed: %w", err) + return "", fmt.Errorf("device reachability check failed: %w", err) } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { - return true, nil + return "BIG-IP", nil } // Fallback to /mgmt/shared/echo for BIG-IQ and appliances without sys ready @@ -363,12 +363,23 @@ func (c *Client) CheckReady(ctx context.Context) (bool, error) { c.setAuth(echoReq) if echoResp, doErr := c.HTTPClient.Do(echoReq); doErr == nil { defer echoResp.Body.Close() - return echoResp.StatusCode == http.StatusOK, nil + if echoResp.StatusCode == http.StatusOK { + return "BIG-IQ", nil + } } } } - return false, nil + return "", nil +} + +// CheckReady queries /mgmt/tm/sys/ready (or /mgmt/shared/echo for BIG-IQ) to verify appliance availability. +func (c *Client) CheckReady(ctx context.Context) (bool, error) { + kind, err := c.CheckReadyWithKind(ctx) + if err != nil { + return false, err + } + return kind != "", nil } var validQKViewFilenameRegex = regexp.MustCompile(`^[a-zA-Z0-9_\-\.]+$`) @@ -609,6 +620,33 @@ func (c *Client) GenerateQKViewWithStatus(ctx context.Context, filename string, } defer res.resp.Body.Close() + if res.resp.StatusCode == http.StatusNotFound { + // Fallback to bash for BIG-IQ where /mgmt/tm/util/qkview may return 404 + bashArgs := fmt.Sprintf("-c \"mkdir -p /var/tmp/qkviews && /usr/bin/qkview %s-f /var/tmp/qkviews/%s && cp /var/tmp/qkviews/%s /var/config/rest/downloads/\"", map[bool]string{true: "-s0 ", false: ""}[complete], filename, filename) + bashPayload := map[string]string{ + "command": "run", + "utilCmdArgs": bashArgs, + } + bashBytes, _ := json.Marshal(bashPayload) + bashURL := fmt.Sprintf("%s/mgmt/tm/util/bash", c.BaseURL()) + bashReq, err := http.NewRequestWithContext(ctx, http.MethodPost, bashURL, bytes.NewReader(bashBytes)) + if err != nil { + return "", err + } + c.setAuth(bashReq) + bashReq.Header.Set("Content-Type", "application/json") + bashResp, err := c.HTTPClient.Do(bashReq) + if err != nil { + return "", fmt.Errorf("bash fallback for qkview failed: %w", err) + } + defer bashResp.Body.Close() + if bashResp.StatusCode < 200 || bashResp.StatusCode >= 300 { + b, _ := io.ReadAll(io.LimitReader(bashResp.Body, 1024*1024)) + return "", fmt.Errorf("bash qkview generation failed with HTTP %d: %s", bashResp.StatusCode, string(b)) + } + return filename, nil + } + if res.resp.StatusCode < 200 || res.resp.StatusCode >= 300 { b, _ := io.ReadAll(io.LimitReader(res.resp.Body, 1024*1024)) return "", fmt.Errorf("qkview generation failed with HTTP %d: %s", res.resp.StatusCode, string(b)) diff --git a/pkg/bigip/client_test.go b/pkg/bigip/client_test.go index f3504ef..43741fc 100644 --- a/pkg/bigip/client_test.go +++ b/pkg/bigip/client_test.go @@ -16,11 +16,12 @@ import ( func TestCheckReady(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/mgmt/tm/sys/ready" { - t.Errorf("unexpected path: %s", r.URL.Path) + if r.URL.Path == "/mgmt/tm/sys/ready" { + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"kind": "tm:sys:ready"}`)) + return } - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"kind": "tm:sys:ready"}`)) + t.Errorf("unexpected path: %s", r.URL.Path) })) defer server.Close() @@ -38,6 +39,44 @@ func TestCheckReady(t *testing.T) { if !ready { t.Errorf("expected appliance to be ready") } + + kind, err := c.CheckReadyWithKind(context.Background()) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if kind != "BIG-IP" { + t.Errorf("expected BIG-IP, got %q", kind) + } +} + +func TestCheckReadyWithKind_BIGIQ(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/mgmt/tm/sys/ready" { + w.WriteHeader(http.StatusNotFound) + return + } + if r.URL.Path == "/mgmt/shared/echo" { + w.WriteHeader(http.StatusOK) + return + } + t.Errorf("unexpected path: %s", r.URL.Path) + })) + defer server.Close() + + u, _ := url.Parse(server.URL) + port, _ := strconv.Atoi(u.Port()) + + c := NewClient(u.Hostname(), port, "admin", "secret") + c.Scheme = "http" + c.HTTPClient = server.Client() + + kind, err := c.CheckReadyWithKind(context.Background()) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if kind != "BIG-IQ" { + t.Errorf("expected BIG-IQ, got %q", kind) + } } func TestBaseURLAndURLNormalization(t *testing.T) { @@ -195,6 +234,47 @@ func TestGenerateQKViewDefaultFilenameISO8601(t *testing.T) { } } +func TestGenerateQKViewBIGIQFallback(t *testing.T) { + bashCalled := false + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/mgmt/tm/util/qkview" { + w.WriteHeader(http.StatusNotFound) + return + } + if r.URL.Path == "/mgmt/tm/util/bash" { + bashCalled = true + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"commandResult":"success"}`)) + return + } + if r.URL.Path == "/mgmt/cm/autodeploy/qkview" { + w.WriteHeader(http.StatusNotFound) + return + } + })) + defer server.Close() + + u, _ := url.Parse(server.URL) + port, _ := strconv.Atoi(u.Port()) + + c := NewClient(u.Hostname(), port, "admin", "secret") + c.Scheme = "http" + c.HTTPClient = server.Client() + + filename, err := c.GenerateQKViewWithStatus(context.Background(), "test.qkview", true, nil) + if err != nil { + t.Fatalf("GenerateQKViewWithStatus failed: %v", err) + } + + if filename != "test.qkview" { + t.Errorf("expected test.qkview, got %q", filename) + } + if !bashCalled { + t.Errorf("expected bash fallback to be called for BIG-IQ") + } +} + func TestValidateHost(t *testing.T) { tests := []struct { name string diff --git a/pkg/bigip/failover.go b/pkg/bigip/failover.go index 0a2f751..cfc65f3 100644 --- a/pkg/bigip/failover.go +++ b/pkg/bigip/failover.go @@ -183,16 +183,10 @@ func DownloadFileWithFailover( return savedPath, MethodSCP, nil case MethodAuto: - // Try iControl REST first if password is provided or file looks like an autodeploy resource (/shared/images or /var/tmp/qkviews) - cleanRemote := path.Clean(remotePath) - isRestFriendly := strings.HasPrefix(cleanRemote, "/shared/images") || - strings.HasPrefix(cleanRemote, "/var/tmp/qkviews") || - strings.HasPrefix(cleanRemote, "/mgmt/") || - strings.HasSuffix(cleanRemote, ".iso") || - strings.HasSuffix(cleanRemote, ".qkview") - + // If an explicit SSH identity key (-i) was provided, prefer SCP first. + // Otherwise, try iControl REST first when REST credentials (password/cert) are available. hasRestAuth := opts.Password != "" || len(opts.PasswordBytes) > 0 || opts.ClientCertPath != "" || os.Getenv("BIGIP_PASSWORD") != "" || os.Getenv("BIGIQ_PASSWORD") != "" - tryRestFirst := hasRestAuth && (isRestFriendly || opts.IdentityFile == "") + tryRestFirst := opts.IdentityFile == "" && hasRestAuth if tryRestFirst { savedPath, restErr := downloadViaIControl(ctx, host, remotePath, localDest, opts, progressCb) @@ -249,12 +243,17 @@ func newClientFromOptions(host string, opts TransferOptions, defaultPort int) *C if user == "" { user = "admin" } + var pwBytes []byte + if len(opts.PasswordBytes) > 0 { + pwBytes = make([]byte, len(opts.PasswordBytes)) + copy(pwBytes, opts.PasswordBytes) + } c, err := NewClientWithOptions(ClientOptions{ Host: host, Port: port, Username: user, Password: opts.Password, - PasswordBytes: opts.PasswordBytes, + PasswordBytes: pwBytes, SkipTLSVerify: true, ClientCertPath: opts.ClientCertPath, ClientKeyPath: opts.ClientKeyPath, @@ -296,23 +295,37 @@ func pushViaIControl( return remoteUploaded, nil } -func pushViaSCP( - ctx context.Context, - host, localFile, destDir string, - opts TransferOptions, - progressCb func(transferred, total int64), -) (string, error) { - scpOpts := SCPOptions{ +func newSCPOptions(host string, opts TransferOptions) SCPOptions { + var pwBytes []byte + if len(opts.PasswordBytes) > 0 { + pwBytes = make([]byte, len(opts.PasswordBytes)) + copy(pwBytes, opts.PasswordBytes) + } + var passBytes []byte + if len(opts.SSHPassphraseBytes) > 0 { + passBytes = make([]byte, len(opts.SSHPassphraseBytes)) + copy(passBytes, opts.SSHPassphraseBytes) + } + return SCPOptions{ Host: host, Port: opts.Port, Username: opts.Username, Password: opts.Password, - PasswordBytes: opts.PasswordBytes, + PasswordBytes: pwBytes, KeyPath: opts.IdentityFile, Passphrase: opts.SSHPassphrase, - PassphraseBytes: opts.SSHPassphraseBytes, + PassphraseBytes: passBytes, Timeout: opts.Timeout, } +} + +func pushViaSCP( + ctx context.Context, + host, localFile, destDir string, + opts TransferOptions, + progressCb func(transferred, total int64), +) (string, error) { + scpOpts := newSCPOptions(host, opts) defer scpOpts.Zero() return SCPUpload(ctx, localFile, destDir, scpOpts, progressCb) } @@ -348,17 +361,7 @@ func downloadViaSCP( opts TransferOptions, progressCb func(transferred, total int64), ) (string, error) { - scpOpts := SCPOptions{ - Host: host, - Port: opts.Port, - Username: opts.Username, - Password: opts.Password, - PasswordBytes: opts.PasswordBytes, - KeyPath: opts.IdentityFile, - Passphrase: opts.SSHPassphrase, - PassphraseBytes: opts.SSHPassphraseBytes, - Timeout: opts.Timeout, - } + scpOpts := newSCPOptions(host, opts) defer scpOpts.Zero() return SCPDownload(ctx, remotePath, localDest, scpOpts, progressCb) } @@ -390,17 +393,7 @@ func GenerateQKViewWithFailover( return filename, MethodIControl, nil case MethodSCP: - scpOpts := SCPOptions{ - Host: host, - Port: opts.Port, - Username: opts.Username, - Password: opts.Password, - PasswordBytes: opts.PasswordBytes, - KeyPath: opts.IdentityFile, - Passphrase: opts.SSHPassphrase, - PassphraseBytes: opts.SSHPassphraseBytes, - Timeout: opts.Timeout, - } + scpOpts := newSCPOptions(host, opts) defer scpOpts.Zero() filename, err := GenerateQKViewSSH(ctx, scpOpts, requestedFilename, complete, statusCb) if err != nil { @@ -410,7 +403,7 @@ func GenerateQKViewWithFailover( case MethodAuto: // If password or client certificate is provided and no key, try iControl REST first - tryRestFirst := opts.Password != "" || len(opts.PasswordBytes) > 0 || opts.ClientCertPath != "" || (opts.IdentityFile == "" && os.Getenv("BIGIP_PASSWORD") != "") + tryRestFirst := opts.IdentityFile == "" && (opts.Password != "" || len(opts.PasswordBytes) > 0 || opts.ClientCertPath != "" || os.Getenv("BIGIP_PASSWORD") != "") if tryRestFirst { client := newClientFromOptions(host, opts, 443) @@ -427,17 +420,7 @@ func GenerateQKViewWithFailover( logFn("iControl REST QKView generation failed (%v). Automatically falling back to SSH...", restErr) } - scpOpts := SCPOptions{ - Host: host, - Port: opts.Port, - Username: opts.Username, - Password: opts.Password, - PasswordBytes: opts.PasswordBytes, - KeyPath: opts.IdentityFile, - Passphrase: opts.SSHPassphrase, - PassphraseBytes: opts.SSHPassphraseBytes, - Timeout: opts.Timeout, - } + scpOpts := newSCPOptions(host, opts) defer scpOpts.Zero() filename, sshErr := GenerateQKViewSSH(ctx, scpOpts, requestedFilename, complete, statusCb) if sshErr == nil { @@ -448,17 +431,7 @@ func GenerateQKViewWithFailover( } // Try SSH first - scpOpts := SCPOptions{ - Host: host, - Port: opts.Port, - Username: opts.Username, - Password: opts.Password, - PasswordBytes: opts.PasswordBytes, - KeyPath: opts.IdentityFile, - Passphrase: opts.SSHPassphrase, - PassphraseBytes: opts.SSHPassphraseBytes, - Timeout: opts.Timeout, - } + scpOpts := newSCPOptions(host, opts) filename, sshErr := GenerateQKViewSSH(ctx, scpOpts, requestedFilename, complete, statusCb) scpOpts.Zero() if sshErr == nil { @@ -489,7 +462,7 @@ func GenerateQKViewWithFailover( // DeleteQKViewWithFailover deletes a generated QKView archive on the appliance via REST or SSH. func DeleteQKViewWithFailover(ctx context.Context, host, remoteFilename string, opts TransferOptions) error { method := opts.Method - if method == MethodIControl || (method == MethodAuto && (opts.Password != "" || len(opts.PasswordBytes) > 0 || opts.ClientCertPath != "")) { + if method == MethodIControl || (method == MethodAuto && opts.IdentityFile == "" && (opts.Password != "" || len(opts.PasswordBytes) > 0 || opts.ClientCertPath != "")) { client := newClientFromOptions(host, opts, 443) defer client.Zero() if err := client.DeleteQKView(ctx, remoteFilename); err == nil { @@ -499,17 +472,7 @@ func DeleteQKViewWithFailover(ctx context.Context, host, remoteFilename string, } } - scpOpts := SCPOptions{ - Host: host, - Port: opts.Port, - Username: opts.Username, - Password: opts.Password, - PasswordBytes: opts.PasswordBytes, - KeyPath: opts.IdentityFile, - Passphrase: opts.SSHPassphrase, - PassphraseBytes: opts.SSHPassphraseBytes, - Timeout: opts.Timeout, - } + scpOpts := newSCPOptions(host, opts) defer scpOpts.Zero() return DeleteQKViewSSH(ctx, scpOpts, remoteFilename) } diff --git a/pkg/bigip/failover_test.go b/pkg/bigip/failover_test.go index 8bca218..c611001 100644 --- a/pkg/bigip/failover_test.go +++ b/pkg/bigip/failover_test.go @@ -161,3 +161,32 @@ func TestDownloadFileWithFailover_BothFail(t *testing.T) { t.Errorf("expected failover logger to be invoked") } } + +func TestTransferOptionsPasswordBytesNotZeroedAcrossCalls(t *testing.T) { + opts := TransferOptions{ + PasswordBytes: []byte("secret123"), + SSHPassphraseBytes: []byte("pass123"), + } + + // 1. Verify client creation with newClientFromOptions does not zero opts.PasswordBytes + client := newClientFromOptions("10.0.0.1", opts, 443) + if client == nil { + t.Fatalf("expected non-nil client") + } + client.Zero() + + if string(opts.PasswordBytes) != "secret123" { + t.Errorf("expected opts.PasswordBytes to remain %q, got %q", "secret123", string(opts.PasswordBytes)) + } + + // 2. Verify newSCPOptions and scpOpts.Zero() do not zero opts.PasswordBytes or opts.SSHPassphraseBytes + scpOpts := newSCPOptions("10.0.0.1", opts) + scpOpts.Zero() + + if string(opts.PasswordBytes) != "secret123" { + t.Errorf("expected opts.PasswordBytes to remain %q after scpOpts.Zero(), got %q", "secret123", string(opts.PasswordBytes)) + } + if string(opts.SSHPassphraseBytes) != "pass123" { + t.Errorf("expected opts.SSHPassphraseBytes to remain %q after scpOpts.Zero(), got %q", "pass123", string(opts.SSHPassphraseBytes)) + } +} diff --git a/pkg/bigip/geoip.go b/pkg/bigip/geoip.go index aa78925..797c0a0 100644 --- a/pkg/bigip/geoip.go +++ b/pkg/bigip/geoip.go @@ -252,6 +252,12 @@ func generateGeoIPScript(remoteZipPath string, force, keepExtracted bool) string return fmt.Sprintf(`( set -o pipefail + +if grep -qi '^Product:[[:space:]]*BIG-IQ' /VERSION 2>/dev/null; then + echo "ERROR: Autodetected BIG-IQ appliance. GeoIP database updates are only supported on BIG-IP appliances." >&2 + exit 8 +fi + ZIP_FILE=%q if [ ! -f "$ZIP_FILE" ]; then @@ -333,15 +339,24 @@ exit $SCRIPT_EXIT_CODE } func applyGeoIPSSH(ctx context.Context, host, scriptB64 string, opts GeoIPOptions) (string, error) { + var pwCopy, ppCopy []byte + if len(opts.PasswordBytes) > 0 { + pwCopy = make([]byte, len(opts.PasswordBytes)) + copy(pwCopy, opts.PasswordBytes) + } + if len(opts.SSHPassphraseBytes) > 0 { + ppCopy = make([]byte, len(opts.SSHPassphraseBytes)) + copy(ppCopy, opts.SSHPassphraseBytes) + } scpOpts := SCPOptions{ Host: host, Port: opts.Port, Username: opts.Username, Password: opts.Password, - PasswordBytes: opts.PasswordBytes, + PasswordBytes: pwCopy, KeyPath: opts.IdentityFile, Passphrase: opts.SSHPassphrase, - PassphraseBytes: opts.SSHPassphraseBytes, + PassphraseBytes: ppCopy, Timeout: opts.Timeout, } defer scpOpts.Zero() @@ -422,12 +437,18 @@ func applyGeoIPREST(ctx context.Context, host, scriptB64 string, opts GeoIPOptio user = "admin" } + var pwCopy []byte + if len(opts.PasswordBytes) > 0 { + pwCopy = make([]byte, len(opts.PasswordBytes)) + copy(pwCopy, opts.PasswordBytes) + } + client, err := NewClientWithOptions(ClientOptions{ Host: host, Port: port, Username: user, Password: opts.Password, - PasswordBytes: opts.PasswordBytes, + PasswordBytes: pwCopy, SkipTLSVerify: true, ClientCertPath: opts.ClientCertPath, ClientKeyPath: opts.ClientKeyPath, diff --git a/pkg/bigip/info.go b/pkg/bigip/info.go index 9bea043..857f1b1 100644 --- a/pkg/bigip/info.go +++ b/pkg/bigip/info.go @@ -58,6 +58,14 @@ func (s *SystemInfo) PreferredSerialNumber() string { return s.RegistrationKey } +// ApplianceKind returns "BIG-IQ" if the appliance is detected as BIG-IQ, or "BIG-IP" otherwise. +func (s *SystemInfo) ApplianceKind() string { + if s.IsBIGIQ() { + return "BIG-IQ" + } + return "BIG-IP" +} + // IsBIGIQ returns true if the appliance is a BIG-IQ Centralized Management system. func (s *SystemInfo) IsBIGIQ() bool { if s == nil { diff --git a/pkg/bigip/info_test.go b/pkg/bigip/info_test.go index 41bbff8..5450724 100644 --- a/pkg/bigip/info_test.go +++ b/pkg/bigip/info_test.go @@ -530,6 +530,18 @@ Active License } } +func TestApplianceKind(t *testing.T) { + s1 := &SystemInfo{Product: "BIG-IQ"} + if got := s1.ApplianceKind(); got != "BIG-IQ" { + t.Errorf("ApplianceKind() = %v, want BIG-IQ", got) + } + + s2 := &SystemInfo{Product: "BIG-IP"} + if got := s2.ApplianceKind(); got != "BIG-IP" { + t.Errorf("ApplianceKind() = %v, want BIG-IP", got) + } +} + func TestSystemInfo_SummaryPlatformEnrichment(t *testing.T) { // Case 1: Raw platform code C119 info1 := &SystemInfo{Platform: "C119"} From 2c5ae70d04a83e8d40fc1475d9cf8e2a8e8fc8d6 Mon Sep 17 00:00:00 2001 From: Greg Robinson Date: Sat, 7 Nov 2026 01:20:56 -0500 Subject: [PATCH 2/9] style(cli): gofmt cmd/myf5/main.go --- cmd/myf5/main.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmd/myf5/main.go b/cmd/myf5/main.go index 87d9ae7..ddb9fc8 100644 --- a/cmd/myf5/main.go +++ b/cmd/myf5/main.go @@ -2371,7 +2371,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { exitFunc(1) } host := positional[0] - + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp") targetKind = creds.TargetKind @@ -2407,7 +2407,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { }) checkErr(ctx, err, "Failed to initialize appliance client") defer client.Zero() - + var kind string if client != nil { kind, err = client.CheckReadyWithKind(ctx) @@ -2415,7 +2415,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { // CheckReady fallback? kind = targetKind } - + checkErr(ctx, err, "Ready check failed") if kind != "" { targetKind = kind @@ -2493,7 +2493,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { zipTarget := positional[1] creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp") - + if creds.TargetKind == "auto" { // Note: ApplyGeoIP will error out if it detects BIG-IQ, but we can do a quick check // We can leave TargetKind as is; we will pass it. @@ -2610,7 +2610,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { exitFunc(1) } host := positional[0] - + creds := resolveApplianceCreds(host, targetKind, user, certPath, certKeyPath, keyPath, method == "scp" || method == "ssh") targetKind = creds.TargetKind From bf6f2fb1fd5c43eb294d519d54a8214c7a5c9d35 Mon Sep 17 00:00:00 2001 From: Greg Robinson Date: Sat, 7 Nov 2026 01:44:24 -0500 Subject: [PATCH 3/9] sec(cli): enforce strict input validation, username/port/file checks, and host-bound credentials --- cmd/myf5/main.go | 421 +++++++++++++++++++++++---------------- cmd/myf5/main_test.go | 33 +++ pkg/bigip/client.go | 105 +++++++++- pkg/bigip/client_test.go | 93 +++++++++ pkg/bigip/scp.go | 8 + 5 files changed, 483 insertions(+), 177 deletions(-) diff --git a/cmd/myf5/main.go b/cmd/myf5/main.go index ddb9fc8..df41df3 100644 --- a/cmd/myf5/main.go +++ b/cmd/myf5/main.go @@ -1893,43 +1893,99 @@ type ApplianceCreds struct { TargetKind string } +func requireFlagValue(args []string, i int, flagName string) string { + if i+1 >= len(args) || strings.HasPrefix(args[i+1], "-") { + fmt.Fprintf(os.Stderr, "[ERROR] Flag %s requires a value\n", flagName) + exitFunc(1) + } + return args[i+1] +} + +func rejectSecretFlag(flagName string) { + fmt.Fprintf(os.Stderr, "[SECURITY ERROR] Passing passwords or secrets via command-line flags (%s) is prohibited because CLI arguments are exposed in the OS process table. Use environment variables or the interactive prompt.\n", flagName) + exitFunc(1) +} + func resolveApplianceCreds(host, targetKind, flagUser, flagCert, flagKey, flagIdentity string, isSCP bool) ApplianceCreds { - cleanHost := strings.TrimSpace(host) - if _, h, _, _, err := bigip.ParseAndValidateApplianceHost(cleanHost, 443); err == nil && h != "" { - cleanHost = h + isLocalFile := false + if fi, err := os.Stat(host); err == nil && fi.Mode().IsRegular() { + isLocalFile = true + } + if !isLocalFile { + if _, _, _, _, err := bigip.ParseAndValidateApplianceHost(host, 443); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } + } + + cleanEnvHost := func(raw string) string { + if raw == "" { + return "" + } + if _, h, _, _, err := bigip.ParseAndValidateApplianceHost(raw, 443); err == nil && h != "" { + return h + } + return strings.TrimSpace(raw) } - // Host-matching awareness - prefix1 := "BIGIP" - prefix2 := "BIGIQ" + envBigipHost := cleanEnvHost(os.Getenv("BIGIP_HOST")) + envBigiqHost := cleanEnvHost(os.Getenv("BIGIQ_HOST")) + cleanHost := cleanEnvHost(host) - if os.Getenv("BIGIQ_HOST") != "" && (strings.EqualFold(host, os.Getenv("BIGIQ_HOST")) || strings.EqualFold(cleanHost, os.Getenv("BIGIQ_HOST"))) { - prefix1, prefix2 = "BIGIQ", "BIGIP" + bigipAllowed := (envBigipHost == "" || strings.EqualFold(cleanHost, envBigipHost)) + bigiqAllowed := (envBigiqHost == "" || strings.EqualFold(cleanHost, envBigiqHost)) + + var prefixes []string + if envBigiqHost != "" && strings.EqualFold(cleanHost, envBigiqHost) { + prefixes = append(prefixes, "BIGIQ") targetKind = "BIG-IQ" - } else if os.Getenv("BIGIP_HOST") != "" && (strings.EqualFold(host, os.Getenv("BIGIP_HOST")) || strings.EqualFold(cleanHost, os.Getenv("BIGIP_HOST"))) { - prefix1, prefix2 = "BIGIP", "BIGIQ" + if bigipAllowed { + prefixes = append(prefixes, "BIGIP") + } + } else if envBigipHost != "" && strings.EqualFold(cleanHost, envBigipHost) { + prefixes = append(prefixes, "BIGIP") targetKind = "BIG-IP" - } else if strings.EqualFold(targetKind, "BIG-IQ") || strings.EqualFold(targetKind, "bigiq") { - prefix1, prefix2 = "BIGIQ", "BIGIP" + if bigiqAllowed { + prefixes = append(prefixes, "BIGIQ") + } + } else { + if bigipAllowed { + prefixes = append(prefixes, "BIGIP") + } + if bigiqAllowed { + prefixes = append(prefixes, "BIGIQ") + } + } + + if targetKind == "" || strings.EqualFold(targetKind, "auto") { + if len(prefixes) > 0 && prefixes[0] == "BIGIQ" { + targetKind = "BIG-IQ" + } else if len(prefixes) > 0 && prefixes[0] == "BIGIP" { + targetKind = "BIG-IP" + } else { + targetKind = "auto" + } + } else if strings.EqualFold(targetKind, "bigiq") { targetKind = "BIG-IQ" - } else if strings.EqualFold(targetKind, "BIG-IP") || strings.EqualFold(targetKind, "bigip") { - prefix1, prefix2 = "BIGIP", "BIGIQ" + } else if strings.EqualFold(targetKind, "bigip") { targetKind = "BIG-IP" - } else { - prefix1, prefix2 = "BIGIP", "BIGIQ" - targetKind = "auto" } creds := ApplianceCreds{TargetKind: targetKind} + getEnv := func(suffix string) string { + for _, p := range prefixes { + if v := os.Getenv(p + suffix); v != "" { + return v + } + } + return "" + } + // Username if flagUser != "" { creds.User = flagUser - } else if u := os.Getenv(prefix1 + "_USER"); u != "" { - creds.User = u - } else if u := os.Getenv(prefix2 + "_USER"); u != "" { - creds.User = u - } else if u := os.Getenv("APPLIANCE_USER"); u != "" { + } else if u := getEnv("_USER"); u != "" { creds.User = u } else { if isSCP { @@ -1938,44 +1994,54 @@ func resolveApplianceCreds(host, targetKind, flagUser, flagCert, flagKey, flagId creds.User = "admin" } } + if err := bigip.ValidateApplianceUsername(creds.User); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } // Password - if p := os.Getenv(prefix1 + "_PASSWORD"); p != "" { - creds.Password = p - } else if p := os.Getenv(prefix2 + "_PASSWORD"); p != "" { - creds.Password = p - } else if p := os.Getenv("APPLIANCE_PASSWORD"); p != "" { - creds.Password = p - } + creds.Password = getEnv("_PASSWORD") // Cert if flagCert != "" { creds.Cert = flagCert - } else if c := os.Getenv(prefix1 + "_CERT"); c != "" { - creds.Cert = c - } else if c := os.Getenv(prefix2 + "_CERT"); c != "" { - creds.Cert = c + } else { + creds.Cert = getEnv("_CERT") + } + if creds.Cert != "" { + if _, err := bigip.ValidateCredentialFilePath(creds.Cert, "Client certificate"); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } } - // Cert Key + // Key if flagKey != "" { creds.Key = flagKey - } else if k := os.Getenv(prefix1 + "_KEY"); k != "" { - creds.Key = k - } else if k := os.Getenv(prefix2 + "_KEY"); k != "" { - creds.Key = k + } else { + creds.Key = getEnv("_KEY") + } + if creds.Key != "" { + if _, err := bigip.ValidateCredentialFilePath(creds.Key, "Client key"); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } } // SSH Identity if flagIdentity != "" { creds.Identity = flagIdentity - } else if i := os.Getenv(prefix1 + "_SSH_KEY"); i != "" { - creds.Identity = i - } else if i := os.Getenv(prefix2 + "_SSH_KEY"); i != "" { + } else if i := getEnv("_SSH_KEY"); i != "" { creds.Identity = i } else if i := os.Getenv("SSH_KEY_PATH"); i != "" { creds.Identity = i } + if creds.Identity != "" { + if _, err := bigip.ValidateCredentialFilePath(creds.Identity, "SSH identity key"); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } + } return creds } @@ -2012,74 +2078,70 @@ func handlePush(ctx context.Context, args []string) { for i := 0; i < len(args); i++ { arg := args[i] - if arg == "--user" || arg == "-u" { - if i+1 < len(args) { - user = args[i+1] - i++ - } + if arg == "--" { + positional = append(positional, args[i+1:]...) + break + } else if arg == "--password" || arg == "--pass" || arg == "-P" || arg == "--token" || arg == "--secret" || arg == "--ssh-passphrase" { + rejectSecretFlag(arg) + } else if arg == "--user" || arg == "-u" { + user = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--user=") { user = strings.TrimPrefix(arg, "--user=") } else if arg == "--port" || arg == "-p" { - if i+1 < len(args) { - if p, err := strconv.Atoi(args[i+1]); err == nil { - port = p - } - i++ + pStr := requireFlagValue(args, i, arg) + p, err := bigip.ValidatePort(pStr) + if err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) } + port = p + i++ } else if strings.HasPrefix(arg, "--port=") { - if p, err := strconv.Atoi(strings.TrimPrefix(arg, "--port=")); err == nil { - port = p + p, err := bigip.ValidatePort(strings.TrimPrefix(arg, "--port=")) + if err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) } + port = p } else if arg == "--method" || arg == "-m" { - if i+1 < len(args) { - method = args[i+1] - i++ - } + method = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--method=") { method = strings.TrimPrefix(arg, "--method=") } else if arg == "--dest" || arg == "-d" { - if i+1 < len(args) { - destPath = args[i+1] - i++ - } + destPath = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--dest=") { destPath = strings.TrimPrefix(arg, "--dest=") } else if arg == "--identity" || arg == "-i" { - if i+1 < len(args) { - keyPath = args[i+1] - i++ - } + keyPath = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--identity=") { keyPath = strings.TrimPrefix(arg, "--identity=") } else if arg == "--target" || arg == "-t" { - if i+1 < len(args) { - targ := args[i+1] - if strings.EqualFold(targ, "bigiq") || strings.EqualFold(targ, "big-iq") { - targetKind = "BIG-IQ" - } else { - targetKind = "BIG-IP" - } - i++ + targ := requireFlagValue(args, i, arg) + if !strings.EqualFold(targ, "bigiq") && !strings.EqualFold(targ, "big-iq") && !strings.EqualFold(targ, "bigip") && !strings.EqualFold(targ, "big-ip") && !strings.EqualFold(targ, "auto") { + fmt.Fprintf(os.Stderr, "[ERROR] Invalid target %q (must be 'bigip', 'bigiq', or 'auto')\n", targ) + exitFunc(1) } + targetKind = targ + i++ } else if strings.HasPrefix(arg, "--target=") { targ := strings.TrimPrefix(arg, "--target=") - if strings.EqualFold(targ, "bigiq") || strings.EqualFold(targ, "big-iq") { - targetKind = "BIG-IQ" - } else { - targetKind = "BIG-IP" + if !strings.EqualFold(targ, "bigiq") && !strings.EqualFold(targ, "big-iq") && !strings.EqualFold(targ, "bigip") && !strings.EqualFold(targ, "big-ip") && !strings.EqualFold(targ, "auto") { + fmt.Fprintf(os.Stderr, "[ERROR] Invalid target %q (must be 'bigip', 'bigiq', or 'auto')\n", targ) + exitFunc(1) } + targetKind = targ } else if arg == "--cert" { - if i+1 < len(args) { - certPath = args[i+1] - i++ - } + certPath = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--cert=") { certPath = strings.TrimPrefix(arg, "--cert=") } else if arg == "--cert-key" || arg == "--key-file" { - if i+1 < len(args) { - certKeyPath = args[i+1] - i++ - } + certKeyPath = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--cert-key=") { certKeyPath = strings.TrimPrefix(arg, "--cert-key=") } else if strings.HasPrefix(arg, "--key-file=") { @@ -2090,7 +2152,10 @@ func handlePush(ctx context.Context, args []string) { keepExtracted = true } else if arg == "--json" { jsonOutput = true - } else if !strings.HasPrefix(arg, "-") { + } else if strings.HasPrefix(arg, "-") { + fmt.Fprintf(os.Stderr, "[ERROR] Unknown flag %q\n", arg) + exitFunc(1) + } else { positional = append(positional, arg) } } @@ -2099,6 +2164,10 @@ func handlePush(ctx context.Context, args []string) { printPushUsage() exitFunc(1) } + if len(positional) > 2 { + fmt.Fprintf(os.Stderr, "[ERROR] Unexpected extra argument(s): %s\n", strings.Join(positional[2:], " ")) + exitFunc(1) + } host := positional[0] localFile := positional[1] @@ -2126,81 +2195,80 @@ func handlePull(ctx context.Context, args []string) { for i := 0; i < len(args); i++ { arg := args[i] - if arg == "--user" || arg == "-u" { - if i+1 < len(args) { - user = args[i+1] - i++ - } + if arg == "--" { + positional = append(positional, args[i+1:]...) + break + } else if arg == "--password" || arg == "--pass" || arg == "-P" || arg == "--token" || arg == "--secret" || arg == "--ssh-passphrase" { + rejectSecretFlag(arg) + } else if arg == "--user" || arg == "-u" { + user = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--user=") { user = strings.TrimPrefix(arg, "--user=") } else if arg == "--port" || arg == "-p" { - if i+1 < len(args) { - if p, err := strconv.Atoi(args[i+1]); err == nil { - port = p - } - i++ + pStr := requireFlagValue(args, i, arg) + p, err := bigip.ValidatePort(pStr) + if err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) } + port = p + i++ } else if strings.HasPrefix(arg, "--port=") { - if p, err := strconv.Atoi(strings.TrimPrefix(arg, "--port=")); err == nil { - port = p + p, err := bigip.ValidatePort(strings.TrimPrefix(arg, "--port=")) + if err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) } + port = p } else if arg == "--method" || arg == "-m" { - if i+1 < len(args) { - method = args[i+1] - i++ - } + method = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--method=") { method = strings.TrimPrefix(arg, "--method=") - } else if arg == "--output" || arg == "-o" || arg == "--dest" || arg == "-d" { - if i+1 < len(args) { - localDest = args[i+1] - i++ - } - } else if strings.HasPrefix(arg, "--output=") { - localDest = strings.TrimPrefix(arg, "--output=") + } else if arg == "--dest" || arg == "-d" || arg == "--output" || arg == "-o" { + localDest = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--dest=") { localDest = strings.TrimPrefix(arg, "--dest=") + } else if strings.HasPrefix(arg, "--output=") { + localDest = strings.TrimPrefix(arg, "--output=") } else if arg == "--identity" || arg == "-i" { - if i+1 < len(args) { - keyPath = args[i+1] - i++ - } + keyPath = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--identity=") { keyPath = strings.TrimPrefix(arg, "--identity=") } else if arg == "--target" || arg == "-t" { - if i+1 < len(args) { - targ := args[i+1] - if strings.EqualFold(targ, "bigiq") || strings.EqualFold(targ, "big-iq") { - targetKind = "BIG-IQ" - } else { - targetKind = "BIG-IP" - } - i++ + targ := requireFlagValue(args, i, arg) + if !strings.EqualFold(targ, "bigiq") && !strings.EqualFold(targ, "big-iq") && !strings.EqualFold(targ, "bigip") && !strings.EqualFold(targ, "big-ip") && !strings.EqualFold(targ, "auto") { + fmt.Fprintf(os.Stderr, "[ERROR] Invalid target %q (must be 'bigip', 'bigiq', or 'auto')\n", targ) + exitFunc(1) } + targetKind = targ + i++ } else if strings.HasPrefix(arg, "--target=") { targ := strings.TrimPrefix(arg, "--target=") - if strings.EqualFold(targ, "bigiq") || strings.EqualFold(targ, "big-iq") { - targetKind = "BIG-IQ" - } else { - targetKind = "BIG-IP" + if !strings.EqualFold(targ, "bigiq") && !strings.EqualFold(targ, "big-iq") && !strings.EqualFold(targ, "bigip") && !strings.EqualFold(targ, "big-ip") && !strings.EqualFold(targ, "auto") { + fmt.Fprintf(os.Stderr, "[ERROR] Invalid target %q (must be 'bigip', 'bigiq', or 'auto')\n", targ) + exitFunc(1) } + targetKind = targ } else if arg == "--cert" { - if i+1 < len(args) { - certPath = args[i+1] - i++ - } + certPath = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--cert=") { certPath = strings.TrimPrefix(arg, "--cert=") } else if arg == "--cert-key" || arg == "--key-file" { - if i+1 < len(args) { - certKeyPath = args[i+1] - i++ - } + certKeyPath = requireFlagValue(args, i, arg) + i++ } else if strings.HasPrefix(arg, "--cert-key=") { certKeyPath = strings.TrimPrefix(arg, "--cert-key=") } else if strings.HasPrefix(arg, "--key-file=") { certKeyPath = strings.TrimPrefix(arg, "--key-file=") - } else if !strings.HasPrefix(arg, "-") { + } else if strings.HasPrefix(arg, "-") { + fmt.Fprintf(os.Stderr, "[ERROR] Unknown flag %q\n", arg) + exitFunc(1) + } else { positional = append(positional, arg) } } @@ -2209,6 +2277,10 @@ func handlePull(ctx context.Context, args []string) { printPullUsage() exitFunc(1) } + if len(positional) > 2 { + fmt.Fprintf(os.Stderr, "[ERROR] Unexpected extra argument(s): %s\n", strings.Join(positional[2:], " ")) + exitFunc(1) + } host := positional[0] remoteFile := positional[1] @@ -2285,59 +2357,57 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { for i := 0; i < len(actionArgs); i++ { arg := actionArgs[i] - if arg == "--user" || arg == "-u" { - if i+1 < len(actionArgs) { - user = actionArgs[i+1] - i++ - } + if arg == "--" { + positional = append(positional, actionArgs[i+1:]...) + break + } else if arg == "--password" || arg == "--pass" || arg == "-P" || arg == "--token" || arg == "--secret" || arg == "--ssh-passphrase" { + rejectSecretFlag(arg) + } else if arg == "--user" || arg == "-u" { + user = requireFlagValue(actionArgs, i, arg) + i++ } else if strings.HasPrefix(arg, "--user=") { user = strings.TrimPrefix(arg, "--user=") } else if arg == "--port" || arg == "-p" { - if i+1 < len(actionArgs) { - if p, err := strconv.Atoi(actionArgs[i+1]); err == nil { - port = p - } - i++ + pStr := requireFlagValue(actionArgs, i, arg) + p, err := bigip.ValidatePort(pStr) + if err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) } + port = p + i++ } else if strings.HasPrefix(arg, "--port=") { - if p, err := strconv.Atoi(strings.TrimPrefix(arg, "--port=")); err == nil { - port = p + p, err := bigip.ValidatePort(strings.TrimPrefix(arg, "--port=")) + if err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) } + port = p } else if arg == "--method" || arg == "-m" { - if i+1 < len(actionArgs) { - method = actionArgs[i+1] - i++ - } + method = requireFlagValue(actionArgs, i, arg) + i++ } else if strings.HasPrefix(arg, "--method=") { method = strings.TrimPrefix(arg, "--method=") } else if arg == "--output" || arg == "-o" || arg == "--dest" || arg == "-d" { - if i+1 < len(actionArgs) { - destPath = actionArgs[i+1] - i++ - } + destPath = requireFlagValue(actionArgs, i, arg) + i++ } else if strings.HasPrefix(arg, "--output=") { destPath = strings.TrimPrefix(arg, "--output=") } else if strings.HasPrefix(arg, "--dest=") { destPath = strings.TrimPrefix(arg, "--dest=") } else if arg == "--identity" || arg == "-i" { - if i+1 < len(actionArgs) { - keyPath = actionArgs[i+1] - i++ - } + keyPath = requireFlagValue(actionArgs, i, arg) + i++ } else if strings.HasPrefix(arg, "--identity=") { keyPath = strings.TrimPrefix(arg, "--identity=") } else if arg == "--cert" { - if i+1 < len(actionArgs) { - certPath = actionArgs[i+1] - i++ - } + certPath = requireFlagValue(actionArgs, i, arg) + i++ } else if strings.HasPrefix(arg, "--cert=") { certPath = strings.TrimPrefix(arg, "--cert=") } else if arg == "--cert-key" || arg == "--key-file" { - if i+1 < len(actionArgs) { - certKeyPath = actionArgs[i+1] - i++ - } + certKeyPath = requireFlagValue(actionArgs, i, arg) + i++ } else if strings.HasPrefix(arg, "--cert-key=") { certKeyPath = strings.TrimPrefix(arg, "--cert-key=") } else if strings.HasPrefix(arg, "--key-file=") { @@ -2350,7 +2420,10 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { keepExtracted = true } else if arg == "--json" { jsonOutput = true - } else if !strings.HasPrefix(arg, "-") { + } else if strings.HasPrefix(arg, "-") { + fmt.Fprintf(os.Stderr, "[ERROR] Unknown flag %q\n", arg) + exitFunc(1) + } else { positional = append(positional, arg) } } @@ -2366,7 +2439,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { switch action { case "ready": - if len(positional) < 1 { + if len(positional) != 1 { fmt.Fprintf(os.Stderr, "Usage: myf5 %s ready [--user ] [--port ] [--cert ] [--cert-key ]\n", cmdName) exitFunc(1) } @@ -2428,7 +2501,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { } case "info", "system-info", "sysinfo": - if len(positional) < 1 { + if len(positional) != 1 { fmt.Fprintf(os.Stderr, "Usage: myf5 %s info [--json] [--method auto|icontrol|ssh] [--user ] [--port ] [-i ] [--cert ] [--cert-key ]\n", cmdName) exitFunc(1) } @@ -2446,7 +2519,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { } case "serial", "sn", "serialnumber": - if len(positional) < 1 { + if len(positional) != 1 { fmt.Fprintf(os.Stderr, "Usage: myf5 %s serial [--json] [--method auto|icontrol|ssh] [--user ] [--port ] [-i ] [--cert ] [--cert-key ]\n", cmdName) exitFunc(1) } @@ -2475,7 +2548,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { } } case "push", "upload": - if len(positional) < 2 { + if len(positional) != 2 { fmt.Fprintf(os.Stderr, "Usage: myf5 %s push [--method auto|icontrol|scp] [--dest ] [--apply-geoip] [--keep-extracted] [--user ] [--port ] [-i ] [--cert ] [--cert-key ] [--json]\n", cmdName) exitFunc(1) } @@ -2485,7 +2558,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { executePushToAppliance(ctx, host, localFile, method, destPath, creds.User, port, creds.Identity, creds.TargetKind, creds.Cert, creds.Key, applyGeoIP, keepExtracted, jsonOutput) case "geoip": - if len(positional) < 2 { + if len(positional) != 2 { fmt.Fprintf(os.Stderr, "Usage: myf5 %s geoip [--method auto|icontrol|scp] [--dest ] [--keep-extracted] [--user ] [--port ] [-i ] [--cert ] [--cert-key ] [--json]\n", cmdName) exitFunc(1) } @@ -2595,7 +2668,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { } case "download", "pull", "fetch": - if len(positional) < 2 { + if len(positional) != 2 { fmt.Fprintf(os.Stderr, "Usage: myf5 %s download [-o ] [--method auto|icontrol|scp] [--user ] [--port ] [-i ] [--cert ] [--cert-key ]\n", cmdName) exitFunc(1) } @@ -2605,7 +2678,7 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { executeDownloadFromAppliance(ctx, host, remoteFile, destPath, method, creds.User, port, creds.Identity, creds.TargetKind, creds.Cert, creds.Key) case "qkview": - if len(positional) < 1 { + if len(positional) != 1 { fmt.Fprintf(os.Stderr, "Usage: myf5 %s qkview [--method auto|icontrol|scp] [--dest ] [--user ] [--port ] [-i ] [--cert ] [--cert-key ] [--keep-remote]\n", cmdName) exitFunc(1) } diff --git a/cmd/myf5/main_test.go b/cmd/myf5/main_test.go index 6c47286..22ae490 100644 --- a/cmd/myf5/main_test.go +++ b/cmd/myf5/main_test.go @@ -249,3 +249,36 @@ func TestCaseCreate_LifecycleWarnings(t *testing.T) { t.Errorf("expected no Hardware Rec in stderr, got: %q", errOutput) } } + +func TestResolveApplianceCreds_HostBinding(t *testing.T) { + // Setup env + os.Setenv("BIGIP_HOST", "10.0.0.1") + os.Setenv("BIGIP_PASSWORD", "secret1") + os.Setenv("BIGIQ_HOST", "10.0.0.2") + os.Setenv("BIGIQ_PASSWORD", "secret2") + + defer func() { + os.Unsetenv("BIGIP_HOST") + os.Unsetenv("BIGIP_PASSWORD") + os.Unsetenv("BIGIQ_HOST") + os.Unsetenv("BIGIQ_PASSWORD") + }() + + // 1. Target exactly matches BIGIP_HOST + creds1 := resolveApplianceCreds("10.0.0.1", "BIG-IP", "", "", "", "", false) + if creds1.Password != "secret1" { + t.Errorf("expected secret1 for 10.0.0.1, got %q", creds1.Password) + } + + // 2. Target exactly matches BIGIQ_HOST + creds2 := resolveApplianceCreds("10.0.0.2", "BIG-IQ", "", "", "", "", false) + if creds2.Password != "secret2" { + t.Errorf("expected secret2 for 10.0.0.2, got %q", creds2.Password) + } + + // 3. Unrelated host should NOT get leaked passwords + creds3 := resolveApplianceCreds("1.2.3.4", "BIG-IP", "", "", "", "", false) + if creds3.Password != "" { + t.Errorf("expected NO password for unrelated host 1.2.3.4, got leaked password %q", creds3.Password) + } +} diff --git a/pkg/bigip/client.go b/pkg/bigip/client.go index cb9a324..0e6d5c9 100644 --- a/pkg/bigip/client.go +++ b/pkg/bigip/client.go @@ -11,6 +11,7 @@ import ( "net" "net/http" "net/netip" + "net/url" "os" "path" "path/filepath" @@ -148,6 +149,18 @@ func validateHostname(h string) error { // ParseAndValidateApplianceHost extracts scheme, normalized host, and port, validating the host. func ParseAndValidateApplianceHost(rawHost string, defaultPort int) (scheme, cleanHost string, port int, isIPv6 bool, err error) { + if strings.Contains(rawHost, "://") { + u, err := url.Parse(rawHost) + if err == nil { + if u.User != nil { + return "", "", 0, false, fmt.Errorf("embedded credentials in host URL %q are prohibited", rawHost) + } + if u.RawQuery != "" || u.Fragment != "" { + return "", "", 0, false, fmt.Errorf("query parameters or fragments in host URL %q are prohibited", rawHost) + } + } + } + scheme = "https" s := strings.TrimSpace(rawHost) if strings.HasPrefix(s, "http://") { @@ -212,6 +225,25 @@ type ClientOptions struct { // NewClientWithOptions initializes a BIG-IP appliance client with validation and optional mTLS client certificates. func NewClientWithOptions(opts ClientOptions) (*Client, error) { + if opts.Username != "" { + if err := ValidateApplianceUsername(opts.Username); err != nil { + return nil, err + } + } + if opts.Port < 0 || opts.Port > 65535 { + return nil, fmt.Errorf("invalid port %d: must be between 1 and 65535", opts.Port) + } + if opts.ClientCertPath != "" { + if _, err := ValidateCredentialFilePath(opts.ClientCertPath, "Client certificate"); err != nil { + return nil, err + } + } + if opts.ClientKeyPath != "" { + if _, err := ValidateCredentialFilePath(opts.ClientKeyPath, "Client key"); err != nil { + return nil, err + } + } + scheme, cleanHost, port, _, err := ParseAndValidateApplianceHost(opts.Host, opts.Port) if err != nil { return nil, err @@ -622,7 +654,10 @@ func (c *Client) GenerateQKViewWithStatus(ctx context.Context, filename string, if res.resp.StatusCode == http.StatusNotFound { // Fallback to bash for BIG-IQ where /mgmt/tm/util/qkview may return 404 - bashArgs := fmt.Sprintf("-c \"mkdir -p /var/tmp/qkviews && /usr/bin/qkview %s-f /var/tmp/qkviews/%s && cp /var/tmp/qkviews/%s /var/config/rest/downloads/\"", map[bool]string{true: "-s0 ", false: ""}[complete], filename, filename) + if err := ValidateQKViewFilename(filename); err != nil { + return "", err + } + bashArgs := fmt.Sprintf("-c \"mkdir -p /var/tmp/qkviews && /usr/bin/qkview %s-f /var/tmp/qkviews/'%s' && cp /var/tmp/qkviews/'%s' /var/config/rest/downloads/\"", map[bool]string{true: "-s0 ", false: ""}[complete], filename, filename) bashPayload := map[string]string{ "command": "run", "utilCmdArgs": bashArgs, @@ -640,9 +675,12 @@ func (c *Client) GenerateQKViewWithStatus(ctx context.Context, filename string, return "", fmt.Errorf("bash fallback for qkview failed: %w", err) } defer bashResp.Body.Close() + bashBody, _ := io.ReadAll(io.LimitReader(bashResp.Body, 1024*1024)) if bashResp.StatusCode < 200 || bashResp.StatusCode >= 300 { - b, _ := io.ReadAll(io.LimitReader(bashResp.Body, 1024*1024)) - return "", fmt.Errorf("bash qkview generation failed with HTTP %d: %s", bashResp.StatusCode, string(b)) + return "", fmt.Errorf("bash qkview generation failed with HTTP %d: %s", bashResp.StatusCode, string(bashBody)) + } + if strings.Contains(string(bashBody), "command not found") || strings.Contains(string(bashBody), "syntax error") { + return "", fmt.Errorf("bash qkview generation command failed: %s", string(bashBody)) } return filename, nil } @@ -896,3 +934,64 @@ func (c *Client) setAuth(req *http.Request) { req.Header.Set("Authorization", "Basic "+authHeader) req.Header.Set("User-Agent", "myf5-cli-go/1.0.0") } + +var validUsernameRegex = regexp.MustCompile(`^[a-zA-Z0-9_][a-zA-Z0-9_.\-@]*$`) + +// ValidateApplianceUsername validates a username for BIG-IP / BIG-IQ appliance access. +func ValidateApplianceUsername(username string) error { + if username == "" { + return fmt.Errorf("username cannot be empty") + } + if len(username) > 64 { + return fmt.Errorf("username exceeds maximum length of 64 characters") + } + if strings.Contains(username, ":") { + return fmt.Errorf("username cannot contain a colon") + } + for _, r := range username { + if r < 32 || r == 127 || r == ' ' || r == '\t' || r == '\n' || r == '\r' { + return fmt.Errorf("username cannot contain control characters or whitespace") + } + } + if !validUsernameRegex.MatchString(username) { + return fmt.Errorf("username contains invalid characters") + } + return nil +} + +// ValidatePort validates a port string and returns the integer value. +func ValidatePort(rawPort string) (int, error) { + portStr := strings.TrimSpace(rawPort) + port, err := strconv.Atoi(portStr) + if err != nil { + return 0, fmt.Errorf("invalid port %q: must be a numeric value", rawPort) + } + if port < 1 || port > 65535 { + return 0, fmt.Errorf("invalid port %d: must be between 1 and 65535", port) + } + return port, nil +} + +// ValidateCredentialFilePath validates a file path used for credentials (keys/certs). +func ValidateCredentialFilePath(filePath, label string) (string, error) { + for _, r := range filePath { + if r < 32 || r == 127 { + return "", fmt.Errorf("%s path cannot contain control characters", label) + } + } + cleanPath := filepath.Clean(strings.TrimSpace(filePath)) + fi, err := os.Stat(cleanPath) + if err != nil { + return "", fmt.Errorf("failed to access %s file %s: %w", label, cleanPath, err) + } + if !fi.Mode().IsRegular() { + return "", fmt.Errorf("%s must be a regular file: %s", label, cleanPath) + } + if fi.Size() == 0 { + return "", fmt.Errorf("%s file is empty: %s", label, cleanPath) + } + if fi.Size() > 1024*1024 { + return "", fmt.Errorf("%s file exceeds maximum allowed size of 1MB: %s", label, cleanPath) + } + return cleanPath, nil +} diff --git a/pkg/bigip/client_test.go b/pkg/bigip/client_test.go index 43741fc..db35977 100644 --- a/pkg/bigip/client_test.go +++ b/pkg/bigip/client_test.go @@ -631,3 +631,96 @@ func TestTransferOptionsZero(t *testing.T) { var nilOpts *TransferOptions nilOpts.Zero() // Must not panic } + +func TestValidateApplianceUsername(t *testing.T) { + tests := []struct { + name string + username string + wantErr bool + }{ + {"valid", "admin", false}, + {"valid email", "user@domain.com", false}, + {"colon injection", "admin:pass", true}, + {"spaces", "admin user", true}, + {"shell meta", "admin;ls", true}, + {"ANSI escapes", "admin\033[0m", true}, + {"empty", "", true}, + {"too long", "a" + string(make([]byte, 64)), true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := ValidateApplianceUsername(tt.username) + if (err != nil) != tt.wantErr { + t.Errorf("ValidateApplianceUsername() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestValidatePort(t *testing.T) { + tests := []struct { + port string + wantErr bool + }{ + {"22", false}, + {"443", false}, + {"8443", false}, + {"0", true}, + {"-1", true}, + {"65536", true}, + {"abc", true}, + } + + for _, tt := range tests { + t.Run(tt.port, func(t *testing.T) { + _, err := ValidatePort(tt.port) + if (err != nil) != tt.wantErr { + t.Errorf("ValidatePort() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestValidateCredentialFilePath(t *testing.T) { + tmpDir := t.TempDir() + + validFile := filepath.Join(tmpDir, "valid.key") + os.WriteFile(validFile, []byte("key content"), 0600) + + emptyFile := filepath.Join(tmpDir, "empty.key") + os.WriteFile(emptyFile, []byte(""), 0600) + + largeFile := filepath.Join(tmpDir, "large.key") + largeData := make([]byte, 1024*1024+1) + os.WriteFile(largeFile, largeData, 0600) + + tests := []struct { + name string + path string + wantErr bool + }{ + {"valid", validFile, false}, + {"nonexistent", filepath.Join(tmpDir, "missing.key"), true}, + {"directory", tmpDir, true}, + {"empty file", emptyFile, true}, + {"large file", largeFile, true}, + {"null byte", filepath.Join(tmpDir, "file\x00.key"), true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := ValidateCredentialFilePath(tt.path, "test") + if (err != nil) != tt.wantErr { + t.Errorf("ValidateCredentialFilePath() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestParseAndValidateApplianceHost_EmbeddedCreds(t *testing.T) { + _, _, _, _, err := ParseAndValidateApplianceHost("https://admin:secret@10.1.1.4", 443) + if err == nil { + t.Errorf("ParseAndValidateApplianceHost() expected error for embedded credentials") + } +} diff --git a/pkg/bigip/scp.go b/pkg/bigip/scp.go index eeae82b..37f68bc 100644 --- a/pkg/bigip/scp.go +++ b/pkg/bigip/scp.go @@ -91,6 +91,14 @@ func BuildSSHClientConfig(opts SCPOptions) (*ssh.ClientConfig, error) { if username == "" { username = "admin" } + if err := ValidateApplianceUsername(username); err != nil { + return nil, err + } + if opts.KeyPath != "" { + if _, err := ValidateCredentialFilePath(opts.KeyPath, "SSH identity key"); err != nil { + return nil, err + } + } var authMethods []ssh.AuthMethod From 036bd13467e054817f518c2e2385e09b0ba6e03a Mon Sep 17 00:00:00 2001 From: Greg Robinson Date: Sat, 7 Nov 2026 01:54:55 -0500 Subject: [PATCH 4/9] sec(bigip): enforce F5 K2873 password character validation and document shell quoting --- cmd/myf5/main.go | 54 +++++++++++++++++--- docs/credentials.md | 5 ++ pkg/bigip/client.go | 37 ++++++++++++++ pkg/bigip/client_test.go | 107 +++++++++++++++++++++++++++++++++++++++ pkg/bigip/scp.go | 3 ++ 5 files changed, 200 insertions(+), 6 deletions(-) diff --git a/cmd/myf5/main.go b/cmd/myf5/main.go index df41df3..8079c0b 100644 --- a/cmd/myf5/main.go +++ b/cmd/myf5/main.go @@ -2001,6 +2001,12 @@ func resolveApplianceCreds(host, targetKind, flagUser, flagCert, flagKey, flagId // Password creds.Password = getEnv("_PASSWORD") + if creds.Password != "" { + if err := bigip.ValidateAppliancePassword(creds.Password); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\nHint: When exporting passwords containing special characters (such as !, $, `, \\, or \") in your shell, wrap the value in single quotes: export BIGIP_PASSWORD='...'\n", err) + exitFunc(1) + } + } // Cert if flagCert != "" { @@ -2454,9 +2460,15 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { - pw = strings.TrimSpace(string(bytePw)) + pw = strings.TrimRight(string(bytePw), "\r\n") // Zero raw password byte buffer immediately to scrub cleartext secret from memory auth.ZeroBytes(bytePw) + if pw != "" { + if err := bigip.ValidateAppliancePassword(pw); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } + } } } if pw == "" && creds.Cert == "" { @@ -2599,8 +2611,14 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { - pw = strings.TrimSpace(string(bytePw)) + pw = strings.TrimRight(string(bytePw), "\r\n") auth.ZeroBytes(bytePw) + if pw != "" { + if err := bigip.ValidateAppliancePassword(pw); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } + } } } } @@ -2695,9 +2713,15 @@ func handleAppliance(ctx context.Context, targetKind string, args []string) { bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { - pw = strings.TrimSpace(string(bytePw)) + pw = strings.TrimRight(string(bytePw), "\r\n") // Zero raw password byte buffer immediately to scrub cleartext secret from memory auth.ZeroBytes(bytePw) + if pw != "" { + if err := bigip.ValidateAppliancePassword(pw); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } + } } } } @@ -2855,8 +2879,14 @@ func getSystemInfoTarget(ctx context.Context, target, targetKind, user string, p bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { - pw = strings.TrimSpace(string(bytePw)) + pw = strings.TrimRight(string(bytePw), "\r\n") auth.ZeroBytes(bytePw) + if pw != "" { + if err := bigip.ValidateAppliancePassword(pw); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } + } } } } @@ -2999,9 +3029,15 @@ func executePushToAppliance( bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { - pw = strings.TrimSpace(string(bytePw)) + pw = strings.TrimRight(string(bytePw), "\r\n") // Zero raw password byte buffer immediately to scrub cleartext secret from memory auth.ZeroBytes(bytePw) + if pw != "" { + if err := bigip.ValidateAppliancePassword(pw); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } + } } } } @@ -3221,9 +3257,15 @@ func executeDownloadFromAppliance( bytePw, err := term.ReadPassword(int(os.Stdin.Fd())) fmt.Println() if err == nil { - pw = strings.TrimSpace(string(bytePw)) + pw = strings.TrimRight(string(bytePw), "\r\n") // Zero raw password byte buffer immediately to scrub cleartext secret from memory auth.ZeroBytes(bytePw) + if pw != "" { + if err := bigip.ValidateAppliancePassword(pw); err != nil { + fmt.Fprintf(os.Stderr, "[ERROR] %v\n", err) + exitFunc(1) + } + } } } } diff --git a/docs/credentials.md b/docs/credentials.md index d10f07d..9bdd5f4 100644 --- a/docs/credentials.md +++ b/docs/credentials.md @@ -182,6 +182,11 @@ When managing BIG-IP TMOS or BIG-IQ Centralized Management appliances via `myf5 Enter BIG-IP password for admin@10.1.1.4: ``` In non-interactive environments (cron, headless CI/CD), if the password is not provided via environment variables or SSH keys, `myf5` halts execution with exit code `1` rather than hanging. + - **F5 K2873 Character Policy & Shell Quoting**: + Appliance passwords follow the **F5 K2873** specification: alphanumeric characters and all 32 allowed special characters (`!`, `@`, `#`, `$`, `%`, `^`, `&`, `*`, `(`, `)`, `` ` ``, `~`, `-`, `+`, `=`, `[`, `]`, `{`, `}`, `;`, `’`, `:`, `"`, `'`, `.`, `/`, `<`, `>`, `|`, `\`, `?`, `_`) are supported. Whitespace and control characters are prohibited. When exporting passwords containing shell-active special characters (such as `!`, `$`, `` ` ``, `\`, or `"`) in `bash` or `zsh`, wrap the value in **single quotes** to prevent shell expansion: + ```bash + export BIGIP_PASSWORD='MyP@ssw0rd!$`123' + ``` - **SSH Key & Agent Authentication (SCP Method)**: When using native Go SCP transfers (`--method scp` or `--push-method scp`): diff --git a/pkg/bigip/client.go b/pkg/bigip/client.go index 0e6d5c9..5e809ba 100644 --- a/pkg/bigip/client.go +++ b/pkg/bigip/client.go @@ -230,6 +230,15 @@ func NewClientWithOptions(opts ClientOptions) (*Client, error) { return nil, err } } + if opts.Password != "" { + if err := ValidateAppliancePassword(opts.Password); err != nil { + return nil, err + } + } else if len(opts.PasswordBytes) > 0 { + if err := ValidateAppliancePassword(string(opts.PasswordBytes)); err != nil { + return nil, err + } + } if opts.Port < 0 || opts.Port > 65535 { return nil, fmt.Errorf("invalid port %d: must be between 1 and 65535", opts.Port) } @@ -959,6 +968,34 @@ func ValidateApplianceUsername(username string) error { return nil } +// K2873SpecialCharacters contains the 32 allowed special characters defined in F5 K2873. +const K2873SpecialCharacters = "!@#$%^&*()`~-+=[]{};’:\"'./<>|\\?_" + +// ValidateAppliancePassword validates an appliance password against F5 K2873 policy. +// It allows alphanumeric characters and the 32 special characters specified in K2873. +// To prevent secret disclosure in logs or stderr, error messages never include the password or rejected character. +func ValidateAppliancePassword(password string) error { + if password == "" { + return fmt.Errorf("appliance password cannot be empty") + } + if len(password) > 255 { + return fmt.Errorf("appliance password exceeds maximum length of 255 characters") + } + for i, r := range password { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || strings.ContainsRune(K2873SpecialCharacters, r) { + continue + } + if r == ' ' || r == '\t' || r == '\n' || r == '\r' { + return fmt.Errorf("invalid appliance password: whitespace is not permitted (refer to F5 K2873 for allowed password characters)") + } + if r < 32 || r == 127 { + return fmt.Errorf("invalid appliance password: control characters are not permitted (refer to F5 K2873)") + } + return fmt.Errorf("invalid appliance password: contains unsupported character at byte offset %d (refer to F5 K2873 for allowed special characters)", i) + } + return nil +} + // ValidatePort validates a port string and returns the integer value. func ValidatePort(rawPort string) (int, error) { portStr := strings.TrimSpace(rawPort) diff --git a/pkg/bigip/client_test.go b/pkg/bigip/client_test.go index db35977..18a3e89 100644 --- a/pkg/bigip/client_test.go +++ b/pkg/bigip/client_test.go @@ -2,6 +2,7 @@ package bigip import ( "context" + "encoding/base64" "fmt" "net/http" "net/http/httptest" @@ -724,3 +725,109 @@ func TestParseAndValidateApplianceHost_EmbeddedCreds(t *testing.T) { t.Errorf("ParseAndValidateApplianceHost() expected error for embedded credentials") } } + +func TestValidateAppliancePassword_K2873(t *testing.T) { + // 32 K2873 special characters: + // ! @ # $ % ^ & * ( ) ` ~ - + = [ ] { } ; ’ : " ' . / < > | \ ? _ + allSpecialCharsPw := "Abc123!@#$%^&*()`~-+=[]{};’:\"'./<>|\\?_" + + if err := ValidateAppliancePassword(allSpecialCharsPw); err != nil { + t.Fatalf("ValidateAppliancePassword failed on valid K2873 password: %v", err) + } + + // Verify Basic Auth serialization & deserialization with all 32 K2873 characters + c := &Client{ + Username: "admin", + Password: allSpecialCharsPw, + } + req, err := http.NewRequest(http.MethodGet, "https://10.1.1.4/mgmt/tm/sys/ready", nil) + if err != nil { + t.Fatalf("http.NewRequest failed: %v", err) + } + c.setAuth(req) + + authHdr := req.Header.Get("Authorization") + if !strings.HasPrefix(authHdr, "Basic ") { + t.Fatalf("expected Basic auth header, got %q", authHdr) + } + rawEncoded := strings.TrimPrefix(authHdr, "Basic ") + decodedBytes, err := base64.StdEncoding.DecodeString(rawEncoded) + if err != nil { + t.Fatalf("failed to decode base64 auth header: %v", err) + } + expectedAuth := "admin:" + allSpecialCharsPw + if string(decodedBytes) != expectedAuth { + t.Fatalf("decoded auth mismatch:\n got: %q\n want: %q", string(decodedBytes), expectedAuth) + } + + // Verify also with PasswordBytes + cBytes := &Client{ + Username: "admin", + PasswordBytes: []byte(allSpecialCharsPw), + } + req2, err := http.NewRequest(http.MethodGet, "https://10.1.1.4/mgmt/tm/sys/ready", nil) + if err != nil { + t.Fatalf("http.NewRequest failed: %v", err) + } + cBytes.setAuth(req2) + authHdr2 := req2.Header.Get("Authorization") + decodedBytes2, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHdr2, "Basic ")) + if err != nil { + t.Fatalf("failed to decode base64 auth header with PasswordBytes: %v", err) + } + if string(decodedBytes2) != expectedAuth { + t.Fatalf("decoded auth with PasswordBytes mismatch:\n got: %q\n want: %q", string(decodedBytes2), expectedAuth) + } + + // Verify NewClientWithOptions enforces password validation + _, err = NewClientWithOptions(ClientOptions{ + Host: "10.1.1.4", + Username: "admin", + Password: "invalid,password", + }) + if err == nil { + t.Fatalf("expected NewClientWithOptions to reject password with comma") + } + + _, err = NewClientWithOptions(ClientOptions{ + Host: "10.1.1.4", + Username: "admin", + PasswordBytes: []byte("invalid,password"), + }) + if err == nil { + t.Fatalf("expected NewClientWithOptions to reject passwordBytes with comma") + } + + // Verify rejected passwords and ensure no secret leakage in error messages + tooLongPw := strings.Repeat("a", 256) + invalidTestCases := []struct { + name string + pw string + }{ + {"empty", ""}, + {"too long", tooLongPw}, + {"space", "abc def"}, + {"leading space", " abc"}, + {"trailing space", "abc "}, + {"tab", "abc\tdef"}, + {"newline", "abc\ndef"}, + {"carriage return", "abc\rdef"}, + {"null control char", "abc\x00def"}, + {"del control char", "abc\x7fdef"}, + {"comma", "abc,def"}, + {"unsupported unicode", "abc\u00a9def"}, + } + + for _, tc := range invalidTestCases { + t.Run(tc.name, func(t *testing.T) { + err := ValidateAppliancePassword(tc.pw) + if err == nil { + t.Fatalf("expected error for invalid password %q, got nil", tc.name) + } + // CRITICAL: verify password or substring "abc" is never leaked in error + if tc.pw != "" && strings.Contains(err.Error(), "abc") { + t.Errorf("secret leaked in error message for case %q: %v", tc.name, err) + } + }) + } +} diff --git a/pkg/bigip/scp.go b/pkg/bigip/scp.go index 37f68bc..eb12e9f 100644 --- a/pkg/bigip/scp.go +++ b/pkg/bigip/scp.go @@ -108,6 +108,9 @@ func BuildSSHClientConfig(opts SCPOptions) (*ssh.ClientConfig, error) { pw = string(opts.PasswordBytes) } if pw != "" { + if err := ValidateAppliancePassword(pw); err != nil { + return nil, err + } authMethods = append(authMethods, ssh.Password(pw)) // Also support keyboard-interactive (PAM / TACACS+ / RADIUS) authMethods = append(authMethods, ssh.KeyboardInteractive( From 17131fc39d560cc2fa79ef74ded9f573d9169cd7 Mon Sep 17 00:00:00 2001 From: Greg Robinson Date: Sat, 7 Nov 2026 02:07:57 -0500 Subject: [PATCH 5/9] sec: remediate CWE-78, CWE-409, CWE-200, CWE-400, and CWE-732 audit findings --- pkg/bigip/client.go | 6 ++-- pkg/bigip/client_test.go | 8 +++++ pkg/bigip/geoip.go | 6 ++-- pkg/bigip/geoip_test.go | 10 ++++-- pkg/bigip/info.go | 28 ++++++++++----- pkg/bigip/info_test.go | 33 +++++++++++++++++ pkg/client/tls.go | 39 ++++++++++++++++++--- pkg/client/tls_test.go | 76 ++++++++++++++++++++++++++++++++++++++++ pkg/ihealth/models.go | 3 +- 9 files changed, 189 insertions(+), 20 deletions(-) diff --git a/pkg/bigip/client.go b/pkg/bigip/client.go index 5e809ba..698ff64 100644 --- a/pkg/bigip/client.go +++ b/pkg/bigip/client.go @@ -495,7 +495,7 @@ func (c *Client) CreateQKViewTaskWithOptions(ctx context.Context, filename strin } var task QKViewTask - if err := json.NewDecoder(resp.Body).Decode(&task); err != nil { + if err := json.NewDecoder(io.LimitReader(resp.Body, 1024*1024)).Decode(&task); err != nil { return nil, fmt.Errorf("failed to decode qkview task response: %w", err) } return &task, nil @@ -522,7 +522,7 @@ func (c *Client) QueryQKViewTask(ctx context.Context, taskID string) (*QKViewTas } var task QKViewTask - if err := json.NewDecoder(resp.Body).Decode(&task); err != nil { + if err := json.NewDecoder(io.LimitReader(resp.Body, 1024*1024)).Decode(&task); err != nil { return nil, fmt.Errorf("failed to decode qkview task query: %w", err) } return &task, nil @@ -720,7 +720,7 @@ func (c *Client) DownloadFromURI(ctx context.Context, endpointURI, localPath str } partPath := localPath + ".part" - out, err := os.Create(partPath) + out, err := os.OpenFile(partPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("failed to create local file: %w", err) } diff --git a/pkg/bigip/client_test.go b/pkg/bigip/client_test.go index 18a3e89..14d2991 100644 --- a/pkg/bigip/client_test.go +++ b/pkg/bigip/client_test.go @@ -169,6 +169,14 @@ func TestDownloadFromURI(t *testing.T) { if !progressCalled { t.Errorf("expected progress callback to be called") } + + info, err := os.Stat(destFile) + if err != nil { + t.Fatalf("failed to stat destFile: %v", err) + } + if info.Mode().Perm() != 0600 { + t.Errorf("expected file mode 0600, got %04o", info.Mode().Perm()) + } } func TestDeleteQKView(t *testing.T) { diff --git a/pkg/bigip/geoip.go b/pkg/bigip/geoip.go index 797c0a0..fc34b06 100644 --- a/pkg/bigip/geoip.go +++ b/pkg/bigip/geoip.go @@ -250,6 +250,8 @@ func generateGeoIPScript(remoteZipPath string, force, keepExtracted bool) string extractCmd = `tar -xzf "$ZIP_FILE" -C "$EXTRACT_DIR"` } + safeZipPath := strings.ReplaceAll(remoteZipPath, "'", `'\''`) + return fmt.Sprintf(`( set -o pipefail @@ -258,7 +260,7 @@ if grep -qi '^Product:[[:space:]]*BIG-IQ' /VERSION 2>/dev/null; then exit 8 fi -ZIP_FILE=%q +ZIP_FILE='%s' if [ ! -f "$ZIP_FILE" ]; then echo "ERROR: GeoIP archive file not found: $ZIP_FILE" >&2 @@ -335,7 +337,7 @@ echo "--- GEOIP_COMPLETE ---" SCRIPT_EXIT_CODE=$? echo "--- SCRIPT_EXIT_CODE: $SCRIPT_EXIT_CODE ---" exit $SCRIPT_EXIT_CODE -`, remoteZipPath, cleanupAction, extractCmd, forceFlag) +`, safeZipPath, cleanupAction, extractCmd, forceFlag) } func applyGeoIPSSH(ctx context.Context, host, scriptB64 string, opts GeoIPOptions) (string, error) { diff --git a/pkg/bigip/geoip_test.go b/pkg/bigip/geoip_test.go index c231bfd..668c43a 100644 --- a/pkg/bigip/geoip_test.go +++ b/pkg/bigip/geoip_test.go @@ -47,8 +47,8 @@ func TestApplyGeoIPPathValidation(t *testing.T) { func TestGenerateGeoIPScript(t *testing.T) { script := generateGeoIPScript("/var/tmp/geoip.zip", true, false) - if !strings.Contains(script, `ZIP_FILE="/var/tmp/geoip.zip"`) { - t.Errorf("expected script to contain zip file path, got:\n%s", script) + if !strings.Contains(script, `ZIP_FILE='/var/tmp/geoip.zip'`) { + t.Errorf("expected script to contain single-quoted zip file path, got:\n%s", script) } if !strings.Contains(script, `rm -rf "$EXTRACT_DIR"`) { t.Errorf("expected script to clean up extract dir when keepExtracted is false") @@ -57,6 +57,12 @@ func TestGenerateGeoIPScript(t *testing.T) { t.Errorf("expected script to pass -f when force is true") } + // Test single-quote escaping defense-in-depth + scriptEscaped := generateGeoIPScript("/var/tmp/inject'test$(whoami).zip", true, false) + if !strings.Contains(scriptEscaped, `ZIP_FILE='/var/tmp/inject'\''test$(whoami).zip'`) { + t.Errorf("expected script to properly escape single quotes, got:\n%s", scriptEscaped) + } + scriptKeep := generateGeoIPScript("/var/tmp/geoip.tgz", false, true) if !strings.Contains(scriptKeep, "Extracted files preserved") { t.Errorf("expected script to preserve extract dir when keepExtracted is true") diff --git a/pkg/bigip/info.go b/pkg/bigip/info.go index 857f1b1..5e4ea7a 100644 --- a/pkg/bigip/info.go +++ b/pkg/bigip/info.go @@ -275,6 +275,14 @@ func InspectQKViewReader(r io.Reader) (*SystemInfo, error) { licenseFileSerialRe := regexp.MustCompile(`(?i)Serial Number\s*:\s*([A-Za-z0-9-]+)`) hostnameRe := regexp.MustCompile(`(?m)^\s*hostname\s+([^\s;]+)`) + const maxTarEntries = 50000 + var tarEntries int + newLimitedScanner := func(r io.Reader) *bufio.Scanner { + s := bufio.NewScanner(io.LimitReader(r, 10*1024*1024)) + s.Buffer(make([]byte, 0, 64*1024), 1024*1024) + return s + } + for { hdr, err := tr.Next() if err == io.EOF { @@ -283,11 +291,15 @@ func InspectQKViewReader(r io.Reader) (*SystemInfo, error) { if err != nil { return nil, fmt.Errorf("tar read error: %w", err) } + tarEntries++ + if tarEntries > maxTarEntries { + return nil, fmt.Errorf("qkview archive exceeds maximum allowed tar entries (%d)", maxTarEntries) + } name := strings.TrimPrefix(hdr.Name, "./") switch { case name == "VERSION.LTM" || name == "VERSION": - scanner := bufio.NewScanner(tr) + scanner := newLimitedScanner(tr) for scanner.Scan() { line := scanner.Text() parts := strings.SplitN(line, ":", 2) @@ -310,7 +322,7 @@ func InspectQKViewReader(r io.Reader) (*SystemInfo, error) { } case name == "PLATFORM": - scanner := bufio.NewScanner(tr) + scanner := newLimitedScanner(tr) for scanner.Scan() { line := scanner.Text() parts := strings.SplitN(line, "=", 2) @@ -320,7 +332,7 @@ func InspectQKViewReader(r io.Reader) (*SystemInfo, error) { } case name == "HWINFO": - scanner := bufio.NewScanner(tr) + scanner := newLimitedScanner(tr) for scanner.Scan() { line := scanner.Text() parts := strings.SplitN(line, "=", 2) @@ -330,7 +342,7 @@ func InspectQKViewReader(r io.Reader) (*SystemInfo, error) { } case strings.HasSuffix(name, "config/bigip.license"): - scanner := bufio.NewScanner(tr) + scanner := newLimitedScanner(tr) for scanner.Scan() { line := scanner.Text() if m := licenseFileRegKeyRe.FindStringSubmatch(line); len(m) > 1 && info.RegistrationKey == "" { @@ -342,7 +354,7 @@ func InspectQKViewReader(r io.Reader) (*SystemInfo, error) { } case strings.HasSuffix(name, "config/bigip_base.conf"): - scanner := bufio.NewScanner(tr) + scanner := newLimitedScanner(tr) for scanner.Scan() { line := scanner.Text() if m := hostnameRe.FindStringSubmatch(line); len(m) > 1 && info.Hostname == "" { @@ -351,7 +363,7 @@ func InspectQKViewReader(r io.Reader) (*SystemInfo, error) { } case strings.HasSuffix(name, "var/prompt/hostname"): - scanner := bufio.NewScanner(tr) + scanner := newLimitedScanner(tr) if scanner.Scan() { val := strings.TrimSpace(scanner.Text()) if val != "" && info.Hostname == "" { @@ -360,7 +372,7 @@ func InspectQKViewReader(r io.Reader) (*SystemInfo, error) { } case strings.HasSuffix(name, "bigip_sys.conf"): - scanner := bufio.NewScanner(tr) + scanner := newLimitedScanner(tr) curMod := "" provisionRe := regexp.MustCompile(`(?i)(?:sys\s+)?provision\s+([a-zA-Z0-9_-]+)\s*\{`) levelRe := regexp.MustCompile(`(?i)level\s+([a-zA-Z0-9_-]+)`) @@ -384,7 +396,7 @@ func InspectQKViewReader(r io.Reader) (*SystemInfo, error) { } case name == "mcp_module.xml": - scanner := bufio.NewScanner(tr) + scanner := newLimitedScanner(tr) inSysInfo := false isHostnameVar := false curMod := "" diff --git a/pkg/bigip/info_test.go b/pkg/bigip/info_test.go index 5450724..9b6304d 100644 --- a/pkg/bigip/info_test.go +++ b/pkg/bigip/info_test.go @@ -6,6 +6,7 @@ import ( "compress/gzip" "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "os" @@ -138,6 +139,38 @@ Version: 16.1.4`, } } +func TestInspectQKViewReader_TarBombEntryLimit(t *testing.T) { + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + + for i := 0; i < 50005; i++ { + hdr := &tar.Header{ + Name: fmt.Sprintf("dummy_%d.txt", i), + Mode: 0600, + Size: 0, + } + if err := tw.WriteHeader(hdr); err != nil { + t.Fatalf("WriteHeader failed: %v", err) + } + } + + if err := tw.Close(); err != nil { + t.Fatalf("Close tar failed: %v", err) + } + if err := gz.Close(); err != nil { + t.Fatalf("Close gzip failed: %v", err) + } + + _, err := InspectQKViewReader(bytes.NewReader(buf.Bytes())) + if err == nil { + t.Fatalf("expected error exceeding max tar entries, got nil") + } + if !strings.Contains(err.Error(), "exceeds maximum allowed tar entries") { + t.Errorf("expected error to mention 'exceeds maximum allowed tar entries', got: %v", err) + } +} + func TestInspectQKViewReader_InvalidData(t *testing.T) { _, err := InspectQKViewReader(bytes.NewReader([]byte("not a gzip"))) if err == nil { diff --git a/pkg/client/tls.go b/pkg/client/tls.go index b4fc3ef..a0d2094 100644 --- a/pkg/client/tls.go +++ b/pkg/client/tls.go @@ -8,6 +8,7 @@ import ( "net/url" "os" "runtime" + "strings" "time" ) @@ -122,6 +123,34 @@ func LoadClientCertificate(certFile, keyFile string) (*tls.Certificate, error) { return &cert, nil } +// SecureRedirectPolicy validates HTTP redirects to prevent credential leakage and protocol downgrades. +func SecureRedirectPolicy(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return fmt.Errorf("stopped after 10 redirects") + } + if len(via) > 0 { + isCrossHost := !strings.EqualFold(req.URL.Host, via[0].URL.Host) + isDowngrade := (strings.EqualFold(via[0].URL.Scheme, "https") || strings.EqualFold(via[len(via)-1].URL.Scheme, "https")) && strings.EqualFold(req.URL.Scheme, "http") + + if isDowngrade { + return fmt.Errorf("refusing insecure HTTP redirect from HTTPS endpoint") + } + + if isCrossHost { + req.Header.Del("Authorization") + req.Header.Del("X-F5-Auth-Token") + + if _, ok := via[0].URL.Query()["k"]; ok { + return fmt.Errorf("refusing cross-origin redirect that would leak query credentials") + } + if _, ok := req.URL.Query()["k"]; ok { + return fmt.Errorf("refusing cross-origin redirect that would leak query credentials") + } + } + } + return nil +} + // NewSecureHTTPClient returns an *http.Client configured with modern TLS and transport settings. func NewSecureHTTPClient(timeout time.Duration) *http.Client { return NewSecureHTTPClientWithCert(timeout, nil) @@ -134,8 +163,9 @@ func NewSecureHTTPClientWithCert(timeout time.Duration, cert *tls.Certificate) * certs = []tls.Certificate{*cert} } return &http.Client{ - Transport: NewProductionTransport(SecureTLSConfigWithCerts(false, certs...)), - Timeout: timeout, + Transport: NewProductionTransport(SecureTLSConfigWithCerts(false, certs...)), + Timeout: timeout, + CheckRedirect: SecureRedirectPolicy, } } @@ -152,7 +182,8 @@ func NewInsecureHTTPClientWithCert(timeout time.Duration, cert *tls.Certificate) } // #nosec G402 -- InsecureSkipVerify is purposefully allowed for lab BIG-IPs with self-signed certs return &http.Client{ - Transport: NewProductionTransport(SecureTLSConfigWithCerts(true, certs...)), - Timeout: timeout, + Transport: NewProductionTransport(SecureTLSConfigWithCerts(true, certs...)), + Timeout: timeout, + CheckRedirect: SecureRedirectPolicy, } } diff --git a/pkg/client/tls_test.go b/pkg/client/tls_test.go index c6a778c..9433105 100644 --- a/pkg/client/tls_test.go +++ b/pkg/client/tls_test.go @@ -12,6 +12,7 @@ import ( "net/http" "os" "path/filepath" + "strings" "testing" "time" ) @@ -47,11 +48,86 @@ func TestNewClients(t *testing.T) { if secClient == nil || secClient.Timeout != 10*time.Second { t.Fatalf("expected client with 10s timeout, got %v", secClient) } + if secClient.CheckRedirect == nil { + t.Errorf("expected CheckRedirect policy configured on secure client") + } insecClient := NewInsecureHTTPClient(5 * time.Second) if insecClient == nil || insecClient.Timeout != 5*time.Second { t.Fatalf("expected client with 5s timeout, got %v", insecClient) } + if insecClient.CheckRedirect == nil { + t.Errorf("expected CheckRedirect policy configured on insecure client") + } +} + +func TestSecureRedirectPolicy(t *testing.T) { + origReq, err := http.NewRequest(http.MethodGet, "https://api.example.com/cases", nil) + if err != nil { + t.Fatalf("NewRequest failed: %v", err) + } + + // 1. Insecure downgrade: HTTPS -> HTTP + httpReq, err := http.NewRequest(http.MethodGet, "http://api.example.com/cases", nil) + if err != nil { + t.Fatalf("NewRequest failed: %v", err) + } + err = SecureRedirectPolicy(httpReq, []*http.Request{origReq}) + if err == nil || !strings.Contains(err.Error(), "refusing insecure HTTP redirect") { + t.Errorf("expected insecure downgrade to be rejected, got: %v", err) + } + + // 2. Cross-host redirect strips Authorization & X-F5-Auth-Token + crossHostReq, err := http.NewRequest(http.MethodGet, "https://other.example.com/cases", nil) + if err != nil { + t.Fatalf("NewRequest failed: %v", err) + } + crossHostReq.Header.Set("Authorization", "Bearer secret") + crossHostReq.Header.Set("X-F5-Auth-Token", "f5secret") + err = SecureRedirectPolicy(crossHostReq, []*http.Request{origReq}) + if err != nil { + t.Fatalf("unexpected redirect error: %v", err) + } + if crossHostReq.Header.Get("Authorization") != "" { + t.Errorf("expected Authorization header to be stripped on cross-host redirect") + } + if crossHostReq.Header.Get("X-F5-Auth-Token") != "" { + t.Errorf("expected X-F5-Auth-Token header to be stripped on cross-host redirect") + } + + // 3. Cross-host redirect with query credential 'k' on original URL + origWithK, err := http.NewRequest(http.MethodGet, "https://api.example.com/cases?k=my-secret-key", nil) + if err != nil { + t.Fatalf("NewRequest failed: %v", err) + } + err = SecureRedirectPolicy(crossHostReq, []*http.Request{origWithK}) + if err == nil || !strings.Contains(err.Error(), "refusing cross-origin redirect that would leak query credentials") { + t.Errorf("expected leak prevention on cross-host redirect with k, got: %v", err) + } + + // 4. Cross-host redirect with query credential 'k' on destination URL + crossWithK, err := http.NewRequest(http.MethodGet, "https://other.example.com/cases?k=my-secret-key", nil) + if err != nil { + t.Fatalf("NewRequest failed: %v", err) + } + err = SecureRedirectPolicy(crossWithK, []*http.Request{origReq}) + if err == nil || !strings.Contains(err.Error(), "refusing cross-origin redirect that would leak query credentials") { + t.Errorf("expected leak prevention when redirect URL has k, got: %v", err) + } + + // 5. Same host redirect preserves Authorization + sameHostReq, err := http.NewRequest(http.MethodGet, "https://api.example.com/v2/cases", nil) + if err != nil { + t.Fatalf("NewRequest failed: %v", err) + } + sameHostReq.Header.Set("Authorization", "Bearer secret") + err = SecureRedirectPolicy(sameHostReq, []*http.Request{origReq}) + if err != nil { + t.Fatalf("unexpected redirect error: %v", err) + } + if sameHostReq.Header.Get("Authorization") != "Bearer secret" { + t.Errorf("expected Authorization to be retained for same-host redirect") + } } func TestLoadClientCertificate(t *testing.T) { diff --git a/pkg/ihealth/models.go b/pkg/ihealth/models.go index e62a851..fe379d0 100644 --- a/pkg/ihealth/models.go +++ b/pkg/ihealth/models.go @@ -2,6 +2,7 @@ package ihealth import ( "fmt" + "net/url" "time" ) @@ -45,7 +46,7 @@ type qkviewDetail struct { func (d qkviewDetail) toSummary(id string) *QKViewSummary { guiURL := d.GUIURI if guiURL == "" && id != "" { - guiURL = fmt.Sprintf("https://ihealth.f5.com/qkview-analyzer/qv/%s", id) + guiURL = fmt.Sprintf("https://ihealth.f5.com/qkview-analyzer/qv/%s", url.PathEscape(id)) } s := &QKViewSummary{ ID: id, From 0bb9d8488b9c30b793fd6c6367c4c10fb00d8868 Mon Sep 17 00:00:00 2001 From: Greg Robinson Date: Mon, 16 Nov 2026 10:11:40 -0500 Subject: [PATCH 6/9] fix(test): skip POSIX 0600 file mode assertion on Windows in TestDownloadFromURI --- pkg/bigip/client_test.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/pkg/bigip/client_test.go b/pkg/bigip/client_test.go index 14d2991..283551b 100644 --- a/pkg/bigip/client_test.go +++ b/pkg/bigip/client_test.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "regexp" + "runtime" "strconv" "strings" "testing" @@ -174,8 +175,10 @@ func TestDownloadFromURI(t *testing.T) { if err != nil { t.Fatalf("failed to stat destFile: %v", err) } - if info.Mode().Perm() != 0600 { - t.Errorf("expected file mode 0600, got %04o", info.Mode().Perm()) + if runtime.GOOS != "windows" { + if info.Mode().Perm() != 0600 { + t.Errorf("expected file mode 0600, got %04o", info.Mode().Perm()) + } } } From 248d1b2c69b54d5496e8b78df7be4b14d667bca2 Mon Sep 17 00:00:00 2001 From: Greg Robinson Date: Mon, 16 Nov 2026 15:36:20 -0500 Subject: [PATCH 7/9] feat(bigip,test): add BIG-IQ token auth fallback and full repo function test coverage --- cmd/myf5/coverage_test.go | 2251 ++++++++++++++++++++++++++++++ cmd/myf5/interactive.go | 19 +- cmd/myf5/main.go | 15 +- pkg/auth/credentials_test.go | 19 + pkg/auth/oauth.go | 6 +- pkg/auth/oauth_test.go | 50 +- pkg/bigip/client.go | 136 +- pkg/bigip/client_test.go | 278 +++- pkg/bigip/failover.go | 7 +- pkg/bigip/failover_test.go | 191 ++- pkg/bigip/geoip.go | 2 + pkg/bigip/geoip_test.go | 181 ++- pkg/bigip/info.go | 3 +- pkg/bigip/info_test.go | 110 +- pkg/bigip/lifecycle_test.go | 45 + pkg/bigip/mock_server_test.go | 222 +++ pkg/bigip/scp_test.go | 78 +- pkg/bigip/upload.go | 6 +- pkg/bigip/upload_test.go | 10 +- pkg/cases/client.go | 7 +- pkg/cases/client_test.go | 203 ++- pkg/client/proxy.go | 28 +- pkg/client/proxy_test.go | 395 +++++- pkg/client/tls.go | 11 +- pkg/client/tls_test.go | 26 + pkg/downloads/client_test.go | 234 +++- pkg/downloads/downloader.go | 7 +- pkg/downloads/downloader_test.go | 13 +- pkg/downloads/folder_test.go | 20 + pkg/ihealth/client.go | 6 +- pkg/ihealth/client_test.go | 116 +- pkg/logger/logger_test.go | 25 + pkg/logger/logger_unix.go | 9 + pkg/progress/progress_test.go | 85 ++ 34 files changed, 4655 insertions(+), 159 deletions(-) create mode 100644 cmd/myf5/coverage_test.go create mode 100644 pkg/bigip/mock_server_test.go diff --git a/cmd/myf5/coverage_test.go b/cmd/myf5/coverage_test.go new file mode 100644 index 0000000..41270bd --- /dev/null +++ b/cmd/myf5/coverage_test.go @@ -0,0 +1,2251 @@ +package main + +import ( + "archive/tar" + "bufio" + "bytes" + "compress/gzip" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "golang.org/x/term" + + "myf5-cli/pkg/cases" + "myf5-cli/pkg/client" + "myf5-cli/pkg/downloads" +) + +func TestExtractProxyFlag(t *testing.T) { + tests := []struct { + name string + args []string + wantArgs []string + wantProxy string + }{ + { + name: "space separated proxy", + args: []string{"bigip", "--proxy", "http://proxy.corp:8080", "ready", "10.1.1.4"}, + wantArgs: []string{"bigip", "ready", "10.1.1.4"}, + wantProxy: "http://proxy.corp:8080", + }, + { + name: "equals separated proxy", + args: []string{"--proxy=socks5://127.0.0.1:1080", "cases", "list"}, + wantArgs: []string{"cases", "list"}, + wantProxy: "socks5://127.0.0.1:1080", + }, + { + name: "proxy at end without value", + args: []string{"doctor", "--proxy"}, + wantArgs: []string{"doctor"}, + wantProxy: "", + }, + { + name: "no proxy flag", + args: []string{"version"}, + wantArgs: []string{"version"}, + wantProxy: "", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + gotArgs, gotProxy := extractProxyFlag(tc.args) + if gotProxy != tc.wantProxy { + t.Errorf("extractProxyFlag() proxy = %q, want %q", gotProxy, tc.wantProxy) + } + if len(gotArgs) != len(tc.wantArgs) { + t.Fatalf("extractProxyFlag() args length = %d, want %d (%v)", len(gotArgs), len(tc.wantArgs), gotArgs) + } + for i := range gotArgs { + if gotArgs[i] != tc.wantArgs[i] { + t.Errorf("args[%d] = %q, want %q", i, gotArgs[i], tc.wantArgs[i]) + } + } + }) + } +} + +func TestUsagePrinters(t *testing.T) { + // Exercise all printer functions to ensure they execute without panics. + printers := []func(){ + printInteractiveUsage, + printCasesUsage, + printIHealthUsage, + func() { printApplianceUsage("BIG-IP") }, + func() { printApplianceUsage("BIG-IQ") }, + func() { printApplianceUsage("auto") }, + printPushUsage, + printPullUsage, + printProxyUsage, + printDoctorUsage, + printUsage, + printDownloadsUsage, + } + + for i, fn := range printers { + t.Run(fmt.Sprintf("printer_%d", i), func(t *testing.T) { + fn() + }) + } + + // Exercise printCommandHelp branches + helpCommands := []string{ + "downloads", "download", "cases", "case", "wizard", "ihealth", + "bigip", "geoip", "bigiq", "push", "pull", "fetch", + "proxy", "doctor", "interactive", "shell", "repl", "i", "other", + } + for _, cmd := range helpCommands { + t.Run("printCommandHelp_"+cmd, func(t *testing.T) { + printCommandHelp(cmd) + }) + } +} + +func TestSuggestRemediationAndCheckErr(t *testing.T) { + remediations := []struct { + errStr string + expected string + }{ + {"unencrypted HTTP is forbidden", "Appliance management strictly requires HTTPS"}, + {"Appliance Mode is enabled", "The TMOS bash utility is restricted"}, + {"/mgmt/tm/util/bash disabled", "The TMOS bash utility is restricted"}, + {"401 Unauthorized: invalid_client credentials", "Run 'myf5 doctor'"}, + {"HTTP 429 Too Many Requests", "Wait 60 seconds"}, + {"dial tcp: connection refused", "Verify hostname DNS resolution"}, + {"network timeout occurred", "Verify hostname DNS resolution"}, + {"directory traversal detected outside destination", "illegal directory traversal"}, + {"unrelated generic failure", ""}, + } + + for _, r := range remediations { + rem := suggestRemediation(errors.New(r.errStr)) + if r.expected == "" && rem != "" { + t.Errorf("expected empty remediation for %q, got %q", r.errStr, rem) + } + if r.expected != "" && !strings.Contains(rem, r.expected) { + t.Errorf("expected remediation to contain %q, got %q", r.expected, rem) + } + } + if rem := suggestRemediation(nil); rem != "" { + t.Errorf("expected nil error to return empty remediation, got %q", rem) + } + + // printDetailedError with and without prefix + printDetailedError("TestPrefix", errors.New("401 Unauthorized")) + printDetailedError("", errors.New("generic error")) + + // checkErr: nil error does not exit + checkErr(context.Background(), nil, "ignored") + + // checkErr: cancelled context exits with 130 + code, exited := runWithExitCapture(func() { + canceledCtx, cancel := context.WithCancel(context.Background()) + cancel() + checkErr(canceledCtx, context.Canceled, "cancelled op") + }) + if !exited || code != 130 { + t.Errorf("expected exit code 130 for cancelled context, got code=%d exited=%v", code, exited) + } + + // checkErr: general error exits with 1 + code, exited = runWithExitCapture(func() { + checkErr(context.Background(), errors.New("something failed"), "general error") + }) + if !exited || code != 1 { + t.Errorf("expected exit code 1 for generic error, got code=%d exited=%v", code, exited) + } +} + +func TestHandleProxyCommand(t *testing.T) { + origProxy := client.GetGlobalProxy() + defer func() { + if origProxy != nil { + _ = client.SetGlobalProxy(origProxy.String()) + } else { + client.ClearGlobalProxy() + } + }() + + // 1. Status / show when none configured + client.ClearGlobalProxy() + handleProxyCommand([]string{}) + handleProxyCommand([]string{"show"}) + handleProxyCommand([]string{"status"}) + + // 2. Set valid proxy + handleProxyCommand([]string{"set", "http://proxy.corp.internal:8080"}) + if p := client.GetGlobalProxy(); p == nil || !strings.Contains(p.String(), "8080") { + t.Fatalf("expected proxy to be set, got %v", p) + } + + // Status when configured + handleProxyCommand([]string{"status"}) + + // 3. Clear proxy + handleProxyCommand([]string{"clear"}) + if p := client.GetGlobalProxy(); p != nil { + t.Errorf("expected proxy to be cleared, got %v", p) + } + handleProxyCommand([]string{"unset"}) + handleProxyCommand([]string{"off"}) + + // 4. Help flag + handleProxyCommand([]string{"--help"}) + + // 5. Bare URL syntax + handleProxyCommand([]string{"socks5://127.0.0.1:1080"}) + if p := client.GetGlobalProxy(); p == nil || !strings.Contains(p.String(), "socks5") { + t.Errorf("expected socks5 proxy set, got %v", p) + } + + // 6. Invalid URLs exit 1 + code, exited := runWithExitCapture(func() { + handleProxyCommand([]string{"set", ":::invalid-url"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on invalid proxy set, got %d", code) + } + + code, exited = runWithExitCapture(func() { + handleProxyCommand([]string{":::invalid-url"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on invalid bare proxy, got %d", code) + } + + client.ClearGlobalProxy() +} + +func TestDefaultDownloadsDir(t *testing.T) { + dir := getDefaultDownloadsDir() + if dir == "" { + t.Errorf("expected non-empty default downloads dir") + } +} + +func TestRequireFlagValueAndRejectSecretFlag(t *testing.T) { + // Valid value + val := requireFlagValue([]string{"--user", "admin"}, 0, "--user") + if val != "admin" { + t.Errorf("expected admin, got %q", val) + } + + // Missing value at end + code, exited := runWithExitCapture(func() { + requireFlagValue([]string{"--user"}, 0, "--user") + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for missing flag value, got %d", code) + } + + // Next arg is another flag + code, exited = runWithExitCapture(func() { + requireFlagValue([]string{"--user", "--port", "443"}, 0, "--user") + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for next flag value, got %d", code) + } + + // Reject secret flag + code, exited = runWithExitCapture(func() { + rejectSecretFlag("--password") + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for rejectSecretFlag, got %d", code) + } +} + +func TestResolveApplianceCreds_Validations(t *testing.T) { + // Invalid host + code, exited := runWithExitCapture(func() { + resolveApplianceCreds("http://invalid:format:host", "BIG-IP", "", "", "", "", false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for invalid host, got %d", code) + } + + // Existing file avoids host parse check + tmpFile := filepath.Join(t.TempDir(), "localfile.txt") + os.WriteFile(tmpFile, []byte("data"), 0600) + creds := resolveApplianceCreds(tmpFile, "auto", "custom-user", "", "", "", false) + if creds.User != "custom-user" { + t.Errorf("expected custom-user, got %q", creds.User) + } + + // Invalid username + code, exited = runWithExitCapture(func() { + resolveApplianceCreds("10.1.1.1", "BIG-IP", "bad\nuser", "", "", "", false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for invalid username, got %d", code) + } + + // Cert validation failure + code, exited = runWithExitCapture(func() { + resolveApplianceCreds("10.1.1.1", "BIG-IP", "admin", "/nonexistent/cert.pem", "", "", false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for nonexistent cert, got %d", code) + } + + // Key validation failure + code, exited = runWithExitCapture(func() { + resolveApplianceCreds("10.1.1.1", "BIG-IP", "admin", "", "/nonexistent/key.pem", "", false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for nonexistent key, got %d", code) + } + + // Identity validation failure + code, exited = runWithExitCapture(func() { + resolveApplianceCreds("10.1.1.1", "BIG-IP", "admin", "", "", "/nonexistent/id_rsa", false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for nonexistent identity, got %d", code) + } + + // Valid cert, key, and identity files + certPath := filepath.Join(t.TempDir(), "client.crt") + keyPath := filepath.Join(t.TempDir(), "client.key") + idPath := filepath.Join(t.TempDir(), "id_rsa") + os.WriteFile(certPath, []byte("cert"), 0600) + os.WriteFile(keyPath, []byte("key"), 0600) + os.WriteFile(idPath, []byte("id"), 0600) + + validCreds := resolveApplianceCreds("10.1.1.1", "bigiq", "testuser", certPath, keyPath, idPath, true) + if validCreds.TargetKind != "BIG-IQ" { + t.Errorf("expected BIG-IQ, got %q", validCreds.TargetKind) + } + if validCreds.Cert != certPath || validCreds.Key != keyPath || validCreds.Identity != idPath { + t.Errorf("paths mismatched in ApplianceCreds: %+v", validCreds) + } +} + +func TestHasDefaultSSHAuth(t *testing.T) { + // 1. With SSH_AUTH_SOCK set + os.Setenv("SSH_AUTH_SOCK", "/tmp/fake-ssh-agent.sock") + if !hasDefaultSSHAuth() { + t.Errorf("expected hasDefaultSSHAuth to be true with SSH_AUTH_SOCK") + } + os.Unsetenv("SSH_AUTH_SOCK") + + // 2. With clean temp home directory without keys + fakeHome := t.TempDir() + origHome := os.Getenv("HOME") + os.Setenv("HOME", fakeHome) + defer os.Setenv("HOME", origHome) + + if hasDefaultSSHAuth() { + t.Errorf("expected hasDefaultSSHAuth to be false in empty home") + } + + // 3. With id_rsa created + sshDir := filepath.Join(fakeHome, ".ssh") + os.MkdirAll(sshDir, 0700) + os.WriteFile(filepath.Join(sshDir, "id_rsa"), []byte("dummy-key"), 0600) + + if !hasDefaultSSHAuth() { + t.Errorf("expected hasDefaultSSHAuth to be true with id_rsa present") + } +} + +func TestHandleDoctor(t *testing.T) { + // Help flag + handleDoctor(context.Background(), []string{"--help"}) + handleDoctor(context.Background(), []string{"-h"}) + + // Canceled context exits 130 + canceledCtx, cancel := context.WithCancel(context.Background()) + cancel() + code, exited := runWithExitCapture(func() { + handleDoctor(canceledCtx, nil) + }) + if !exited || code != 130 { + t.Errorf("expected exit 130 on canceled doctor run, got %d", code) + } + + // Outbound proxy failure audit + origProxy := client.GetGlobalProxy() + defer func() { + if origProxy != nil { + _ = client.SetGlobalProxy(origProxy.String()) + } else { + client.ClearGlobalProxy() + } + }() + + _ = client.SetGlobalProxy("http://127.0.0.1:1") + os.Setenv("F5_CLIENT_ID", "dummy-client-id") + os.Setenv("F5_CLIENT_SECRET", "dummy-client-secret") + defer func() { + os.Unsetenv("F5_CLIENT_ID") + os.Unsetenv("F5_CLIENT_SECRET") + }() + + code, exited = runWithExitCapture(func() { + handleDoctor(context.Background(), nil) + }) + if !exited || code != 1 { + t.Errorf("expected doctor to exit 1 when endpoints fail, got %d", code) + } +} + +func TestInteractiveRunSafely(t *testing.T) { + // Empty args + runSafely([]string{}) + + // Proxy argument with command + runSafely([]string{"--proxy", "http://127.0.0.1:8080", "version"}) + + // Proxy parse error + runSafely([]string{"--proxy", ":::invalid-proxy"}) + + // Unexpected panic rethrown + defer func() { + r := recover() + if r == nil { + t.Errorf("expected runSafely to rethrow unexpected panic") + } + }() + // Trigger unexpected non-exitPanic panic + prevExit := exitFunc + exitFunc = func(code int) { + panic("non-exit panic") + } + defer func() { + exitFunc = prevExit + }() + runSafely([]string{"nonexistent_subcommand_to_trigger_exit"}) +} + +func TestStartInteractive_NonTTY(t *testing.T) { + code, exited := runWithExitCapture(func() { + startInteractive() + }) + if !exited || code != 1 { + t.Errorf("expected startInteractive to exit 1 in non-terminal, got %d", code) + } +} + +func TestExecuteSubcommand_HelpRoutes(t *testing.T) { + subcommands := []string{ + "downloads", "download", "cases", "case", "wizard", "ihealth", + "bigip", "bigiq", "appliance", "device", "ready", "info", "serial", + "qkview", "push", "pull", "geoip", "proxy", "doctor", + } + + for _, sub := range subcommands { + t.Run("help_"+sub, func(t *testing.T) { + code, exited := runWithExitCapture(func() { + executeSubcommand(context.Background(), sub, []string{"--help"}) + }) + if !exited || code != 0 { + t.Errorf("expected exit 0 for %s --help, got code=%d exited=%v", sub, code, exited) + } + }) + } + + // Test non-help subcommands dispatching + t.Run("version", func(t *testing.T) { + executeSubcommand(context.Background(), "version", nil) + executeSubcommand(context.Background(), "--version", nil) + executeSubcommand(context.Background(), "-v", nil) + }) + + t.Run("top_level_help", func(t *testing.T) { + executeSubcommand(context.Background(), "help", nil) + executeSubcommand(context.Background(), "--help", nil) + }) + + t.Run("unknown_subcommand", func(t *testing.T) { + code, exited := runWithExitCapture(func() { + executeSubcommand(context.Background(), "nonexistent_cmd_xyz", nil) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for unknown subcommand, got %d", code) + } + }) + + t.Run("subcommand_empty_args", func(t *testing.T) { + emptyArgsCmds := []string{ + "downloads", "cases", "ihealth", "bigip", "bigiq", + "appliance", "device", "ready", "info", "serial", + "qkview", "push", "pull", "geoip", + } + for _, cmd := range emptyArgsCmds { + code, exited := runWithExitCapture(func() { + executeSubcommand(context.Background(), cmd, []string{}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for bare %s, got %d", cmd, code) + } + } + }) +} + +func TestHandleDownloads_Validation(t *testing.T) { + // Empty args + code, exited := runWithExitCapture(func() { + handleDownloads(context.Background(), []string{}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for empty downloads args, got %d", code) + } + + // Missing sub-arguments + actionsMissingArgs := [][]string{ + {"lines"}, + {"versions"}, + {"containers"}, + {"files"}, + {"get"}, + {"unknown-action"}, + } + + for _, args := range actionsMissingArgs { + t.Run("downloads_"+args[0], func(t *testing.T) { + code, exited := runWithExitCapture(func() { + handleDownloads(context.Background(), args) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for downloads %v, got %d", args, code) + } + }) + } +} + +func TestHandleCasesAndDetail(t *testing.T) { + // Bare invocation + code, exited := runWithExitCapture(func() { + handleCases(context.Background(), []string{}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for bare handleCases, got %d", code) + } + + // Unknown action + code, exited = runWithExitCapture(func() { + handleCases(context.Background(), []string{"unknown-action"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for unknown cases action, got %d", code) + } + + // Get without case number + code, exited = runWithExitCapture(func() { + handleCases(context.Background(), []string{"get"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for cases get without number, got %d", code) + } + + // printCaseDetail + detail := &cases.CaseDetail{ + CaseNumber: "C-123456", + Subject: "High CPU usage on TMM", + Status: "In Progress", + Priority: "2 - Site At Risk", + Product: "BIG-IP LTM", + Version: "17.5.1", + ReasonForContact: "Software Bug", + SerialNumber: "test-serial-123", + HostName: "bigip-01.corp.internal", + DateOpened: "2026-11-01T12:00:00Z", + CaseOwnerContact: cases.CaseContact{ + FirstName: "Jane", + LastName: "Doe", + Email: "jane.doe@example.com", + }, + AlternateContact: cases.CaseContact{ + FirstName: "John", + LastName: "Smith", + Email: "john.smith@example.com", + }, + Description: "Detailed description of the TMM core dump.\nMultiple lines.\n", + } + detail.Account.AccountName = "ACME Corp" + detail.Account.AccountID = "ACT-9999" + detail.Links = []struct { + Rel string `json:"rel"` + Href string `json:"href"` + }{ + {Rel: "case-detail", Href: "https://my.f5.com/cases/C-123456"}, + } + printCaseDetail(detail) + + // Minimal detail + printCaseDetail(&cases.CaseDetail{ + CaseNumber: "C-000000", + Subject: "Simple question", + Status: "Open", + }) +} + +func TestHandleCaseCreate_FlagsAndDryRun(t *testing.T) { + // Help flag + handleCaseCreate(context.Background(), nil, []string{"--help"}) + handleCaseCreate(context.Background(), nil, []string{"-h"}) + + // Unknown flag + code, exited := runWithExitCapture(func() { + handleCaseCreate(context.Background(), nil, []string{"--nonexistent-flag"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for unknown flag in case create, got %d", code) + } + + // Missing value for flag + code, exited = runWithExitCapture(func() { + handleCaseCreate(context.Background(), nil, []string{"--from-appliance"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for missing value for --from-appliance, got %d", code) + } + + // Dry run with missing required fields + code, exited = runWithExitCapture(func() { + handleCaseCreate(context.Background(), nil, []string{"--dry-run", "--family", "BIG-IP"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for dry-run with missing fields, got %d", code) + } + + // Dry run with all required fields (BIG-IP) + code, exited = runWithExitCapture(func() { + handleCaseCreate(context.Background(), nil, []string{ + "--dry-run", + "--family", "BIG-IP", + "--product", "BIG-IP LTM", + "--version", "17.5.1", + "--serial", "f5-serial-test-123", + "--priority", "4", + "--reason", "General Problem", + "--subject", "Testing Dry Run Complete", + "--description", "Everything filled out properly", + "--email", "user@example.com", + "--timezone", "(GMT -05:00) EST", + }) + }) + if exited && code != 0 { + t.Errorf("expected dry-run with all fields to succeed without error, got code=%d", code) + } +} + +func TestHandleIHealth_Validation(t *testing.T) { + // Empty args + code, exited := runWithExitCapture(func() { + handleIHealth(context.Background(), []string{}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for bare handleIHealth, got %d", code) + } + + // Upload without file + code, exited = runWithExitCapture(func() { + handleIHealth(context.Background(), []string{"upload"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for ihealth upload without file, got %d", code) + } + + // Upload nonexistent file + code, exited = runWithExitCapture(func() { + handleIHealth(context.Background(), []string{"upload", "/nonexistent/test.qkview"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for nonexistent qkview upload, got %d", code) + } + + // Unknown action + code, exited = runWithExitCapture(func() { + handleIHealth(context.Background(), []string{"unknown-action"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for unknown ihealth action, got %d", code) + } +} + +func TestMockApplianceTLSServer_Operations(t *testing.T) { + client.ClearGlobalProxy() + + // 1. detectApplianceKind fallback behavior + kind1 := detectApplianceKind(context.Background(), "127.0.0.1", 443, "admin", "", nil, "", "", "BIG-IP") + if kind1 != "BIG-IP" { + t.Errorf("expected detectApplianceKind fallback = BIG-IP, got %q", kind1) + } + + kind2 := detectApplianceKind(context.Background(), "127.0.0.1", 443, "admin", "", nil, "", "", "auto") + if kind2 != "Appliance" { + t.Errorf("expected detectApplianceKind fallback = Appliance, got %q", kind2) + } + + // 2. resolveApplianceSystemInfo error handling + _, errIC := resolveApplianceSystemInfo(context.Background(), "127.0.0.1", 1, "admin", "secret", nil, "", "icontrol", "BIG-IP", "", "") + if errIC == nil { + t.Errorf("expected resolveApplianceSystemInfo icontrol error on closed port") + } + + _, errSSH := resolveApplianceSystemInfo(context.Background(), "127.0.0.1", 1, "admin", "secret", nil, "", "scp", "BIG-IP", "", "") + if errSSH == nil { + t.Errorf("expected resolveApplianceSystemInfo scp error on closed port") + } + + _, errAuto := resolveApplianceSystemInfo(context.Background(), "127.0.0.1", 1, "admin", "secret", nil, "", "auto", "BIG-IP", "", "") + if errAuto == nil { + t.Errorf("expected resolveApplianceSystemInfo auto error on closed port") + } + + // 3. getSystemInfoTarget with valid qkview file and nonexistent qkview + qkviewFile := filepath.Join(t.TempDir(), "test.qkview") + createMockQKViewArchive(t, qkviewFile) + + sysInfo := getSystemInfoTarget(context.Background(), qkviewFile, "BIG-IP", "admin", 0, "", "auto", "", "") + if sysInfo == nil || sysInfo.Version != "17.5.1" { + t.Fatalf("getSystemInfoTarget on qkview failed: %+v", sysInfo) + } + + code, exited := runWithExitCapture(func() { + getSystemInfoTarget(context.Background(), "nonexistent.qkview", "BIG-IP", "admin", 0, "", "auto", "", "") + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for nonexistent qkview, got %d", code) + } + + // 4. handleAppliance: info and serial using local QKView (tests successful paths!) + handleAppliance(context.Background(), "BIG-IP", []string{"info", qkviewFile}) + handleAppliance(context.Background(), "BIG-IP", []string{"info", qkviewFile, "--json"}) + handleAppliance(context.Background(), "BIG-IP", []string{"serial", qkviewFile}) + handleAppliance(context.Background(), "BIG-IP", []string{"serial", qkviewFile, "--json"}) + + // 5. handleAppliance: ready check network failure + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"ready", "127.0.0.1", "--port", "1"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for ready check to closed port, got %d", code) + } + + // 6. handleAppliance: qkview, geoip, push, and download errors to closed port + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"qkview", "127.0.0.1", "--port", "1"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for qkview to closed port, got %d", code) + } + + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IQ", []string{"geoip", "127.0.0.1", "geo.zip"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for BIG-IQ geoip rejection, got %d", code) + } + + // 7. handleBIGIP and handleBIGIQ wrappers with local qkview + handleBIGIP(context.Background(), []string{"info", qkviewFile}) + handleBIGIQ(context.Background(), []string{"serial", qkviewFile}) + + // 8. handleAppliance error validation branches + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for empty appliance args, got %d", code) + } + + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"ready"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for ready without host, got %d", code) + } + + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"unknown-action", "127.0.0.1"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for unknown appliance action, got %d", code) + } + + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"ready", "127.0.0.1", "--password", "secret"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for rejected password flag, got %d", code) + } + + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"ready", "127.0.0.1", "--bogus-flag"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for unknown flag, got %d", code) + } + + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"ready", "127.0.0.1", "--method", "invalid-method"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for invalid method, got %d", code) + } + + // 9. Push & Pull error validation + code, exited = runWithExitCapture(func() { + handlePush(context.Background(), []string{"127.0.0.1"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for push with insufficient args, got %d", code) + } + + code, exited = runWithExitCapture(func() { + handlePull(context.Background(), []string{"127.0.0.1"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for pull with insufficient args, got %d", code) + } + + code, exited = runWithExitCapture(func() { + executePushToAppliance(context.Background(), "127.0.0.1", "/nonexistent/path/file.txt", "icontrol", "/tmp", "admin", 1, "", "BIG-IP", "", "", false, false, false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for nonexistent file push, got %d", code) + } + + code, exited = runWithExitCapture(func() { + executePushToAppliance(context.Background(), "127.0.0.1", qkviewFile, "invalid-method", "/tmp", "admin", 1, "", "BIG-IP", "", "", false, false, false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for invalid method push, got %d", code) + } + + code, exited = runWithExitCapture(func() { + executePushToAppliance(context.Background(), "127.0.0.1", qkviewFile, "icontrol", "/tmp", "admin", 1, "", "BIG-IQ", "", "", true, false, false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for geoip on bigiq push, got %d", code) + } + + code, exited = runWithExitCapture(func() { + executeDownloadFromAppliance(context.Background(), "127.0.0.1", "../../../etc/shadow", "", "icontrol", "admin", 1, "", "BIG-IP", "", "") + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for illegal path traversal download, got %d", code) + } + + code, exited = runWithExitCapture(func() { + executeDownloadFromAppliance(context.Background(), "127.0.0.1", "/shared/images/file.iso", "", "invalid-method", "admin", 1, "", "BIG-IP", "", "") + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for invalid method download, got %d", code) + } +} + +func TestWizardAndSelectorExtensions(t *testing.T) { + // 1. promptRequired + in := bufio.NewReader(strings.NewReader("\n\nProvided Value\n")) + var out bytes.Buffer + val, err := promptRequired(in, &out, "Field", "") + if err != nil { + t.Fatalf("promptRequired failed: %v", err) + } + if val != "Provided Value" { + t.Errorf("expected 'Provided Value', got %q", val) + } + + // promptRequired with EOF + inEOF := bufio.NewReader(strings.NewReader("\n\n")) + _, errEOF := promptRequired(inEOF, &out, "Field", "") + if errEOF == nil { + t.Errorf("expected error on EOF in promptRequired") + } + + // 2. editInExternalEditor with EDITOR=true + os.Setenv("EDITOR", "true") + defer os.Unsetenv("EDITOR") + content, err := editInExternalEditor("initial test line") + if err != nil { + t.Fatalf("editInExternalEditor failed with EDITOR=true: %v", err) + } + if content != "initial test line" { + t.Errorf("expected initial test line, got %q", content) + } + + // editInExternalEditor with failing editor + os.Setenv("EDITOR", "nonexistent-cmd-12345") + _, errFail := editInExternalEditor("fail content") + if errFail == nil { + t.Errorf("expected failure with nonexistent editor") + } + + // 3. editWizardField + fieldsToTest := []struct { + fieldNum int + input string + }{ + {1, "BIG-IP\n"}, + {2, "BIG-IP LTM\n"}, + {3, "17.5.1\n"}, + {4, "test-serial-123\n"}, + {5, "2\n"}, + {6, "1\n"}, + {7, "New Subject\n"}, + {8, "Updated description line 1\n.\n"}, + {9, "admin@example.com\n"}, + {10, "Email\n"}, + {11, "(GMT -05:00) EST\n"}, + {12, "bigip-01.corp\n"}, + {13, "INC-12345\n"}, + {99, ""}, // default invalid field + } + + opts := &CaseWizardOptions{ + ProductFamily: "BIG-IP", + Product: "BIG-IP LTM", + Version: "17.5.1", + } + + for _, tc := range fieldsToTest { + reader := bufio.NewReader(strings.NewReader(tc.input)) + var buf bytes.Buffer + _ = editWizardField(reader, &buf, tc.fieldNum, opts) + } + + // Test field 4 for NGINX subscription + opts.ProductFamily = "NGINX" + readerSub := bufio.NewReader(strings.NewReader("A-SUB-9999\n")) + var bufSub bytes.Buffer + _ = editWizardField(readerSub, &bufSub, 4, opts) + if opts.SubscriptionID != "A-SUB-9999" { + t.Errorf("expected SubscriptionID to be A-SUB-9999, got %q", opts.SubscriptionID) + } + + // 4. SelectMenu with empty items + _, _, errEmpty := SelectMenu(SelectConfig{Items: nil}) + if errEmpty == nil { + t.Errorf("expected error for empty SelectMenu items") + } + + // SelectMenu non-TTY fallback + items := []SelectItem{ + {ID: "opt1", Title: "Option 1"}, + {ID: "opt2", Title: "Option 2"}, + } + rPipe, wPipe, _ := os.Pipe() + go func() { + wPipe.WriteString("1\n") + wPipe.Close() + }() + idx, chosen, sErr := SelectMenu(SelectConfig{ + Items: items, + In: rPipe, + }) + rPipe.Close() + if sErr != nil || idx != 0 || chosen.ID != "opt1" { + t.Errorf("SelectMenu fallback pipe failed: idx=%d chosen=%+v err=%v", idx, chosen, sErr) + } + + // 5. selectNavField + rNav := bufio.NewReader(strings.NewReader("b\n")) + _, navErr := selectNavField(rNav, nil, nil, "Title", "Prompt", items, "1") + if !errors.Is(navErr, ErrWizardBack) { + t.Errorf("expected ErrWizardBack on 'b', got %v", navErr) + } + + // 6. runStep1AutoDetection: Option 3 (Skip) + optsDetect := &CaseWizardOptions{} + step, errStep := runStep1AutoDetection(context.Background(), bufio.NewReader(strings.NewReader("3\n")), &bytes.Buffer{}, optsDetect) + if errStep != nil || step != 2 { + t.Errorf("runStep1AutoDetection option 3 failed: step=%d err=%v", step, errStep) + } + + // runStep1AutoDetection: Option 2 (Local QKView) + qkviewFile := filepath.Join(t.TempDir(), "test.qkview") + createMockQKViewArchive(t, qkviewFile) + readerOpt2 := bufio.NewReader(strings.NewReader("2\n" + qkviewFile + "\n")) + step, errStep = runStep1AutoDetection(context.Background(), readerOpt2, &bytes.Buffer{}, optsDetect) + if errStep != nil || step != 2 { + t.Fatalf("runStep1AutoDetection option 2 failed: step=%d err=%v", step, errStep) + } + if optsDetect.SerialNumber != "test-serial-999" { + t.Errorf("expected SerialNumber=test-serial-999, got %q", optsDetect.SerialNumber) + } +} + +func createMockQKViewArchive(t *testing.T, filePath string) { + var buf bytes.Buffer + gw := gzip.NewWriter(&buf) + tw := tar.NewWriter(gw) + + files := map[string]string{ + "VERSION": "Product: BIG-IP\nVersion: 17.5.1\nBuild: 0.0.1\nEdition: Final\n", + "config/bigip.license": "Registration Key : TEST-REG-KEY-12345\nSerial Number : test-serial-999\n", + } + for name, content := range files { + hdr := &tar.Header{ + Name: name, + Mode: 0600, + Size: int64(len(content)), + } + if err := tw.WriteHeader(hdr); err != nil { + t.Fatalf("WriteHeader failed: %v", err) + } + if _, err := tw.Write([]byte(content)); err != nil { + t.Fatalf("Write failed: %v", err) + } + } + _ = tw.Close() + _ = gw.Close() + + if err := os.WriteFile(filePath, buf.Bytes(), 0600); err != nil { + t.Fatalf("WriteFile failed: %v", err) + } +} + +func TestHandlePush_ComprehensiveFlags(t *testing.T) { + tmpDir := t.TempDir() + certFile := filepath.Join(tmpDir, "cert.pem") + keyFile := filepath.Join(tmpDir, "key.pem") + idFile := filepath.Join(tmpDir, "id_rsa") + localFile := filepath.Join(tmpDir, "test.txt") + os.WriteFile(certFile, []byte("cert"), 0600) + os.WriteFile(keyFile, []byte("key"), 0600) + os.WriteFile(idFile, []byte("id"), 0600) + os.WriteFile(localFile, []byte("content"), 0600) + + // Valid flag combinations that fail at network dial + testFlags := [][]string{ + {"--user", "admin1", "-p", "8443", "-m", "icontrol", "-d", "/tmp", "-i", idFile, "-t", "bigip", "--cert", certFile, "--cert-key", keyFile, "--apply-geoip", "--keep-extracted", "--json", "127.0.0.1", localFile}, + {"--user=admin2", "--port=8443", "--method=scp", "--dest=/tmp", "--identity=" + idFile, "--target=bigiq", "--cert=" + certFile, "--key-file=" + keyFile, "127.0.0.1", localFile}, + {"-u", "admin3", "-o", "/tmp", "--target=auto", "--cert-key=" + keyFile, "--", "127.0.0.1", localFile}, + } + + for _, flags := range testFlags { + code, exited := runWithExitCapture(func() { + handlePush(context.Background(), flags) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for push %v, got %d", flags, code) + } + } + + // Invalid flags + invalidArgs := [][]string{ + {"-p", "invalid-port", "127.0.0.1", localFile}, + {"--port=invalid-port", "127.0.0.1", localFile}, + {"-t", "invalid-target", "127.0.0.1", localFile}, + {"--target=invalid-target", "127.0.0.1", localFile}, + {"--password", "secret", "127.0.0.1", localFile}, + {"--bogus-flag", "127.0.0.1", localFile}, + {"127.0.0.1", localFile, "extra-arg"}, + } + + for _, flags := range invalidArgs { + code, exited := runWithExitCapture(func() { + handlePush(context.Background(), flags) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for push error %v, got %d", flags, code) + } + } +} + +func TestHandlePull_ComprehensiveFlags(t *testing.T) { + tmpDir := t.TempDir() + certFile := filepath.Join(tmpDir, "cert.pem") + keyFile := filepath.Join(tmpDir, "key.pem") + idFile := filepath.Join(tmpDir, "id_rsa") + os.WriteFile(certFile, []byte("cert"), 0600) + os.WriteFile(keyFile, []byte("key"), 0600) + os.WriteFile(idFile, []byte("id"), 0600) + + testFlags := [][]string{ + {"--user", "admin1", "-p", "8443", "-m", "icontrol", "-d", "/tmp/out.txt", "-i", idFile, "-t", "bigip", "--cert", certFile, "--cert-key", keyFile, "127.0.0.1", "/shared/file.iso"}, + {"--user=admin2", "--port=8443", "--method=scp", "--dest=/tmp/out.txt", "--identity=" + idFile, "--target=bigiq", "--cert=" + certFile, "--key-file=" + keyFile, "127.0.0.1", "/shared/file.iso"}, + {"-u", "admin3", "-o", "/tmp/out.txt", "--output=/tmp/out.txt", "--target=auto", "--cert-key=" + keyFile, "--", "127.0.0.1", "/shared/file.iso"}, + } + + for _, flags := range testFlags { + code, exited := runWithExitCapture(func() { + handlePull(context.Background(), flags) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for pull %v, got %d", flags, code) + } + } + + invalidArgs := [][]string{ + {"-p", "invalid-port", "127.0.0.1", "/file.iso"}, + {"--port=invalid-port", "127.0.0.1", "/file.iso"}, + {"-t", "invalid-target", "127.0.0.1", "/file.iso"}, + {"--target=invalid-target", "127.0.0.1", "/file.iso"}, + {"--password", "secret", "127.0.0.1", "/file.iso"}, + {"--bogus-flag", "127.0.0.1", "/file.iso"}, + {"127.0.0.1", "/file.iso", "extra-arg"}, + } + + for _, flags := range invalidArgs { + code, exited := runWithExitCapture(func() { + handlePull(context.Background(), flags) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for pull error %v, got %d", flags, code) + } + } +} + +func TestHandleAppliance_ComprehensiveFlags(t *testing.T) { + tmpDir := t.TempDir() + certFile := filepath.Join(tmpDir, "cert.pem") + keyFile := filepath.Join(tmpDir, "key.pem") + idFile := filepath.Join(tmpDir, "id_rsa") + qkviewFile := filepath.Join(tmpDir, "test.qkview") + createMockQKViewArchive(t, qkviewFile) + os.WriteFile(certFile, []byte("cert"), 0600) + os.WriteFile(keyFile, []byte("key"), 0600) + os.WriteFile(idFile, []byte("id"), 0600) + + // TargetKind aliases + for _, kind := range []string{"device", "appliance", "bigiq", "big-iq", "bigip", "big-ip"} { + handleAppliance(context.Background(), kind, []string{"info", qkviewFile}) + } + + // Flag parsing variations on valid qkview info + applianceFlags := [][]string{ + {"info", qkviewFile, "--user", "admin", "-p", "443", "-m", "auto", "-d", "/tmp", "-i", idFile, "--cert", certFile, "--cert-key", keyFile, "--keep-remote", "--apply-geoip", "--keep-extracted", "--json"}, + {"info", qkviewFile, "--user=admin", "--port=443", "--method=ssh", "--dest=/tmp", "--identity=" + idFile, "--cert=" + certFile, "--key-file=" + keyFile, "--no-delete"}, + {"info", qkviewFile, "-u", "admin", "-o", "/tmp", "--output=/tmp", "--cert-key=" + keyFile, "--no-cleanup", "--geoip"}, + {"info", "--", qkviewFile}, + } + + for _, args := range applianceFlags { + handleAppliance(context.Background(), "BIG-IP", args) + } + + // Invalid ports + for _, portFlag := range []string{"-p", "--port="} { + code, exited := runWithExitCapture(func() { + if portFlag == "-p" { + handleAppliance(context.Background(), "BIG-IP", []string{"info", qkviewFile, "-p", "invalid-port"}) + } else { + handleAppliance(context.Background(), "BIG-IP", []string{"info", qkviewFile, "--port=invalid-port"}) + } + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for invalid appliance port %s", portFlag) + } + } + + // Extra argument validations + extraArgsTests := [][]string{ + {"ready", "127.0.0.1", "extra"}, + {"info", qkviewFile, "extra"}, + {"serial", qkviewFile, "extra"}, + {"push", "127.0.0.1"}, + {"download", "127.0.0.1"}, + {"geoip", "127.0.0.1"}, + {"qkview"}, + {"qkview", "127.0.0.1", "extra"}, + } + + for _, args := range extraArgsTests { + code, exited := runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", args) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for appliance extra/missing args %v, got %d", args, code) + } + } +} + +func TestHandleDownloads_FlagsAndBrowse(t *testing.T) { + // Browse command requires terminal TTY + code, exited := runWithExitCapture(func() { + handleDownloads(context.Background(), []string{"browse"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for downloads browse non-TTY, got %d", code) + } + + // Flag variations parsing with missing target + flagVariations := [][]string{ + {"lines", "-o", "/tmp", "--profile", "custom", "--push", "127.0.0.1", "--push-method", "icontrol", "--push-dest", "/tmp", "--push-user", "admin", "--push-port", "443", "--push-target", "BIG-IP", "--push-cert", "/tmp/cert", "--push-cert-key", "/tmp/key", "--push-apply-geoip", "--push-keep-extracted"}, + {"lines", "-o=/tmp", "--output=/tmp", "--profile=custom", "--push=127.0.0.1", "--push-method=scp", "--push-dest=/tmp", "--push-user=admin", "--push-port=443", "--push-target=BIG-IQ", "--push-cert=/tmp/c", "--push-cert-key=/tmp/k"}, + } + + for _, args := range flagVariations { + code, exited := runWithExitCapture(func() { + handleDownloads(context.Background(), args) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for downloads flags %v, got %d", args, code) + } + } +} + +func TestHandleCaseCreate_Advanced(t *testing.T) { + qkviewFile := filepath.Join(t.TempDir(), "test.qkview") + createMockQKViewArchive(t, qkviewFile) + + // Dry run with --from-appliance / --from-device / --from-bigip / --from-bigiq pointing to local qkview + for _, flag := range []string{"--from-appliance", "--from-device", "--from-bigip", "--from-bigiq"} { + code, exited := runWithExitCapture(func() { + handleCaseCreate(context.Background(), nil, []string{ + "--dry-run", + flag, qkviewFile, + "--priority", "3", + "--reason", "Configuration Assistance", + "--subject", "Advance dry run test", + "--description", "Testing appliance detection in case create", + "--email", "admin@corp.test", + "--contact-method", "Phone", + "--timezone", "UTC", + "--hostname", "bigip01.corp", + "--customer-ticket", "INC-8888", + }) + }) + if exited && code != 0 { + t.Errorf("expected dry run with %s to succeed, got %d", flag, code) + } + } + + // Dry run for NGINX with subscriptionId + code, exited := runWithExitCapture(func() { + handleCaseCreate(context.Background(), nil, []string{ + "--dry-run", + "--family", "NGINX", + "--product", "NGINX Plus", + "--version", "R30", + "--subscription", "A-S00038458", + "--priority", "2", + "--reason", "Software Bug", + "--subject", "NGINX upstream crash", + "--description", "Core dump analysis needed", + "--email", "user@example.com", + "--timezone", "UTC", + }) + }) + if exited && code != 0 { + t.Errorf("expected NGINX dry-run to succeed, got %d", code) + } +} + +func TestWizardEditField_DetailedBranches(t *testing.T) { + opts := &CaseWizardOptions{ + ProductFamily: "BIG-IP", + Product: "BIG-IP LTM", + Version: "15.1.8", // triggers EOL warning + } + + // Field 3 EOL warning branch + var buf bytes.Buffer + _ = editWizardField(bufio.NewReader(strings.NewReader("15.1.8\n")), &buf, 3, opts) + if !strings.Contains(buf.String(), "End of Life") { + t.Errorf("expected EOL warning in field 3 edit output") + } + + // Field 5 (Priority) back command + _ = editWizardField(bufio.NewReader(strings.NewReader("b\n")), &buf, 5, opts) + + // Field 5 (Priority) all choices + for _, p := range []string{"1\n", "2\n", "3\n", "4\n"} { + _ = editWizardField(bufio.NewReader(strings.NewReader(p)), &buf, 5, opts) + } + + // Field 6 (Reason) back command + _ = editWizardField(bufio.NewReader(strings.NewReader("b\n")), &buf, 6, opts) + + // Field 6 (Reason) all choices + for _, r := range []string{"1\n", "2\n", "3\n", "4\n", "5\n"} { + _ = editWizardField(bufio.NewReader(strings.NewReader(r)), &buf, 6, opts) + } + + // Field 8 (Description) multiline buffer with line and end + descInput := "First description line\nSecond description line\n.\n" + _ = editWizardField(bufio.NewReader(strings.NewReader(descInput)), &buf, 8, opts) + + // Nav back on fields 10, 11, 12, 13 + for _, f := range []int{10, 11, 12, 13} { + _ = editWizardField(bufio.NewReader(strings.NewReader("b\n")), &buf, f, opts) + } +} + +func TestRunStep1AutoDetection_EdgeCases(t *testing.T) { + opts := &CaseWizardOptions{} + + // Option ':b' (back from step 1) -> returns step 1, nil + step, err := runStep1AutoDetection(context.Background(), bufio.NewReader(strings.NewReader("b\n")), &bytes.Buffer{}, opts) + if err != nil || step != 1 { + t.Errorf("expected step 1 on back, got step=%d err=%v", step, err) + } + + // Option 1 with back on host prompt -> advances to step 2 + step, err = runStep1AutoDetection(context.Background(), bufio.NewReader(strings.NewReader("1\nb\n")), &bytes.Buffer{}, opts) + if err != nil || step != 2 { + t.Errorf("expected step 2 on option 1 host back, got step=%d err=%v", step, err) + } + + // Option 2 with invalid qkview file -> prints error and advances to step 2 + step, err = runStep1AutoDetection(context.Background(), bufio.NewReader(strings.NewReader("2\n/nonexistent/bad.qkview\n")), &bytes.Buffer{}, opts) + if err != nil || step != 2 { + t.Errorf("expected step 2 on option 2 bad qkview, got step=%d err=%v", step, err) + } + + // Option 2 with back on qkview prompt -> advances to step 2 + step, err = runStep1AutoDetection(context.Background(), bufio.NewReader(strings.NewReader("2\nb\n")), &bytes.Buffer{}, opts) + if err != nil || step != 2 { + t.Errorf("expected step 2 on option 2 back, got step=%d err=%v", step, err) + } +} + +func TestSubcommandAliasesAndInteractive(t *testing.T) { + // Aliases in executeSubcommand + aliases := []struct { + cmd string + args []string + }{ + {"download", []string{}}, + {"case", []string{}}, + {"upload", []string{}}, + {"fetch", []string{}}, + {"sysinfo", []string{}}, + {"system-info", []string{}}, + {"sn", []string{}}, + {"serialnumber", []string{}}, + {"interactive", []string{}}, + {"shell", []string{}}, + {"repl", []string{}}, + {"i", []string{}}, + } + + for _, a := range aliases { + code, exited := runWithExitCapture(func() { + executeSubcommand(context.Background(), a.cmd, a.args) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for subcommand alias %s, got %d", a.cmd, code) + } + } +} + +func TestHandleCases_AdditionalBranches(t *testing.T) { + // wizard / new action with cancel input in Step 5 + cancelLines := []string{ + "3", // Step 1: skip auto-detect + "", // Step 2: Product family (default) + "", // Product (default) + "", // Version (default) + "sn-test-12345", // Serial number + "4", // Step 3: Priority 4 + "1", // Reason 1 + "Cancel test", // Subject + "Testing cancel\n.", // Description + "user@example.com", // Step 4: Email + "", // Contact Method (default) + "", // Timezone (default) + "", // Hostname + "", // Ticket Ref + "c", // Step 5: Cancel + } + + origStdin := os.Stdin + rPipe, wPipe, _ := os.Pipe() + for _, l := range cancelLines { + wPipe.WriteString(l + "\n") + } + wPipe.Close() + os.Stdin = rPipe + defer func() { os.Stdin = origStdin }() + + code, exited := runWithExitCapture(func() { + handleCases(context.Background(), []string{"wizard"}) + }) + if exited && code != 0 { + t.Errorf("expected wizard to handle cancel gracefully, got %d", code) + } + + // create action via handleCases dispatching to handleCaseCreate + code, exited = runWithExitCapture(func() { + handleCases(context.Background(), []string{"create", "--help"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 when no creds for create, got %d", code) + } + + // Actions requiring authentication when no credentials present + for _, action := range []string{"list", "metadata"} { + code, exited = runWithExitCapture(func() { + handleCases(context.Background(), []string{action}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for handleCases %s without creds, got %d", action, code) + } + } + + // With credentials set, authentication fails cleanly + os.Setenv("F5_CLIENT_ID", "dummy-id") + os.Setenv("F5_CLIENT_SECRET", "dummy-secret") + defer func() { + os.Unsetenv("F5_CLIENT_ID") + os.Unsetenv("F5_CLIENT_SECRET") + }() + + for _, action := range []string{"list", "metadata"} { + code, exited = runWithExitCapture(func() { + handleCases(context.Background(), []string{action}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for handleCases %s with failing auth, got %d", action, code) + } + } +} + +func TestHandleDownloads_AuthBranches(t *testing.T) { + // With credentials set, calling families/lines/versions/containers/files triggers getDownloadsClient + os.Setenv("F5_CLIENT_ID", "dummy-id") + os.Setenv("F5_CLIENT_SECRET", "dummy-secret") + defer func() { + os.Unsetenv("F5_CLIENT_ID") + os.Unsetenv("F5_CLIENT_SECRET") + }() + + downloadsActions := [][]string{ + {"families"}, + {"lines", "BIG-IP"}, + {"versions", "BIG-IP", "BIG-IP LTM"}, + {"containers", "BIG-IP", "BIG-IP LTM"}, + {"files", "BIG-IP", "BIG-IP LTM"}, + {"get", "BIG-IP", "BIG-IP LTM", "17.5.1", "Base ISO", "test.iso"}, + } + + for _, args := range downloadsActions { + code, exited := runWithExitCapture(func() { + handleDownloads(context.Background(), args) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for handleDownloads %v with failing auth, got %d", args, code) + } + } +} + +func TestHandleIHealth_AuthBranches(t *testing.T) { + // With credentials set, list triggers authentication + os.Setenv("F5_CLIENT_ID", "dummy-id") + os.Setenv("F5_CLIENT_SECRET", "dummy-secret") + defer func() { + os.Unsetenv("F5_CLIENT_ID") + os.Unsetenv("F5_CLIENT_SECRET") + }() + + code, exited := runWithExitCapture(func() { + handleIHealth(context.Background(), []string{"list"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for ihealth list with failing auth, got %d", code) + } +} + +func TestSelector_EdgeCases(t *testing.T) { + // TruncateRunes with small limit <= 3 returns s unchanged + if got := truncateRunes("Hello", 2); got != "Hello" { + t.Errorf("expected 'Hello', got %q", got) + } + if got := truncateRunes("Hello", 3); got != "Hello" { + t.Errorf("expected 'Hello', got %q", got) + } + // TruncateRunes with length > maxRunes > 3 + if got := truncateRunes("Hello World", 8); got != "Hello..." { + t.Errorf("expected 'Hello...', got %q", got) + } + + // SelectMenu default index normalization + items := []SelectItem{{ID: "1", Title: "One"}} + rPipe, wPipe, _ := os.Pipe() + go func() { + wPipe.WriteString("1\n") + wPipe.Close() + }() + idx, _, err := SelectMenu(SelectConfig{ + Items: items, + In: rPipe, + DefaultIndex: -10, // will normalize to 0 + }) + rPipe.Close() + if err != nil || idx != 0 { + t.Errorf("expected index 0 after normalization, got %d (err: %v)", idx, err) + } + + rPipe2, wPipe2, _ := os.Pipe() + go func() { + wPipe2.WriteString("1\n") + wPipe2.Close() + }() + idx2, _, err2 := SelectMenu(SelectConfig{ + Items: items, + In: rPipe2, + DefaultIndex: 50, // will normalize to 0 + }) + rPipe2.Close() + if err2 != nil || idx2 != 0 { + t.Errorf("expected index 0 after normalization, got %d (err: %v)", idx2, err2) + } +} + +type mockRoundTripper func(req *http.Request) (*http.Response, error) + +func (m mockRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + return m(req) +} + +func TestRunInteractiveBrowser_Coverage(t *testing.T) { + // 1. Error fetching metadata + failClient := downloads.NewClientWithKey("token", "https://downloads.test", "key") + failClient.HTTPClient = &http.Client{ + Transport: mockRoundTripper(func(req *http.Request) (*http.Response, error) { + return nil, errors.New("network dial failure") + }), + } + code, exited := runWithExitCapture(func() { + runInteractiveBrowser(context.Background(), failClient) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on metadata fetch error, got %d", code) + } + + // 2. Canceled context on metadata + canceledCtx, cancel := context.WithCancel(context.Background()) + cancel() + code, exited = runWithExitCapture(func() { + runInteractiveBrowser(canceledCtx, failClient) + }) + if !exited || code != 130 { + t.Errorf("expected exit 130 on canceled context, got %d", code) + } + + // 3. Successful metadata and navigation + mockClient := downloads.NewClientWithKey("token", "https://downloads.test", "key") + mockClient.HTTPClient = &http.Client{ + Transport: mockRoundTripper(func(req *http.Request) (*http.Response, error) { + path := req.URL.Path + if strings.Contains(path, "/metadata") { + metaJSON := `{ + "data": { + "productFamilies": [ + { + "name": "BIG-IP", + "displayName": "BIG-IP Platforms", + "productLines": [ + { + "name": "BIG-IP v17.x", + "displayName": "Version 17" + } + ] + } + ] + } + }` + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(metaJSON)), + Header: make(http.Header), + }, nil + } + if strings.Contains(path, "BIGIP-17.5.1.iso") { + linksJSON := `{ + "downloadLinks": [ + { + "href": "https://cdn.example.com/BIGIP-17.5.1.iso", + "region": "US East" + } + ] + }` + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(linksJSON)), + Header: make(http.Header), + }, nil + } + if strings.Contains(path, "/product/BIG-IP/") { + verJSON := `{ + "data": { + "productVersions": [ + { + "name": "17.5.1", + "releaseDate": "2024-01-01", + "containers": [ + { + "name": "Base ISO", + "files": [ + { + "name": "BIGIP-17.5.1.iso", + "fileSize": 1048576 + } + ] + } + ] + } + ] + } + }` + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(verJSON)), + Header: make(http.Header), + }, nil + } + return &http.Response{ + StatusCode: http.StatusNotFound, + Body: io.NopCloser(strings.NewReader(`{}`)), + Header: make(http.Header), + }, nil + }), + } + + // Navigate: + // Select family 1 -> Select line 1 -> Select version 1 -> Select category 1 -> Select file 1 -> decline 'n' -> 'b' back to category -> 'b' back to version -> 'b' back to line -> 'b' back to family -> 'q' quit + navInput := "1\n1\n1\n1\n1\nn\nb\nb\nb\nb\nq\n" + origStdin := os.Stdin + rPipe, wPipe, _ := os.Pipe() + wPipe.WriteString(navInput) + wPipe.Close() + os.Stdin = rPipe + defer func() { os.Stdin = origStdin }() + + runInteractiveBrowser(context.Background(), mockClient) +} + +func TestGetSystemInfoTarget_ApplianceBranch(t *testing.T) { + code, exited := runWithExitCapture(func() { + getSystemInfoTarget(context.Background(), "127.0.0.1", "BIG-IP", "admin", 1, "", "auto", "", "") + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for getSystemInfoTarget on unreachable host, got %d", code) + } +} + +func TestExecutePushAndDownload_AdditionalBranches(t *testing.T) { + tmpFile := filepath.Join(t.TempDir(), "upload.txt") + os.WriteFile(tmpFile, []byte("data"), 0600) + + canceledCtx, cancel := context.WithCancel(context.Background()) + cancel() + + // Push with canceled context -> exit 130 + code, exited := runWithExitCapture(func() { + executePushToAppliance(canceledCtx, "127.0.0.1", tmpFile, "icontrol", "/tmp", "admin", 1, "", "BIG-IP", "", "", false, false, false) + }) + if !exited || code != 130 { + t.Errorf("expected exit 130 on canceled push, got %d", code) + } + + // Download with canceled context -> exit 130 + code, exited = runWithExitCapture(func() { + executeDownloadFromAppliance(canceledCtx, "127.0.0.1", "/shared/file.iso", "", "icontrol", "admin", 1, "", "BIG-IP", "", "") + }) + if !exited || code != 130 { + t.Errorf("expected exit 130 on canceled download, got %d", code) + } + + // Push with empty method and targetKind (tests default fallbacks) + code, exited = runWithExitCapture(func() { + executePushToAppliance(context.Background(), "127.0.0.1", tmpFile, "", "", "admin", 1, "", "", "", "", false, false, false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on default push to closed port, got %d", code) + } + + // Download with empty method and targetKind (tests default fallbacks) + code, exited = runWithExitCapture(func() { + executeDownloadFromAppliance(context.Background(), "127.0.0.1", "/shared/file.iso", "", "", "admin", 1, "", "", "", "") + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on default download to closed port, got %d", code) + } + + // Download with method="ssh" (tests method="scp" normalization) + code, exited = runWithExitCapture(func() { + executeDownloadFromAppliance(context.Background(), "127.0.0.1", "/shared/file.iso", "", "ssh", "admin", 1, "", "BIG-IP", "", "") + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on ssh method download, got %d", code) + } + + // Push with method="ssh" (tests method="scp" normalization) + code, exited = runWithExitCapture(func() { + executePushToAppliance(context.Background(), "127.0.0.1", tmpFile, "ssh", "/tmp", "admin", 1, "", "BIG-IP", "", "", false, false, false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on ssh method push, got %d", code) + } + + // Push with applyGeoIP=true and default destPath="" (tests destPath="/var/tmp" default) + code, exited = runWithExitCapture(func() { + executePushToAppliance(context.Background(), "127.0.0.1", tmpFile, "icontrol", "", "admin", 1, "", "BIG-IP", "", "", true, false, false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on geoip push to closed port, got %d", code) + } +} + +func TestHandleAppliance_QKViewAndSerialEdgeCases(t *testing.T) { + // 1. QKView with closed port and icontrol + code, exited := runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"qkview", "127.0.0.1", "--method", "icontrol", "--port", "1"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for qkview icontrol to closed port, got %d", code) + } + + // 2. QKView with closed port and scp + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"qkview", "127.0.0.1", "--method", "scp", "--port", "1"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for qkview scp to closed port, got %d", code) + } + + // 3. QKView with invalid method + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"qkview", "127.0.0.1", "--method", "invalid-qkview-method", "--port", "1"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for qkview invalid method, got %d", code) + } + + // 4. Serial on QKView without serial number + noSnQkview := filepath.Join(t.TempDir(), "nosn.qkview") + var buf bytes.Buffer + gw := gzip.NewWriter(&buf) + tw := tar.NewWriter(gw) + hdr := &tar.Header{Name: "VERSION", Mode: 0600, Size: 26} + tw.WriteHeader(hdr) + tw.Write([]byte("Product: BIG-IP\nVersion: 17\n")) + tw.Close() + gw.Close() + os.WriteFile(noSnQkview, buf.Bytes(), 0600) + + code, exited = runWithExitCapture(func() { + handleAppliance(context.Background(), "BIG-IP", []string{"serial", noSnQkview}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 for qkview without serial, got %d", code) + } +} + +func TestHandleCaseCreate_MockClientResponses(t *testing.T) { + // 1. API returns error (isError=true) + mockClientErr := cases.NewClientWithKey("token", "https://cases.test", "key") + mockClientErr.HTTPClient = &http.Client{ + Transport: mockRoundTripper(func(req *http.Request) (*http.Response, error) { + res := `{ + "isError": true, + "message": "account entitlement expired" + }` + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(res)), + Header: make(http.Header), + }, nil + }), + } + args := []string{ + "--family", "BIG-IP", + "--product", "BIG-IP LTM", + "--version", "17.5.1", + "--serial", "test-12345", + "--priority", "4", + "--reason", "General Problem", + "--subject", "Test issue", + "--description", "Desc", + "--email", "user@test.corp", + "--timezone", "UTC", + } + code, exited := runWithExitCapture(func() { + handleCaseCreate(context.Background(), mockClientErr, args) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on case create API error response, got %d", code) + } + + // 2. API returns success with case number + mockClientSuccess := cases.NewClientWithKey("token", "https://cases.test", "key") + mockClientSuccess.HTTPClient = &http.Client{ + Transport: mockRoundTripper(func(req *http.Request) (*http.Response, error) { + res := `{ + "isError": false, + "data": { + "caseNumber": "C-998877" + } + }` + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(res)), + Header: make(http.Header), + }, nil + }), + } + handleCaseCreate(context.Background(), mockClientSuccess, args) + + // 3. API returns success with no case number + mockClientNoNum := cases.NewClientWithKey("token", "https://cases.test", "key") + mockClientNoNum.HTTPClient = &http.Client{ + Transport: mockRoundTripper(func(req *http.Request) (*http.Response, error) { + res := `{ + "isError": false, + "data": {} + }` + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(res)), + Header: make(http.Header), + }, nil + }), + } + handleCaseCreate(context.Background(), mockClientNoNum, args) +} + +func TestMainAndRunMain(t *testing.T) { + origArgs := os.Args + defer func() { os.Args = origArgs }() + + // Test main() with version + os.Args = []string{"myf5", "version"} + main() + + // Test runMain with security error (--password) + code, exited := runWithExitCapture(func() { + runMain([]string{"myf5", "--password", "secret"}) + }) + if !exited || code != 2 { + t.Errorf("expected exit 2 on secret flag, got %d", code) + } + + // Test runMain with invalid proxy + code, exited = runWithExitCapture(func() { + runMain([]string{"myf5", "--proxy", "invalid proxy with space", "version"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on bad proxy, got %d", code) + } + + // Test runMain with empty args -> usage + code, exited = runWithExitCapture(func() { + runMain([]string{"myf5"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on empty args, got %d", code) + } +} + +func TestStartInteractiveFullSession(t *testing.T) { + origIsTerm := isTerminalFunc + origMakeRaw := makeRawFunc + origRestore := restoreTerminalFunc + origIn := interactiveIn + origOut := interactiveOut + defer func() { + isTerminalFunc = origIsTerm + makeRawFunc = origMakeRaw + restoreTerminalFunc = origRestore + interactiveIn = origIn + interactiveOut = origOut + }() + + // 1. Terminal mode: enter commands, empty line, clear, and quit + isTerminalFunc = func(fd int) bool { return true } + makeRawFunc = func(fd int) (*term.State, error) { return &term.State{}, nil } + restoreTerminalFunc = func(fd int, s *term.State) error { return nil } + + interactiveIn = strings.NewReader("help\nversion\n \nclear\nexit\n") + var outBuf bytes.Buffer + interactiveOut = &outBuf + + startInteractive() + + // 2. Terminal mode: makeRaw error branch + makeRawFunc = func(fd int) (*term.State, error) { return nil, errors.New("cannot make raw") } + startInteractive() + + // 3. Non-terminal error branch + isTerminalFunc = func(fd int) bool { return false } + code, exited := runWithExitCapture(func() { + startInteractive() + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on non-terminal, got %d", code) + } +} + +func TestRunStep1AutoDetectionOptions(t *testing.T) { + ctx := context.Background() + qkviewFile := filepath.Join(t.TempDir(), "autodetect.qkview") + createMockQKViewArchive(t, qkviewFile) + + // Option 1: connect to host (using mock qkview path which getSystemInfoTarget supports) + var out1 bytes.Buffer + in1 := bufio.NewReader(strings.NewReader("1\n" + qkviewFile + "\nadmin\n")) + opts1 := &CaseWizardOptions{} + step1, err := runStep1AutoDetection(ctx, in1, &out1, opts1) + if err != nil { + t.Errorf("unexpected err: %v", err) + } + if step1 != 2 { + t.Errorf("expected step 2, got %d", step1) + } + if opts1.SerialNumber != "test-serial-999" { + t.Errorf("expected SerialNumber=test-serial-999, got %q", opts1.SerialNumber) + } + + // Option 2: local qkview (with empty or invalid path) + var out bytes.Buffer + in2 := bufio.NewReader(strings.NewReader("2\n/nonexistent/file.qkview\n")) + opts2 := &CaseWizardOptions{} + step, err := runStep1AutoDetection(ctx, in2, &out, opts2) + if err != nil { + t.Errorf("unexpected err: %v", err) + } + if step != 2 { + t.Errorf("expected step 2, got %d", step) + } + + // Back error navigation + inBack := bufio.NewReader(strings.NewReader("b\n")) + step, err = runStep1AutoDetection(ctx, inBack, &out, opts2) + if err != nil { + t.Errorf("unexpected err: %v", err) + } + if step != 1 { + t.Errorf("expected step 1 on back, got %d", step) + } +} + +func TestExecutePushToApplianceBranches(t *testing.T) { + ctx := context.Background() + + // 1. Invalid method + code, exited := runWithExitCapture(func() { + executePushToAppliance(ctx, "10.0.0.1", "test.iso", "invalid-method", "", "admin", 443, "", "BIG-IP", "", "", false, false, false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on invalid method, got %d", code) + } + + // 2. applyGeoIP on BIG-IQ + code, exited = runWithExitCapture(func() { + executePushToAppliance(ctx, "10.0.0.1", "test.iso", "auto", "", "admin", 443, "", "BIG-IQ", "", "", true, false, false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on BIG-IQ geoip push, got %d", code) + } + + // 3. Local file does not exist + code, exited = runWithExitCapture(func() { + executePushToAppliance(ctx, "10.0.0.1", "/nonexistent/path/file.iso", "auto", "", "admin", 443, "", "BIG-IP", "", "", false, false, false) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on missing file, got %d", code) + } + + // 4. File exists, transfer failure with json output + tmpFile := filepath.Join(t.TempDir(), "test.iso") + _ = os.WriteFile(tmpFile, []byte("dummy-data"), 0600) + code, exited = runWithExitCapture(func() { + executePushToAppliance(ctx, "127.0.0.1", tmpFile, "auto", "", "admin", 65530, "", "BIG-IP", "", "", false, false, true) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on failed push with json, got %d", code) + } + + // 5. File exists, transfer canceled context + cancelCtx, cancel := context.WithCancel(context.Background()) + cancel() + code, exited = runWithExitCapture(func() { + executePushToAppliance(cancelCtx, "127.0.0.1", tmpFile, "auto", "", "admin", 65530, "", "BIG-IP", "", "", false, false, false) + }) + if !exited || (code != 1 && code != 130) { + t.Errorf("expected exit 1 or 130 on canceled push, got %d", code) + } +} + +func TestExecutePushToApplianceSuccess(t *testing.T) { + mockMux := http.NewServeMux() + mockMux.HandleFunc("/mgmt/tm/sys/ready", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"kind": "tm:sys:ready"}`)) + }) + mockMux.HandleFunc("/mgmt/tm/sys/version", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + }) + mockMux.HandleFunc("/mgmt/shared/file-transfer/uploads/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"localFilePath": "/var/config/rest/downloads/test.iso"}`)) + }) + mockMux.HandleFunc("/mgmt/tm/util/bash", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"commandResult": "success"}`)) + }) + + dialer := func(ctx context.Context, network, addr string) (net.Conn, error) { + c1, c2 := net.Pipe() + go func() { + req, err := http.ReadRequest(bufio.NewReader(c2)) + if err != nil { + c2.Close() + return + } + rec := httptest.NewRecorder() + mockMux.ServeHTTP(rec, req) + resp := rec.Result() + _ = resp.Write(c2) + c2.Close() + }() + return c1, nil + } + + client.SetDialContext(dialer) + defer client.SetDialContext(nil) + + tmpFile := filepath.Join(t.TempDir(), "test.iso") + _ = os.WriteFile(tmpFile, []byte("iso data"), 0600) + + t.Setenv("BIGIP_PASSWORD", "secret") + ctx := context.Background() + + // 1. Success without json + executePushToAppliance(ctx, "http://127.0.0.1", tmpFile, "icontrol", "/shared/images", "admin", 80, "", "BIG-IP", "", "", false, false, false) + + // 2. Success with json + executePushToAppliance(ctx, "http://127.0.0.1", tmpFile, "icontrol", "/shared/images", "admin", 80, "", "BIG-IP", "", "", false, false, true) +} + +func TestHandleCasesUsageAndErrors(t *testing.T) { + ctx := context.Background() + + // Empty args -> usage + code, exited := runWithExitCapture(func() { + handleCases(ctx, []string{}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on empty handleCases args, got %d", code) + } + + // Missing credentials + code, exited = runWithExitCapture(func() { + handleCases(ctx, []string{"list"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on missing creds for list, got %d", code) + } +} + +func TestHandleIHealthUsageAndErrors(t *testing.T) { + ctx := context.Background() + + // Empty args -> usage + code, exited := runWithExitCapture(func() { + handleIHealth(ctx, []string{}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on empty handleIHealth args, got %d", code) + } + + // Missing credentials + code, exited = runWithExitCapture(func() { + handleIHealth(ctx, []string{"list"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on missing creds for ihealth, got %d", code) + } +} + +func TestHandleCasesWithMockServer(t *testing.T) { + mockMux := http.NewServeMux() + mockMux.HandleFunc("/oauth/token", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "access_token": "mock-token-xyz", + "token_type": "Bearer", + "expires_in": 3600, + }) + }) + mockMux.HandleFunc("/case-management/v1/cases", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "isError": false, + "data": []map[string]any{ + { + "caseNumber": "C-12345", + "status": "Open", + "priority": "3 - Standard", + "subject": "Test Support Case", + }, + }, + }) + }) + mockMux.HandleFunc("/case-management/v1/cases/metadata", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "isError": false, + "data": map[string]any{ + "rootKey": "rootVal", + }, + }) + }) + mockMux.HandleFunc("/case-management/v1/cases/C-12345", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodPatch { + _ = json.NewEncoder(w).Encode(map[string]any{ + "isError": false, + "data": map[string]any{ + "caseNumber": "C-12345", + "updatedDate": "2026-11-16T12:00:00Z", + }, + }) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "isError": false, + "data": []map[string]any{ + { + "caseNumber": "C-12345", + "status": "Open", + "priority": "3 - Standard", + "subject": "Test Support Case", + }, + }, + }) + }) + + dialer := func(ctx context.Context, network, addr string) (net.Conn, error) { + c1, c2 := net.Pipe() + go func() { + req, err := http.ReadRequest(bufio.NewReader(c2)) + if err != nil { + c2.Close() + return + } + rec := httptest.NewRecorder() + mockMux.ServeHTTP(rec, req) + resp := rec.Result() + _ = resp.Write(c2) + c2.Close() + }() + return c1, nil + } + + client.SetDialContext(dialer) + defer client.SetDialContext(nil) + + t.Setenv("F5_CLIENT_ID", "test-client") + t.Setenv("F5_CLIENT_SECRET", "test-secret") + t.Setenv("F5_AUTH_FQDN", "http://auth.test") + t.Setenv("F5_SUPPORT_FQDN", "http://cases.test") + + ctx := context.Background() + + // 1. handleCases list (open cases) + handleCases(ctx, []string{"list"}) + + // 2. handleCases list --all (open & closed) + handleCases(ctx, []string{"list", "--all"}) + + // 3. handleCases metadata + handleCases(ctx, []string{"metadata"}) + + // 4. handleCases get + handleCases(ctx, []string{"get", "C-12345"}) + + // 5. handleCases comment + handleCases(ctx, []string{"comment", "C-12345", "test comment note"}) +} + +func TestHandleIHealthWithMockServer(t *testing.T) { + mockMux := http.NewServeMux() + mockMux.HandleFunc("/oauth/token", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "access_token": "mock-ihealth-token", + "token_type": "Bearer", + "expires_in": 3600, + }) + }) + mockMux.HandleFunc("/qkview-analyzer/api/qkviews", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/vnd.f5.ihealth.api+json") + if r.Method == http.MethodPost { + _, _ = w.Write([]byte(`{"id":"26894783","processing_status":"COMPLETE"}`)) + return + } + _, _ = w.Write([]byte(`{"id":["26894783"]}`)) + }) + mockMux.HandleFunc("/qkview-analyzer/api/qkviews/26894783", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/vnd.f5.ihealth.api+json") + _, _ = w.Write([]byte(`{"file_name":"test_diag.qkview","hostname":"host.example","gui_uri":"https://ihealth.f5.com/qkview-analyzer/qv/26894783","f5_support_case":"","processing_status":"COMPLETE","file_size":43928363,"upload":{"date":1789750903000}}`)) + }) + + dialer := func(ctx context.Context, network, addr string) (net.Conn, error) { + c1, c2 := net.Pipe() + go func() { + req, err := http.ReadRequest(bufio.NewReader(c2)) + if err != nil { + c2.Close() + return + } + rec := httptest.NewRecorder() + mockMux.ServeHTTP(rec, req) + resp := rec.Result() + _ = resp.Write(c2) + c2.Close() + }() + return c1, nil + } + + client.SetDialContext(dialer) + defer client.SetDialContext(nil) + + t.Setenv("IHEALTH_CLIENT_ID", "test-ihealth-client") + t.Setenv("IHEALTH_CLIENT_SECRET", "test-ihealth-secret") + t.Setenv("F5_AUTH_FQDN", "http://auth.test") + t.Setenv("F5_IHEALTH_FQDN", "http://ihealth.test") + + ctx := context.Background() + + // 1. handleIHealth list + handleIHealth(ctx, []string{"list"}) + + // 2. handleIHealth upload with no args -> exit 1 + code, exited := runWithExitCapture(func() { + handleIHealth(ctx, []string{"upload"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on empty upload args, got %d", code) + } + + // 3. handleIHealth upload missing file -> exit 1 + code, exited = runWithExitCapture(func() { + handleIHealth(ctx, []string{"upload", "/nonexistent/path/f.qkview"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on missing file upload, got %d", code) + } + + // 4. handleIHealth upload valid file -> success + tmpQkview := filepath.Join(t.TempDir(), "test.qkview") + _ = os.WriteFile(tmpQkview, []byte("fake-qkview"), 0600) + handleIHealth(ctx, []string{"upload", tmpQkview, "C-12345", "test description"}) + + // 5. handleIHealth unknown action -> exit 1 + code, exited = runWithExitCapture(func() { + handleIHealth(ctx, []string{"unknown"}) + }) + if !exited || code != 1 { + t.Errorf("expected exit 1 on unknown action, got %d", code) + } +} diff --git a/cmd/myf5/interactive.go b/cmd/myf5/interactive.go index cacf8f3..8b632e1 100644 --- a/cmd/myf5/interactive.go +++ b/cmd/myf5/interactive.go @@ -19,15 +19,20 @@ type exitPanic struct { code int } -// exitFunc is the process termination function, replaced during interactive mode -// so failed commands return to the shell prompt instead of exiting the process. -var exitFunc = os.Exit +var ( + exitFunc = os.Exit + isTerminalFunc = term.IsTerminal + makeRawFunc = term.MakeRaw + restoreTerminalFunc = term.Restore + interactiveIn io.Reader = os.Stdin + interactiveOut io.Writer = os.Stdout +) // startInteractive launches the interactive CLI shell with command history // and tab-completion. func startInteractive() { fd := int(os.Stdin.Fd()) - if !term.IsTerminal(fd) { + if !isTerminalFunc(fd) { fmt.Fprintln(os.Stderr, "[ERROR] Interactive mode requires a terminal TTY.") exitFunc(1) return @@ -50,7 +55,7 @@ func startInteractive() { for { // Put terminal in raw mode for line editing, history, and tab completion - oldState, err := term.MakeRaw(fd) + oldState, err := makeRawFunc(fd) if err != nil { fmt.Fprintf(os.Stderr, "[ERROR] Failed to set raw terminal: %v\n", err) return @@ -59,7 +64,7 @@ func startInteractive() { terminal := term.NewTerminal(struct { io.Reader io.Writer - }{os.Stdin, os.Stdout}, "myf5> ") + }{interactiveIn, interactiveOut}, "myf5> ") terminal.AutoCompleteCallback = func(line string, pos int, key rune) (string, int, bool) { if key != '\t' { @@ -69,7 +74,7 @@ func startInteractive() { } line, err := terminal.ReadLine() - _ = term.Restore(fd, oldState) + _ = restoreTerminalFunc(fd, oldState) if err != nil { // EOF (Ctrl-D) or terminal closed diff --git a/cmd/myf5/main.go b/cmd/myf5/main.go index 8079c0b..6e6d138 100644 --- a/cmd/myf5/main.go +++ b/cmd/myf5/main.go @@ -33,18 +33,29 @@ import ( const Version = "1.1.0" func main() { + runMain(os.Args) +} + +func runMain(rawArgs []string) { + var argsToInspect []string + if len(rawArgs) > 1 { + argsToInspect = rawArgs[1:] + } + // Enforce Zero-Secret CLI Policy - if err := auth.CheckNoCLISecrets(os.Args[1:]); err != nil { + if err := auth.CheckNoCLISecrets(argsToInspect); err != nil { fmt.Fprintf(os.Stderr, "\n[SECURITY ERROR] %s\n\n", err.Error()) exitFunc(2) + return } // Extract global --proxy flag if present - cleanArgs, proxyFlag := extractProxyFlag(os.Args[1:]) + cleanArgs, proxyFlag := extractProxyFlag(argsToInspect) if proxyFlag != "" { if err := client.SetGlobalProxy(proxyFlag); err != nil { fmt.Fprintf(os.Stderr, "\n[ERROR] Invalid proxy URL: %v\n\n", err) exitFunc(1) + return } } diff --git a/pkg/auth/credentials_test.go b/pkg/auth/credentials_test.go index 8631fa8..6037a8a 100644 --- a/pkg/auth/credentials_test.go +++ b/pkg/auth/credentials_test.go @@ -357,3 +357,22 @@ func TestCredentialsZero(t *testing.T) { nilCreds.Zero() // Must not panic }) } + +func TestCredentialsGoString(t *testing.T) { + c := Credentials{ + ClientID: "test-client", + ClientSecret: "secret-123", + APIKey: "key-456", + Proxy: "http://proxy:8080", + } + gs := c.GoString() + if !strings.Contains(gs, "test-client") { + t.Errorf("GoString missing ClientID: %s", gs) + } + if strings.Contains(gs, "secret-123") || strings.Contains(gs, "key-456") { + t.Errorf("GoString leaked secret: %s", gs) + } + if gs != c.String() { + t.Errorf("GoString() = %q, want String() = %q", gs, c.String()) + } +} diff --git a/pkg/auth/oauth.go b/pkg/auth/oauth.go index bbadabc..89935d1 100644 --- a/pkg/auth/oauth.go +++ b/pkg/auth/oauth.go @@ -67,7 +67,11 @@ func AuthenticateWithClient(ctx context.Context, httpClient *http.Client, authFQ // AuthenticateWithSecretBytes authenticates using a mutable clientSecret byte slice that is scrubbed from memory. func AuthenticateWithSecretBytes(ctx context.Context, httpClient *http.Client, authFQDN, appID, clientID string, clientSecret []byte, scope string) (string, error) { if authFQDN == "" { - authFQDN = DefaultAuthFQDN + if envFQDN := os.Getenv("F5_AUTH_FQDN"); envFQDN != "" { + authFQDN = envFQDN + } else { + authFQDN = DefaultAuthFQDN + } } if appID == "" { appID = DefaultAppID diff --git a/pkg/auth/oauth_test.go b/pkg/auth/oauth_test.go index bee3035..7f67ed2 100644 --- a/pkg/auth/oauth_test.go +++ b/pkg/auth/oauth_test.go @@ -8,8 +8,25 @@ import ( "testing" ) +type roundTripFunc func(req *http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +func newMockServer(handler http.Handler) (*http.Client, string) { + client := &http.Client{ + Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + return rec.Result(), nil + }), + } + return client, "https://mock.auth.f5.invalid" +} + func TestAuthenticate(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { t.Errorf("expected POST, got %s", r.Method) } @@ -28,10 +45,10 @@ func TestAuthenticate(t *testing.T) { } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(resp) - })) - defer server.Close() + }) + mockClient, mockURL := newMockServer(handler) - token, err := AuthenticateWithClient(context.Background(), server.Client(), server.URL, "app123", "client_id", "client_secret", "myf5_scope") + token, err := AuthenticateWithClient(context.Background(), mockClient, mockURL, "app123", "client_id", "client_secret", "myf5_scope") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -59,17 +76,17 @@ func TestAuthenticateAudienceSelection(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { var gotAudience, gotScope string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { t.Fatalf("parse form: %v", err) } gotAudience = r.PostForm.Get("audience") gotScope = r.PostForm.Get("scope") json.NewEncoder(w).Encode(TokenResponse{AccessToken: "tok"}) - })) - defer server.Close() + }) + mockClient, mockURL := newMockServer(handler) - if _, err := AuthenticateWithClient(context.Background(), server.Client(), server.URL, "", "cid", "csec", tc.scope); err != nil { + if _, err := AuthenticateWithClient(context.Background(), mockClient, mockURL, "", "cid", "csec", tc.scope); err != nil { t.Fatalf("unexpected error: %v", err) } if gotAudience != tc.wantAudience { @@ -83,7 +100,7 @@ func TestAuthenticateAudienceSelection(t *testing.T) { } func TestAuthenticateWithSecretBytes(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { authHeader := r.Header.Get("Authorization") if authHeader != "Basic Y2xpZW50X2lkOnNlY3JldF9ieXRlcw==" { // base64 of "client_id:secret_bytes" t.Errorf("unexpected Authorization header: %s", authHeader) @@ -93,11 +110,11 @@ func TestAuthenticateWithSecretBytes(t *testing.T) { AccessToken: "bytes-token-xyz", TokenType: "Bearer", }) - })) - defer server.Close() + }) + mockClient, mockURL := newMockServer(handler) sec := []byte("secret_bytes") - tok, err := AuthenticateWithSecretBytes(context.Background(), server.Client(), server.URL, "app", "client_id", sec, "myf5_scope") + tok, err := AuthenticateWithSecretBytes(context.Background(), mockClient, mockURL, "app", "client_id", sec, "myf5_scope") if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -105,3 +122,12 @@ func TestAuthenticateWithSecretBytes(t *testing.T) { t.Errorf("got token %s, want bytes-token-xyz", tok) } } + +func TestAuthenticateDirect(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err := Authenticate(ctx, "https://invalid.example.com", "app", "cid", "csec", "scope") + if err == nil { + t.Fatal("expected error with canceled context") + } +} diff --git a/pkg/bigip/client.go b/pkg/bigip/client.go index 698ff64..484b0d4 100644 --- a/pkg/bigip/client.go +++ b/pkg/bigip/client.go @@ -32,6 +32,7 @@ type Client struct { Username string Password string PasswordBytes []byte + authToken []byte HTTPClient *http.Client } @@ -44,6 +45,10 @@ func (c *Client) Zero() { auth.ZeroBytes(c.PasswordBytes) c.PasswordBytes = nil } + if len(c.authToken) > 0 { + auth.ZeroBytes(c.authToken) + c.authToken = nil + } c.Password = "" } @@ -221,6 +226,7 @@ type ClientOptions struct { ClientCertPath string ClientKeyPath string Timeout time.Duration + HTTPClient *http.Client } // NewClientWithOptions initializes a BIG-IP appliance client with validation and optional mTLS client certificates. @@ -264,7 +270,9 @@ func NewClientWithOptions(opts ClientOptions) (*Client, error) { } var httpClient *http.Client - if opts.ClientCertPath != "" { + if opts.HTTPClient != nil { + httpClient = opts.HTTPClient + } else if opts.ClientCertPath != "" { cert, err := client.LoadClientCertificate(opts.ClientCertPath, opts.ClientKeyPath) if err != nil { return nil, fmt.Errorf("failed to load client certificate: %w", err) @@ -384,15 +392,29 @@ func (c *Client) CheckReadyWithKind(ctx context.Context) (string, error) { if err != nil { return "", err } - c.setAuth(req) - resp, err := c.HTTPClient.Do(req) + resp, err := c.doWithAuth(req) if err != nil { return "", fmt.Errorf("device reachability check failed: %w", err) } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { + verURL := fmt.Sprintf("%s/mgmt/tm/sys/version", c.BaseURL()) + verReq, verErr := http.NewRequestWithContext(ctx, http.MethodGet, verURL, nil) + if verErr == nil { + if verResp, verDoErr := c.doWithAuth(verReq); verDoErr == nil { + defer verResp.Body.Close() + if verResp.StatusCode == http.StatusOK { + verBody, _ := io.ReadAll(io.LimitReader(verResp.Body, 512*1024)) + var vInfo SystemInfo + parseVersionJSON(verBody, &vInfo) + if vInfo.ApplianceKind() == "BIG-IQ" { + return "BIG-IQ", nil + } + } + } + } return "BIG-IP", nil } @@ -401,8 +423,7 @@ func (c *Client) CheckReadyWithKind(ctx context.Context) (string, error) { echoURL := fmt.Sprintf("%s/mgmt/shared/echo", c.BaseURL()) echoReq, echoErr := http.NewRequestWithContext(ctx, http.MethodGet, echoURL, nil) if echoErr == nil { - c.setAuth(echoReq) - if echoResp, doErr := c.HTTPClient.Do(echoReq); doErr == nil { + if echoResp, doErr := c.doWithAuth(echoReq); doErr == nil { defer echoResp.Body.Close() if echoResp.StatusCode == http.StatusOK { return "BIG-IQ", nil @@ -480,10 +501,9 @@ func (c *Client) CreateQKViewTaskWithOptions(ctx context.Context, filename strin if err != nil { return nil, err } - c.setAuth(req) req.Header.Set("Content-Type", "application/json") - resp, err := c.HTTPClient.Do(req) + resp, err := c.doWithAuth(req) if err != nil { return nil, fmt.Errorf("failed to create qkview task: %w", err) } @@ -508,9 +528,8 @@ func (c *Client) QueryQKViewTask(ctx context.Context, taskID string) (*QKViewTas if err != nil { return nil, err } - c.setAuth(req) - resp, err := c.HTTPClient.Do(req) + resp, err := c.doWithAuth(req) if err != nil { return nil, fmt.Errorf("failed to query qkview task %s: %w", taskID, err) } @@ -621,7 +640,6 @@ func (c *Client) GenerateQKViewWithStatus(ctx context.Context, filename string, if err != nil { return "", err } - c.setAuth(req) req.Header.Set("Content-Type", "application/json") type result struct { @@ -630,7 +648,7 @@ func (c *Client) GenerateQKViewWithStatus(ctx context.Context, filename string, } resCh := make(chan result, 1) go func() { - resp, err := c.HTTPClient.Do(req) + resp, err := c.doWithAuth(req) resCh <- result{resp: resp, err: err} }() @@ -677,9 +695,8 @@ func (c *Client) GenerateQKViewWithStatus(ctx context.Context, filename string, if err != nil { return "", err } - c.setAuth(bashReq) bashReq.Header.Set("Content-Type", "application/json") - bashResp, err := c.HTTPClient.Do(bashReq) + bashResp, err := c.doWithAuth(bashReq) if err != nil { return "", fmt.Errorf("bash fallback for qkview failed: %w", err) } @@ -742,16 +759,15 @@ func (c *Client) DownloadFromURI(ctx context.Context, endpointURI, localPath str if err != nil { return err } - c.setAuth(req) req.Header.Set("Content-Type", "application/octet-stream") req.Header.Set("Content-Range", fmt.Sprintf("%d-%d/%d", start, end, totalSize)) - resp, err := c.HTTPClient.Do(req) + resp, err := c.doWithAuth(req) if err != nil { return fmt.Errorf("failed to download chunk from %s: %w", endpointURI, err) } - if resp.StatusCode != http.StatusOK { + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent { b, _ := io.ReadAll(io.LimitReader(resp.Body, 1024*1024)) _ = resp.Body.Close() return fmt.Errorf("chunk download failed with HTTP %d: %s", resp.StatusCode, string(b)) @@ -857,9 +873,8 @@ func (c *Client) DeleteQKView(ctx context.Context, remoteFilename string) error if err != nil { return err } - c.setAuth(req) - resp, err := c.HTTPClient.Do(req) + resp, err := c.doWithAuth(req) if err != nil { return fmt.Errorf("delete qkview failed: %w", err) } @@ -902,9 +917,8 @@ func (c *Client) GetEndpointExample(ctx context.Context, endpoint string) ([]byt return nil, fmt.Errorf("failed to create request for example endpoint: %w", err) } req.Header.Set("Accept", "application/json") - c.setAuth(req) - resp, err := c.HTTPClient.Do(req) + resp, err := c.doWithAuth(req) if err != nil { return nil, fmt.Errorf("failed to fetch example for %s: %w", p, err) } @@ -929,6 +943,12 @@ func (c *Client) GetEndpointExample(ctx context.Context, endpoint string) ([]byt } func (c *Client) setAuth(req *http.Request) { + if len(c.authToken) > 0 { + req.Header.Set("X-F5-Auth-Token", string(c.authToken)) + req.Header.Set("User-Agent", "myf5-cli-go/1.0.0") + return + } + pwBytes := c.PasswordBytes if len(pwBytes) == 0 && c.Password != "" { pwBytes = []byte(c.Password) @@ -944,6 +964,82 @@ func (c *Client) setAuth(req *http.Request) { req.Header.Set("User-Agent", "myf5-cli-go/1.0.0") } +func (c *Client) acquireAuthToken(ctx context.Context) error { + loginURL := fmt.Sprintf("%s/mgmt/shared/authn/login", c.BaseURL()) + pw := string(c.PasswordBytes) + if pw == "" && c.Password != "" { + pw = c.Password + } + payload := map[string]string{ + "username": c.Username, + "password": pw, + "loginProviderName": "tmos", + } + bodyBytes, err := json.Marshal(payload) + if err != nil { + return fmt.Errorf("failed to marshal login payload: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, loginURL, bytes.NewReader(bodyBytes)) + if err != nil { + return fmt.Errorf("failed to create login request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "myf5-cli-go/1.0.0") + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return fmt.Errorf("login request failed: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1024*1024)) + return fmt.Errorf("login failed with HTTP %d: %s", resp.StatusCode, string(b)) + } + + var parsed struct { + Token struct { + Token string `json:"token"` + } `json:"token"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, 1024*1024)).Decode(&parsed); err != nil { + return fmt.Errorf("failed to decode login token response: %w", err) + } + if parsed.Token.Token == "" { + return errors.New("empty token received from login response") + } + + c.authToken = []byte(parsed.Token.Token) + return nil +} + +func (c *Client) doWithAuth(req *http.Request) (*http.Response, error) { + c.setAuth(req) + resp, err := c.HTTPClient.Do(req) + if err == nil && resp.StatusCode == http.StatusUnauthorized && len(c.authToken) == 0 && (len(c.PasswordBytes) > 0 || c.Password != "") { + if req.Body == nil || req.GetBody != nil { + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + + if tokenErr := c.acquireAuthToken(req.Context()); tokenErr == nil { + req2 := req.Clone(req.Context()) + if req.GetBody != nil { + b, err := req.GetBody() + if err != nil { + return resp, err + } + req2.Body = b + } + req2.Header.Del("Authorization") + c.setAuth(req2) + return c.HTTPClient.Do(req2) + } + } + } + return resp, err +} + var validUsernameRegex = regexp.MustCompile(`^[a-zA-Z0-9_][a-zA-Z0-9_.\-@]*$`) // ValidateApplianceUsername validates a username for BIG-IP / BIG-IQ appliance access. diff --git a/pkg/bigip/client_test.go b/pkg/bigip/client_test.go index 283551b..84d5d18 100644 --- a/pkg/bigip/client_test.go +++ b/pkg/bigip/client_test.go @@ -5,7 +5,6 @@ import ( "encoding/base64" "fmt" "net/http" - "net/http/httptest" "net/url" "os" "path/filepath" @@ -14,15 +13,20 @@ import ( "strconv" "strings" "testing" + "time" ) func TestCheckReady(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/mgmt/tm/sys/ready" { w.WriteHeader(http.StatusOK) w.Write([]byte(`{"kind": "tm:sys:ready"}`)) return } + if r.URL.Path == "/mgmt/tm/sys/version" { + w.WriteHeader(http.StatusNotFound) + return + } t.Errorf("unexpected path: %s", r.URL.Path) })) defer server.Close() @@ -52,7 +56,7 @@ func TestCheckReady(t *testing.T) { } func TestCheckReadyWithKind_BIGIQ(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/mgmt/tm/sys/ready" { w.WriteHeader(http.StatusNotFound) return @@ -134,7 +138,7 @@ func TestValidateQKViewFilename(t *testing.T) { func TestDownloadFromURI(t *testing.T) { testData := []byte("f5-mock-download-content-54321") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Range", fmt.Sprintf("0-%d/%d", len(testData)-1, len(testData))) w.WriteHeader(http.StatusOK) @@ -184,7 +188,7 @@ func TestDownloadFromURI(t *testing.T) { func TestDeleteQKView(t *testing.T) { var receivedMethod, receivedPath, receivedAuth string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { receivedMethod = r.Method receivedPath = r.URL.Path receivedAuth = r.Header.Get("Authorization") @@ -221,7 +225,7 @@ func TestDeleteQKView(t *testing.T) { } func TestGenerateQKViewDefaultFilenameISO8601(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(`{"command":"run","utilCmdArgs":"-f /var/tmp/qkviews/test.qkview","status":"completed"}`)) @@ -248,7 +252,7 @@ func TestGenerateQKViewDefaultFilenameISO8601(t *testing.T) { func TestGenerateQKViewBIGIQFallback(t *testing.T) { bashCalled := false - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if r.URL.Path == "/mgmt/tm/util/qkview" { w.WriteHeader(http.StatusNotFound) @@ -421,7 +425,7 @@ func TestNewClientWithOptions(t *testing.T) { func TestCreateQKViewTaskWithOptions(t *testing.T) { var receivedBody string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/mgmt/cm/autodeploy/qkview" { t.Errorf("unexpected path: %s", r.URL.Path) } @@ -464,7 +468,7 @@ func TestGetEndpointExample(t *testing.T) { var requestedPath string var authHeader string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requestedPath = r.URL.Path authHeader = r.Header.Get("Authorization") if r.URL.Path == "/mgmt/tm/ltm/pool/example" { @@ -842,3 +846,259 @@ func TestValidateAppliancePassword_K2873(t *testing.T) { }) } } + +func TestClientStringAndGoString(t *testing.T) { + var nilClient *Client + if nilClient.String() != "" { + t.Errorf("nil Client.String() = %q, want ", nilClient.String()) + } + if nilClient.GoString() != "" { + t.Errorf("nil Client.GoString() = %q, want ", nilClient.GoString()) + } + + c := NewClient("10.1.1.4", 443, "admin", "supersecret") + if strings.Contains(c.String(), "supersecret") { + t.Errorf("Client.String() leaked password: %s", c.String()) + } + if !strings.Contains(c.String(), "[REDACTED]") { + t.Errorf("Client.String() missing [REDACTED]: %s", c.String()) + } + if c.GoString() != c.String() { + t.Errorf("GoString() != String()") + } + + cEmpty := NewClient("10.1.1.4", 443, "admin", "") + if !strings.Contains(cEmpty.String(), "[EMPTY]") { + t.Errorf("Client.String() missing [EMPTY]: %s", cEmpty.String()) + } +} + +func TestQKViewTaskLifecycle(t *testing.T) { + queryCount := 0 + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodPost && r.URL.Path == "/mgmt/cm/autodeploy/qkview" { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":"task-123","name":"test.qkview","status":"IN_PROGRESS"}`)) + return + } + if r.Method == http.MethodGet && r.URL.Path == "/mgmt/cm/autodeploy/qkview/task-123" { + queryCount++ + if queryCount == 1 { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":"task-123","status":"IN_PROGRESS"}`)) + } else { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":"task-123","status":"SUCCEEDED"}`)) + } + return + } + w.WriteHeader(http.StatusNotFound) + })) + defer server.Close() + + u, _ := url.Parse(server.URL) + port, _ := strconv.Atoi(u.Port()) + c := NewClient(u.Hostname(), port, "admin", "secret") + c.Scheme = "http" + c.HTTPClient = server.Client() + + task, err := c.CreateQKViewTask(context.Background(), "test.qkview") + if err != nil { + t.Fatalf("CreateQKViewTask failed: %v", err) + } + if task.ID != "task-123" { + t.Errorf("got task ID %s, want task-123", task.ID) + } + + taskQuery, err := c.QueryQKViewTask(context.Background(), "task-123") + if err != nil { + t.Fatalf("QueryQKViewTask failed: %v", err) + } + if taskQuery.Status != "IN_PROGRESS" { + t.Errorf("got status %s, want IN_PROGRESS", taskQuery.Status) + } + + taskDone, err := c.WaitForQKViewTask(context.Background(), "task-123", 10*time.Millisecond, nil) + if err != nil { + t.Fatalf("WaitForQKViewTask failed: %v", err) + } + if taskDone.Status != "SUCCEEDED" { + t.Errorf("got status %s, want SUCCEEDED", taskDone.Status) + } +} + +func TestGenerateAndDownloadQKView(t *testing.T) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodPost && r.URL.Path == "/mgmt/tm/util/qkview" { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"command":"run","status":"completed"}`)) + return + } + if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/mgmt/cm/autodeploy/qkview-downloads/") { + w.Header().Set("Content-Range", "bytes 0-11/12") + w.WriteHeader(http.StatusPartialContent) + _, _ = w.Write([]byte("fake-qkview!")) + return + } + if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/mgmt/cm/autodeploy/software-image-downloads/") { + w.Header().Set("Content-Range", "bytes 0-8/9") + w.WriteHeader(http.StatusPartialContent) + _, _ = w.Write([]byte("fake-iso!")) + return + } + w.WriteHeader(http.StatusNotFound) + })) + defer server.Close() + + u, _ := url.Parse(server.URL) + port, _ := strconv.Atoi(u.Port()) + c := NewClient(u.Hostname(), port, "admin", "secret") + c.Scheme = "http" + c.HTTPClient = server.Client() + + fn, err := c.GenerateQKView(context.Background(), "test.qkview", true) + if err != nil { + t.Fatalf("GenerateQKView failed: %v", err) + } + if fn != "test.qkview" { + t.Errorf("got %s, want test.qkview", fn) + } + + tmpDir := t.TempDir() + localQkview := filepath.Join(tmpDir, "test.qkview") + if err := c.DownloadQKView(context.Background(), "test.qkview", localQkview, nil); err != nil { + t.Fatalf("DownloadQKView failed: %v", err) + } + data, _ := os.ReadFile(localQkview) + if string(data) != "fake-qkview!" { + t.Errorf("got %s, want fake-qkview!", string(data)) + } + + localISO := filepath.Join(tmpDir, "image.iso") + if err := c.DownloadFile(context.Background(), "/shared/images/image.iso", localISO, nil); err != nil { + t.Fatalf("DownloadFile failed: %v", err) + } + isoData, _ := os.ReadFile(localISO) + if string(isoData) != "fake-iso!" { + t.Errorf("got %s, want fake-iso!", string(isoData)) + } + + localQkview2 := filepath.Join(tmpDir, "test2.qkview") + if err := c.DownloadFile(context.Background(), "/var/tmp/qkviews/test2.qkview", localQkview2, nil); err != nil { + t.Fatalf("DownloadFile qkview failed: %v", err) + } + + localDirect := filepath.Join(tmpDir, "direct.iso") + if err := c.DownloadFile(context.Background(), "/mgmt/cm/autodeploy/software-image-downloads/direct.iso", localDirect, nil); err != nil { + t.Fatalf("DownloadFile direct mgmt failed: %v", err) + } +} + +func TestAcquireAuthTokenAndDoWithAuth(t *testing.T) { + loginAttempts := 0 + readyAttempts := 0 + + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/mgmt/shared/authn/login" { + loginAttempts++ + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"token": {"token": "bigiq-test-token-abcdef"}}`)) + return + } + if r.URL.Path == "/mgmt/tm/sys/ready" { + readyAttempts++ + token := r.Header.Get("X-F5-Auth-Token") + if token == "" { + w.Header().Set("WWW-Authenticate", `Token realm="REST Framework"`) + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte(`{"code": 401, "message": "Basic auth disabled"}`)) + return + } + if token != "bigiq-test-token-abcdef" { + w.WriteHeader(http.StatusForbidden) + return + } + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"kind": "tm:sys:ready"}`)) + return + } + if r.URL.Path == "/mgmt/tm/sys/version" { + token := r.Header.Get("X-F5-Auth-Token") + if token != "bigiq-test-token-abcdef" { + w.WriteHeader(http.StatusUnauthorized) + return + } + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"entries": {"https://localhost/mgmt/tm/sys/version/0": {"nestedStats": {"entries": {"Product": {"description": "BIG-IQ"}}}}}}`)) + return + } + w.WriteHeader(http.StatusNotFound) + })) + defer server.Close() + + u, _ := url.Parse(server.URL) + port, _ := strconv.Atoi(u.Port()) + c := NewClient(u.Hostname(), port, "admin", "secret") + c.Scheme = "http" + c.HTTPClient = server.Client() + + kind, err := c.CheckReadyWithKind(context.Background()) + if err != nil { + t.Fatalf("CheckReadyWithKind failed: %v", err) + } + if kind != "BIG-IQ" { + t.Errorf("expected BIG-IQ, got %q", kind) + } + if loginAttempts != 1 { + t.Errorf("expected 1 login attempt, got %d", loginAttempts) + } + if readyAttempts != 2 { + t.Errorf("expected 2 ready attempts (1 unauth + 1 with token), got %d", readyAttempts) + } + if string(c.authToken) != "bigiq-test-token-abcdef" { + t.Errorf("expected auth token saved in client, got %s", string(c.authToken)) + } + + // Test Zero() clears token + c.Zero() + if len(c.authToken) != 0 { + t.Errorf("expected Zero() to clear authToken, got %d bytes", len(c.authToken)) + } +} + +func TestAcquireAuthTokenErrors(t *testing.T) { + // Case 1: HTTP error + s1 := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte("invalid credentials")) + })) + defer s1.Close() + + u1, _ := url.Parse(s1.URL) + port1, _ := strconv.Atoi(u1.Port()) + c1 := NewClient(u1.Hostname(), port1, "admin", "secret") + c1.Scheme = "http" + c1.HTTPClient = s1.Client() + if err := c1.acquireAuthToken(context.Background()); err == nil { + t.Errorf("expected error for 401 login, got nil") + } + + // Case 2: empty token + s2 := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"token": {"token": ""}}`)) + })) + defer s2.Close() + + u2, _ := url.Parse(s2.URL) + port2, _ := strconv.Atoi(u2.Port()) + c2 := NewClient(u2.Hostname(), port2, "admin", "secret") + c2.Scheme = "http" + c2.HTTPClient = s2.Client() + if err := c2.acquireAuthToken(context.Background()); err == nil { + t.Errorf("expected error for empty token, got nil") + } +} diff --git a/pkg/bigip/failover.go b/pkg/bigip/failover.go index cfc65f3..e3af796 100644 --- a/pkg/bigip/failover.go +++ b/pkg/bigip/failover.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "net/http" "os" "path" "path/filepath" @@ -42,6 +43,7 @@ type TransferOptions struct { ClientCertPath string // Path to TLS client certificate file (PEM) for mTLS ClientKeyPath string // Path to TLS client certificate private key file (PEM) Timeout time.Duration // Connection timeout + HTTPClient *http.Client // Custom HTTP client (used for in-memory testing or custom transports) } // Zero scrubs sensitive password and passphrase bytes and clears string fields from memory. @@ -258,12 +260,15 @@ func newClientFromOptions(host string, opts TransferOptions, defaultPort int) *C ClientCertPath: opts.ClientCertPath, ClientKeyPath: opts.ClientKeyPath, Timeout: opts.Timeout, + HTTPClient: opts.HTTPClient, }) if err == nil { return c } c = NewClient(host, port, user, opts.Password) - if opts.Timeout > 0 { + if opts.HTTPClient != nil { + c.HTTPClient = opts.HTTPClient + } else if opts.Timeout > 0 { c.HTTPClient.Timeout = opts.Timeout } return c diff --git a/pkg/bigip/failover_test.go b/pkg/bigip/failover_test.go index c611001..7977f56 100644 --- a/pkg/bigip/failover_test.go +++ b/pkg/bigip/failover_test.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "net/http" - "net/http/httptest" "net/url" "os" "path/filepath" @@ -15,7 +14,7 @@ import ( ) func TestPushFileWithFailover_IControlSuccess(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/mgmt/shared/file-transfer/uploads/") { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(`{"localFilePath":"/var/config/rest/downloads/test.txt"}`)) @@ -38,11 +37,12 @@ func TestPushFileWithFailover_IControlSuccess(t *testing.T) { _ = os.WriteFile(localFile, []byte("data"), 0600) opts := TransferOptions{ - Method: MethodAuto, - Username: "admin", - Password: "secret", - Port: port, - Timeout: 2 * time.Second, + Method: MethodAuto, + Username: "admin", + Password: "secret", + Port: port, + Timeout: 2 * time.Second, + HTTPClient: server.Client(), } var logMessages []string @@ -97,7 +97,7 @@ func TestPushFileWithFailover_BothFail(t *testing.T) { func TestDownloadFileWithFailover_IControlSuccess(t *testing.T) { testData := []byte("downloadable-content") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Range", fmt.Sprintf("0-%d/%d", len(testData)-1, len(testData))) w.WriteHeader(http.StatusOK) @@ -112,11 +112,12 @@ func TestDownloadFileWithFailover_IControlSuccess(t *testing.T) { localTarget := filepath.Join(tempDir, "received.txt") opts := TransferOptions{ - Method: MethodAuto, - Username: "admin", - Password: "secret", - Port: port, - Timeout: 2 * time.Second, + Method: MethodAuto, + Username: "admin", + Password: "secret", + Port: port, + Timeout: 2 * time.Second, + HTTPClient: server.Client(), } savedPath, method, err := DownloadFileWithFailover(context.Background(), server.URL, "/shared/images/image.iso", localTarget, opts, nil, nil) @@ -190,3 +191,167 @@ func TestTransferOptionsPasswordBytesNotZeroedAcrossCalls(t *testing.T) { t.Errorf("expected opts.SSHPassphraseBytes to remain %q after scpOpts.Zero(), got %q", "pass123", string(opts.SSHPassphraseBytes)) } } + +func TestGenerateAndDeleteQKViewWithFailover(t *testing.T) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodPost && r.URL.Path == "/mgmt/tm/util/qkview" { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"command":"run","status":"completed"}`)) + return + } + if r.Method == http.MethodDelete && strings.HasPrefix(r.URL.Path, "/mgmt/cm/autodeploy/qkview/") { + w.WriteHeader(http.StatusOK) + return + } + w.WriteHeader(http.StatusNotFound) + })) + defer server.Close() + + u, _ := url.Parse(server.URL) + port, _ := strconv.Atoi(u.Port()) + + opts := TransferOptions{ + Method: MethodIControl, + Username: "admin", + Password: "secret", + Port: port, + Timeout: 2 * time.Second, + HTTPClient: server.Client(), + } + + fn, method, err := GenerateQKViewWithFailover(context.Background(), server.URL, "test.qkview", true, opts, nil, nil) + if err != nil { + t.Fatalf("GenerateQKViewWithFailover failed: %v", err) + } + if method != MethodIControl || fn != "test.qkview" { + t.Errorf("got (%s, %v), want (test.qkview, MethodIControl)", fn, method) + } + + if err := DeleteQKViewWithFailover(context.Background(), server.URL, "test.qkview", opts); err != nil { + t.Fatalf("DeleteQKViewWithFailover failed: %v", err) + } + + optsAuto := opts + optsAuto.Method = MethodAuto + fn2, method2, err := GenerateQKViewWithFailover(context.Background(), server.URL, "test2.qkview", true, optsAuto, nil, nil) + if err != nil { + t.Fatalf("GenerateQKViewWithFailover auto failed: %v", err) + } + if method2 != MethodIControl || fn2 != "test2.qkview" { + t.Errorf("got (%s, %v), want (test2.qkview, MethodIControl)", fn2, method2) + } + + if err := DeleteQKViewWithFailover(context.Background(), server.URL, "test2.qkview", optsAuto); err != nil { + t.Fatalf("DeleteQKViewWithFailover auto failed: %v", err) + } +} + +func TestFailoverBranches(t *testing.T) { + tmpFile := filepath.Join(t.TempDir(), "dummy.txt") + _ = os.WriteFile(tmpFile, []byte("data"), 0600) + tmpDest := filepath.Join(t.TempDir(), "out.txt") + + canceledCtx, cancel := context.WithCancel(context.Background()) + cancel() + + // 1. PushFileWithFailover: unsupported method + _, _, err := PushFileWithFailover(context.Background(), "127.0.0.1", tmpFile, TransferOptions{Method: "unsupported"}, nil, nil) + if err == nil || !strings.Contains(err.Error(), "unsupported transfer method") { + t.Errorf("expected unsupported method error, got %v", err) + } + + // 2. PushFileWithFailover: MethodSCP failure + _, _, err = PushFileWithFailover(context.Background(), "127.0.0.1", tmpFile, TransferOptions{Method: MethodSCP, Port: 65530, Timeout: 50 * time.Millisecond}, nil, nil) + if err == nil || !strings.Contains(err.Error(), "SCP upload failed") { + t.Errorf("expected SCP upload failed error, got %v", err) + } + + // 3. PushFileWithFailover: MethodIControl failure + _, _, err = PushFileWithFailover(context.Background(), "127.0.0.1", tmpFile, TransferOptions{Method: MethodIControl, Port: 65530, Timeout: 50 * time.Millisecond}, nil, nil) + if err == nil || !strings.Contains(err.Error(), "iControl REST upload failed") { + t.Errorf("expected iControl upload failed error, got %v", err) + } + + // 4. PushFileWithFailover: trySCPFirst (IdentityFile) both fail + _, _, err = PushFileWithFailover(context.Background(), "127.0.0.1", tmpFile, TransferOptions{Method: MethodAuto, IdentityFile: "/dummy/key", Port: 65530, Timeout: 50 * time.Millisecond}, func(f string, a ...any) {}, nil) + if err == nil || !strings.Contains(err.Error(), "both transfer methods failed") { + t.Errorf("expected both failed error, got %v", err) + } + + // 5. PushFileWithFailover: canceled context + _, _, err = PushFileWithFailover(canceledCtx, "127.0.0.1", tmpFile, TransferOptions{Method: MethodAuto, Port: 65530, Timeout: 50 * time.Millisecond}, nil, nil) + if err == nil { + t.Errorf("expected error with canceled context, got nil") + } + + // 6. DownloadFileWithFailover: unsupported method + _, _, err = DownloadFileWithFailover(context.Background(), "127.0.0.1", "/shared/images/test.iso", tmpDest, TransferOptions{Method: "unsupported"}, nil, nil) + if err == nil || !strings.Contains(err.Error(), "unsupported transfer method") { + t.Errorf("expected unsupported method error, got %v", err) + } + + // 7. DownloadFileWithFailover: MethodSCP failure + _, _, err = DownloadFileWithFailover(context.Background(), "127.0.0.1", "/shared/images/test.iso", tmpDest, TransferOptions{Method: MethodSCP, Port: 65530, Timeout: 50 * time.Millisecond}, nil, nil) + if err == nil || !strings.Contains(err.Error(), "SCP download failed") { + t.Errorf("expected SCP download failed error, got %v", err) + } + + // 8. DownloadFileWithFailover: MethodIControl failure + _, _, err = DownloadFileWithFailover(context.Background(), "127.0.0.1", "/shared/images/test.iso", tmpDest, TransferOptions{Method: MethodIControl, Port: 65530, Timeout: 50 * time.Millisecond}, nil, nil) + if err == nil || !strings.Contains(err.Error(), "iControl REST download failed") { + t.Errorf("expected iControl download failed error, got %v", err) + } + + // 9. DownloadFileWithFailover: trySCPFirst both fail + _, _, err = DownloadFileWithFailover(context.Background(), "127.0.0.1", "/shared/images/test.iso", tmpDest, TransferOptions{Method: MethodAuto, IdentityFile: "/dummy/key", Port: 65530, Timeout: 50 * time.Millisecond}, func(f string, a ...any) {}, nil) + if err == nil || !strings.Contains(err.Error(), "both download methods failed") { + t.Errorf("expected both failed error, got %v", err) + } + + // 10. DownloadFileWithFailover: canceled context + _, _, err = DownloadFileWithFailover(canceledCtx, "127.0.0.1", "/shared/images/test.iso", tmpDest, TransferOptions{Method: MethodAuto, Port: 65530, Timeout: 50 * time.Millisecond}, nil, nil) + if err == nil { + t.Errorf("expected error with canceled context, got nil") + } + + // 11. GenerateQKViewWithFailover: unsupported method + _, _, err = GenerateQKViewWithFailover(context.Background(), "127.0.0.1", "test.qkview", true, TransferOptions{Method: "unsupported"}, nil, nil) + if err == nil || !strings.Contains(err.Error(), "unsupported transfer method") { + t.Errorf("expected unsupported method error, got %v", err) + } + + // 12. GenerateQKViewWithFailover: MethodSCP failure + _, _, err = GenerateQKViewWithFailover(context.Background(), "127.0.0.1", "test.qkview", true, TransferOptions{Method: MethodSCP, Port: 65530, Timeout: 50 * time.Millisecond}, nil, nil) + if err == nil || !strings.Contains(err.Error(), "SSH QKView generation failed") { + t.Errorf("expected SSH generation failed error, got %v", err) + } + + // 13. GenerateQKViewWithFailover: trySSHFirst (IdentityFile) + _, _, err = GenerateQKViewWithFailover(context.Background(), "127.0.0.1", "test.qkview", true, TransferOptions{Method: MethodAuto, IdentityFile: "/dummy/key", Port: 65530, Timeout: 50 * time.Millisecond}, func(f string, a ...any) {}, nil) + if err == nil || !strings.Contains(err.Error(), "both QKView generation methods failed") { + t.Errorf("expected both failed error, got %v", err) + } + + // 14. GenerateQKViewWithFailover: canceled context + _, _, err = GenerateQKViewWithFailover(canceledCtx, "127.0.0.1", "test.qkview", true, TransferOptions{Method: MethodAuto, Port: 65530, Timeout: 50 * time.Millisecond}, nil, nil) + if err == nil { + t.Errorf("expected error with canceled context, got nil") + } + + // 15. GenerateQKViewWithFailover: MethodIControl error + _, _, _ = GenerateQKViewWithFailover(context.Background(), "127.0.0.1", "test.qkview", true, TransferOptions{Method: MethodIControl, Port: 65530, Timeout: 50 * time.Millisecond}, nil, nil) + + // 16. DeleteQKViewWithFailover branches + _ = DeleteQKViewWithFailover(context.Background(), "127.0.0.1", "test.qkview", TransferOptions{Method: "unsupported"}) + _ = DeleteQKViewWithFailover(context.Background(), "127.0.0.1", "test.qkview", TransferOptions{Method: MethodSCP, Port: 65530, Timeout: 50 * time.Millisecond}) + _ = DeleteQKViewWithFailover(context.Background(), "127.0.0.1", "test.qkview", TransferOptions{Method: MethodIControl, Port: 65530, Timeout: 50 * time.Millisecond}) + _ = DeleteQKViewWithFailover(context.Background(), "127.0.0.1", "test.qkview", TransferOptions{Method: MethodAuto, Port: 65530, Timeout: 50 * time.Millisecond}) + + // 17. TransferOptions.Zero + optsToZero := TransferOptions{PasswordBytes: []byte("secret"), SSHPassphraseBytes: []byte("pass")} + optsToZero.Zero() + if len(optsToZero.PasswordBytes) != 0 || len(optsToZero.SSHPassphraseBytes) != 0 { + t.Errorf("expected PasswordBytes and SSHPassphraseBytes to be zeroed") + } +} diff --git a/pkg/bigip/geoip.go b/pkg/bigip/geoip.go index fc34b06..5883782 100644 --- a/pkg/bigip/geoip.go +++ b/pkg/bigip/geoip.go @@ -36,6 +36,7 @@ type GeoIPOptions struct { ClientCertPath string // mTLS client certificate path ClientKeyPath string // mTLS client private key path Timeout time.Duration // Execution timeout (default: 3 minutes) + HTTPClient *http.Client // Custom HTTP client for mock/testing Force bool // Pass --force to rpm via geoip_update_data -f (default: true) KeepExtracted bool // Retain extracted files on appliance (default: false, cleans up temp dir) } @@ -455,6 +456,7 @@ func applyGeoIPREST(ctx context.Context, host, scriptB64 string, opts GeoIPOptio ClientCertPath: opts.ClientCertPath, ClientKeyPath: opts.ClientKeyPath, Timeout: opts.Timeout, + HTTPClient: opts.HTTPClient, }) if err != nil { return "", fmt.Errorf("failed to initialize appliance REST client: %w", err) diff --git a/pkg/bigip/geoip_test.go b/pkg/bigip/geoip_test.go index 668c43a..7903d9f 100644 --- a/pkg/bigip/geoip_test.go +++ b/pkg/bigip/geoip_test.go @@ -2,13 +2,17 @@ package bigip import ( "context" + "crypto/ed25519" + "crypto/rand" "encoding/json" + "fmt" "io" "net/http" - "net/http/httptest" "strings" "testing" "time" + + "golang.org/x/crypto/ssh" ) func TestApplyGeoIPTargetValidation(t *testing.T) { @@ -140,7 +144,7 @@ ERROR: Failed to extract /var/tmp/geoip.zip func TestApplyGeoIPREST_MockServer(t *testing.T) { var receivedBody map[string]string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/mgmt/tm/util/bash" && r.Method == http.MethodPost { b, _ := io.ReadAll(r.Body) _ = json.Unmarshal(b, &receivedBody) @@ -157,6 +161,7 @@ func TestApplyGeoIPREST_MockServer(t *testing.T) { Method: MethodIControl, Username: "admin", Password: "secret", + HTTPClient: server.Client(), } res, err := ApplyGeoIP(context.Background(), server.URL, "/var/tmp/update.zip", opts, nil) @@ -173,7 +178,7 @@ func TestApplyGeoIPREST_MockServer(t *testing.T) { } func TestApplyGeoIPREST_ApplianceModeError(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/mgmt/tm/util/bash" { w.WriteHeader(http.StatusForbidden) _, _ = w.Write([]byte(`{"error":"bash utility disabled"}`)) @@ -188,6 +193,7 @@ func TestApplyGeoIPREST_ApplianceModeError(t *testing.T) { Method: MethodIControl, Username: "admin", Password: "secret", + HTTPClient: server.Client(), } _, err := ApplyGeoIP(context.Background(), server.URL, "/var/tmp/update.zip", opts, nil) @@ -198,3 +204,172 @@ func TestApplyGeoIPREST_ApplianceModeError(t *testing.T) { t.Errorf("expected remediation hint mentioning Appliance Mode, got: %v", err) } } + +func TestGeoIPOptionsZero(t *testing.T) { + var nilOpts *GeoIPOptions + nilOpts.Zero() + + opts := &GeoIPOptions{ + Password: "secret", + PasswordBytes: []byte("secret"), + SSHPassphrase: "passphrase", + SSHPassphraseBytes: []byte("passphrase"), + } + opts.Zero() + if opts.Password != "" || opts.SSHPassphrase != "" || opts.PasswordBytes != nil || opts.SSHPassphraseBytes != nil { + t.Errorf("GeoIPOptions.Zero() did not clear secrets: %+v", opts) + } +} + +func TestApplyGeoIPSSHMockServer(t *testing.T) { + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("failed generating key: %v", err) + } + signer, err := ssh.NewSignerFromKey(priv) + if err != nil { + t.Fatalf("failed creating signer: %v", err) + } + + serverConfig := &ssh.ServerConfig{ + PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { + if c.User() == "admin" && string(pass) == "secret" { + return nil, nil + } + return nil, fmt.Errorf("password rejected") + }, + } + serverConfig.AddHostKey(signer) + + listener, port := newPipeSSHServer() + defer listener.Close() + + mockOutput := "--- EXTRACT_DIR ---\n/shared/tmp/geoip_update_123\n--- INSTALLED_GEOIP_RPMS ---\ngeoip-data-v2.rpm\n--- GEOIP_LOOKUP_TEST ---\ncountry_code = US\n--- GEOIP_COMPLETE ---\n--- SCRIPT_EXIT_CODE: 0 ---\n" + + go func() { + tcpConn, err := listener.Accept() + if err != nil { + return + } + defer tcpConn.Close() + + sshConn, chans, reqs, err := ssh.NewServerConn(tcpConn, serverConfig) + if err != nil { + return + } + defer sshConn.Close() + go ssh.DiscardRequests(reqs) + + for newChannel := range chans { + if newChannel.ChannelType() != "session" { + _ = newChannel.Reject(ssh.UnknownChannelType, "unknown") + continue + } + channel, requests, err := newChannel.Accept() + if err != nil { + return + } + + go func(in <-chan *ssh.Request) { + defer channel.Close() + for req := range in { + switch req.Type { + case "exec": + _ = req.Reply(true, nil) + _, _ = channel.Write([]byte(mockOutput)) + _ = channel.CloseWrite() + _, _ = channel.SendRequest("exit-status", false, []byte{0, 0, 0, 0}) + _, _ = io.Copy(io.Discard, channel) + return + default: + _ = req.Reply(false, nil) + } + } + }(requests) + } + }() + + opts := GeoIPOptions{ + TargetType: "BIG-IP", + Method: MethodSCP, + Username: "admin", + Password: "secret", + Port: port, + Timeout: 2 * time.Second, + } + + out, err := applyGeoIPSSH(context.Background(), "127.0.0.1", "c2NyaXB0", opts) + if err != nil { + t.Fatalf("applyGeoIPSSH failed: %v", err) + } + if !strings.Contains(out, "GEOIP_COMPLETE") { + t.Errorf("expected GEOIP_COMPLETE in output, got: %s", out) + } +} + +func TestApplyGeoIPIControlSuccess(t *testing.T) { + mockOutput := "--- EXTRACT_DIR ---\n/shared/tmp/geoip_update_123\n--- INSTALLED_GEOIP_RPMS ---\ngeoip-data-v2.rpm\n--- GEOIP_LOOKUP_TEST ---\ncountry_code = US\n--- GEOIP_COMPLETE ---\n--- SCRIPT_EXIT_CODE: 0 ---\n" + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/mgmt/tm/util/bash" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(map[string]string{ + "commandResult": mockOutput, + }) + return + } + w.WriteHeader(http.StatusNotFound) + })) + defer server.Close() + + opts := GeoIPOptions{ + TargetType: "BIG-IP", + Method: MethodIControl, + Username: "admin", + Password: "secret", + Timeout: 2 * time.Second, + HTTPClient: server.Client(), + } + + res, err := ApplyGeoIP(context.Background(), server.URL, "/var/tmp/geoip.zip", opts, func(s string) {}) + if err != nil { + t.Fatalf("ApplyGeoIP iControl failed: %v", err) + } + if res == nil || res.MethodUsed != MethodIControl { + t.Errorf("expected MethodIControl result, got %+v", res) + } + + // Test MethodAuto with iControl first + optsAuto := opts + optsAuto.Method = MethodAuto + resAuto, err := ApplyGeoIP(context.Background(), server.URL, "/var/tmp/geoip.tgz", optsAuto, func(s string) {}) + if err != nil { + t.Fatalf("ApplyGeoIP Auto failed: %v", err) + } + if resAuto == nil || resAuto.MethodUsed != MethodIControl { + t.Errorf("expected MethodIControl result from Auto, got %+v", resAuto) + } + + // Test MethodAuto with SSH first (IdentityFile set), SSH fails, iControl succeeds + optsSSHFirst := opts + optsSSHFirst.Method = MethodAuto + optsSSHFirst.IdentityFile = "/dummy/key" + optsSSHFirst.Port = 65530 + resFallback, err := ApplyGeoIP(context.Background(), server.URL, "/var/tmp/geoip.tar.gz", optsSSHFirst, func(s string) {}) + if err != nil { + t.Fatalf("ApplyGeoIP fallback failed: %v", err) + } + if resFallback == nil || resFallback.MethodUsed != MethodIControl { + t.Errorf("expected MethodIControl from fallback, got %+v", resFallback) + } + + // Test both fail + optsDead := opts + optsDead.Port = 65530 + optsDead.HTTPClient = nil + optsDead.Timeout = 50 * time.Millisecond + _, err = ApplyGeoIP(context.Background(), "127.0.0.1", "/var/tmp/geoip.zip", optsDead, func(s string) {}) + if err == nil { + t.Errorf("expected error when both fail, got nil") + } +} diff --git a/pkg/bigip/info.go b/pkg/bigip/info.go index 5e4ea7a..60a3c9c 100644 --- a/pkg/bigip/info.go +++ b/pkg/bigip/info.go @@ -500,8 +500,7 @@ func (c *Client) GetSystemInfo(ctx context.Context) (*SystemInfo, error) { if err != nil { return nil, err } - c.setAuth(req) - resp, err := c.HTTPClient.Do(req) + resp, err := c.doWithAuth(req) if err != nil { return nil, err } diff --git a/pkg/bigip/info_test.go b/pkg/bigip/info_test.go index 9b6304d..b03804d 100644 --- a/pkg/bigip/info_test.go +++ b/pkg/bigip/info_test.go @@ -5,13 +5,17 @@ import ( "bytes" "compress/gzip" "context" + "crypto/ed25519" + "crypto/rand" "encoding/json" "fmt" "net/http" - "net/http/httptest" "os" "strings" "testing" + "time" + + "golang.org/x/crypto/ssh" ) func createTestQKViewArchive(t *testing.T, files map[string]string) []byte { @@ -397,7 +401,7 @@ sys provision asm { } func TestGetSystemInfo_RestMock(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { case "/mgmt/tm/sys/hardware": @@ -623,3 +627,105 @@ func TestSystemInfo_SummaryPlatformEnrichment(t *testing.T) { t.Errorf("Summary() did not mark BIG-IQ 8.4.2.3 as Supported:\n%s", sum4) } } + +func TestGetSystemInfoSSHMockServer(t *testing.T) { + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("failed generating key: %v", err) + } + signer, err := ssh.NewSignerFromKey(priv) + if err != nil { + t.Fatalf("failed creating signer: %v", err) + } + + serverConfig := &ssh.ServerConfig{ + PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { + if c.User() == "admin" && string(pass) == "secret" { + return nil, nil + } + return nil, fmt.Errorf("password rejected") + }, + } + serverConfig.AddHostKey(signer) + + listener, port := newPipeSSHServer() + defer listener.Close() + + mockOutput := ` +Sys::Version +Main Package + Product BIG-IP + Version 16.1.4 + Build 0.0.12 + Edition Final + +Platform + Name BIG-IP i5800 + Base MAC 00:98:76:54:32:10 + +System Information + Type C119 + Chassis Serial f5-tmsh-serial-888 +` + + go func() { + tcpConn, err := listener.Accept() + if err != nil { + return + } + defer tcpConn.Close() + + sshConn, chans, reqs, err := ssh.NewServerConn(tcpConn, serverConfig) + if err != nil { + return + } + defer sshConn.Close() + go ssh.DiscardRequests(reqs) + + for newChannel := range chans { + if newChannel.ChannelType() != "session" { + _ = newChannel.Reject(ssh.UnknownChannelType, "unknown") + continue + } + channel, requests, err := newChannel.Accept() + if err != nil { + return + } + defer channel.Close() + + go func(in <-chan *ssh.Request) { + for req := range in { + switch req.Type { + case "exec": + _ = req.Reply(true, nil) + _, _ = channel.Write([]byte(mockOutput)) + _, _ = channel.SendRequest("exit-status", false, []byte{0, 0, 0, 0}) + _ = channel.Close() + return + default: + _ = req.Reply(false, nil) + } + } + }(requests) + } + }() + + opts := SCPOptions{ + Host: "127.0.0.1", + Port: port, + Username: "admin", + Password: "secret", + Timeout: 2 * time.Second, + } + + info, err := GetSystemInfoSSH(context.Background(), opts) + if err != nil { + t.Fatalf("GetSystemInfoSSH failed: %v", err) + } + if info.ChassisSerialNumber != "f5-tmsh-serial-888" { + t.Errorf("got serial %s, want f5-tmsh-serial-888", info.ChassisSerialNumber) + } + if info.Product != "BIG-IP" { + t.Errorf("got product %s, want BIG-IP", info.Product) + } +} diff --git a/pkg/bigip/lifecycle_test.go b/pkg/bigip/lifecycle_test.go index abcb3d2..dc2bea8 100644 --- a/pkg/bigip/lifecycle_test.go +++ b/pkg/bigip/lifecycle_test.go @@ -442,3 +442,48 @@ func TestLookupPlatform(t *testing.T) { }) } } + +func TestEvaluateBIGIQLifecycle(t *testing.T) { + now2026 := time.Date(2026, time.October, 7, 0, 0, 0, 0, time.UTC) + now2024 := time.Date(2024, time.October, 7, 0, 0, 0, 0, time.UTC) + + // 1. Empty version + rEmpty := EvaluateBIGIQLifecycle("", now2026) + if rEmpty.Status != StatusUnknown { + t.Errorf("expected StatusUnknown for empty, got %v", rEmpty.Status) + } + + // 2. Invalid version + rInvalid := EvaluateBIGIQLifecycle("invalid-ver", now2026) + if rInvalid.Status != StatusUnknown { + t.Errorf("expected StatusUnknown for invalid, got %v", rInvalid.Status) + } + + // 3. Older version (e.g. 7.1.0 or 8.2.0) -> EOL + r82 := EvaluateBIGIQLifecycle("8.2.0", now2026) + if r82.Status != StatusEOL || !r82.IsEOL { + t.Errorf("expected StatusEOL for 8.2.0, got %v", r82.Status) + } + + // 4. 8.3.0 in 2024 (supported) vs 2026 (EOL) + r83Supported := EvaluateBIGIQLifecycle("8.3.0", now2024) + if r83Supported.Status != StatusSupported { + t.Errorf("expected StatusSupported for 8.3.0 in 2024, got %v", r83Supported.Status) + } + r83EOL := EvaluateBIGIQLifecycle("8.3.0", now2026) + if r83EOL.Status != StatusEOL { + t.Errorf("expected StatusEOL for 8.3.0 in 2026, got %v", r83EOL.Status) + } + + // 5. 8.4.0 in 2026 (supported) + r84 := EvaluateBIGIQLifecycle("8.4.0", now2026) + if r84.Status != StatusSupported { + t.Errorf("expected StatusSupported for 8.4.0, got %v", r84.Status) + } + + // 6. 9.0.0 (future major) + r90 := EvaluateBIGIQLifecycle("9.0.0", now2026) + if r90.Status != StatusSupported { + t.Errorf("expected StatusSupported for 9.0.0, got %v", r90.Status) + } +} diff --git a/pkg/bigip/mock_server_test.go b/pkg/bigip/mock_server_test.go new file mode 100644 index 0000000..db811fe --- /dev/null +++ b/pkg/bigip/mock_server_test.go @@ -0,0 +1,222 @@ +package bigip + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "sync" + "time" + + "myf5-cli/pkg/client" +) + +type roundTripFunc func(req *http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +type mockServer struct { + URL string + client *http.Client +} + +func (m *mockServer) Close() {} +func (m *mockServer) Client() *http.Client { return m.client } + +var ( + mockPortSeqMu sync.Mutex + mockPortSeq = 18000 +) + +func newMockServer(handler http.Handler) *mockServer { + mockPortSeqMu.Lock() + mockPortSeq++ + port := mockPortSeq + mockPortSeqMu.Unlock() + + return &mockServer{ + URL: fmt.Sprintf("http://127.0.0.1:%d", port), + client: &http.Client{ + Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + return rec.Result(), nil + }), + }, + } +} + +type bufferedPipeConn struct { + rCh <-chan []byte + wCh chan<- []byte + rClosed <-chan struct{} + wClosed chan struct{} + closeOnce sync.Once + readBuf []byte +} + +func newBufferedConnPair() (net.Conn, net.Conn) { + ch1 := make(chan []byte, 1024) + ch2 := make(chan []byte, 1024) + closed1 := make(chan struct{}) + closed2 := make(chan struct{}) + c1 := &bufferedPipeConn{rCh: ch1, wCh: ch2, rClosed: closed1, wClosed: closed2} + c2 := &bufferedPipeConn{rCh: ch2, wCh: ch1, rClosed: closed2, wClosed: closed1} + return c1, c2 +} + +func (c *bufferedPipeConn) Read(b []byte) (int, error) { + if len(c.readBuf) > 0 { + n := copy(b, c.readBuf) + c.readBuf = c.readBuf[n:] + return n, nil + } + // Prioritize draining data channel first + select { + case data, ok := <-c.rCh: + if !ok { + return 0, io.EOF + } + n := copy(b, data) + if n < len(data) { + c.readBuf = data[n:] + } + return n, nil + default: + } + + select { + case data, ok := <-c.rCh: + if !ok { + return 0, io.EOF + } + n := copy(b, data) + if n < len(data) { + c.readBuf = data[n:] + } + return n, nil + case <-c.rClosed: + select { + case data, ok := <-c.rCh: + if ok { + n := copy(b, data) + if n < len(data) { + c.readBuf = data[n:] + } + return n, nil + } + default: + } + return 0, io.EOF + } +} + +func (c *bufferedPipeConn) Write(b []byte) (int, error) { + select { + case <-c.wClosed: + return 0, io.ErrClosedPipe + default: + } + cp := make([]byte, len(b)) + copy(cp, b) + select { + case c.wCh <- cp: + return len(b), nil + case <-c.wClosed: + return 0, io.ErrClosedPipe + } +} + +func (c *bufferedPipeConn) Close() error { + c.closeOnce.Do(func() { + close(c.wClosed) + }) + return nil +} + +func (c *bufferedPipeConn) LocalAddr() net.Addr { + return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 22} +} +func (c *bufferedPipeConn) RemoteAddr() net.Addr { + return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 22} +} +func (c *bufferedPipeConn) SetDeadline(t time.Time) error { return nil } +func (c *bufferedPipeConn) SetReadDeadline(t time.Time) error { return nil } +func (c *bufferedPipeConn) SetWriteDeadline(t time.Time) error { return nil } + +type pipeSSHServer struct { + addr string + conns chan net.Conn + done chan struct{} + port int +} + +var ( + pipeSSHMu sync.Mutex + pipeSSHServers = make(map[string]*pipeSSHServer) + pipeSSHPortSeq = 22000 +) + +func newPipeSSHServer() (*pipeSSHServer, int) { + pipeSSHMu.Lock() + defer pipeSSHMu.Unlock() + pipeSSHPortSeq++ + port := pipeSSHPortSeq + addr := fmt.Sprintf("127.0.0.1:%d", port) + s := &pipeSSHServer{ + addr: addr, + conns: make(chan net.Conn, 1), + done: make(chan struct{}), + port: port, + } + pipeSSHServers[addr] = s + return s, port +} + +func (s *pipeSSHServer) Accept() (net.Conn, error) { + select { + case c := <-s.conns: + return c, nil + case <-s.done: + return nil, net.ErrClosed + } +} + +func (s *pipeSSHServer) Close() error { + pipeSSHMu.Lock() + delete(pipeSSHServers, s.addr) + pipeSSHMu.Unlock() + close(s.done) + return nil +} + +func init() { + _ = os.Setenv("NO_PROXY", "127.0.0.1,localhost,::1") + client.SetDialContext(func(ctx context.Context, network, addr string) (net.Conn, error) { + pipeSSHMu.Lock() + s, ok := pipeSSHServers[addr] + pipeSSHMu.Unlock() + if ok { + c1, c2 := newBufferedConnPair() + select { + case s.conns <- c2: + return c1, nil + case <-s.done: + c1.Close() + c2.Close() + return nil, net.ErrClosed + case <-ctx.Done(): + c1.Close() + c2.Close() + return nil, ctx.Err() + } + } + var d net.Dialer + return d.DialContext(ctx, network, addr) + }) +} diff --git a/pkg/bigip/scp_test.go b/pkg/bigip/scp_test.go index aa567f1..7d7d9f3 100644 --- a/pkg/bigip/scp_test.go +++ b/pkg/bigip/scp_test.go @@ -6,6 +6,8 @@ import ( "context" "crypto/ed25519" "crypto/rand" + "crypto/x509" + "encoding/pem" "fmt" "io" "net" @@ -77,6 +79,26 @@ func TestBuildSSHClientConfig(t *testing.T) { t.Errorf("expected error with missing key file, got nil") } + // Invalid username + _, err = BuildSSHClientConfig(SCPOptions{ + Host: "127.0.0.1", + Username: "admin;rm", + Password: "testpassword", + }) + if err == nil { + t.Errorf("expected error with invalid username, got nil") + } + + // Invalid password + _, err = BuildSSHClientConfig(SCPOptions{ + Host: "127.0.0.1", + Username: "admin", + Password: "test password", + }) + if err == nil { + t.Errorf("expected error with invalid password, got nil") + } + // Password auth cfg, err := BuildSSHClientConfig(SCPOptions{ Host: "127.0.0.1", @@ -92,6 +114,40 @@ func TestBuildSSHClientConfig(t *testing.T) { if len(cfg.Auth) == 0 { t.Errorf("expected auth methods to be present") } + + // PasswordBytes auth + cfgBytes, err := BuildSSHClientConfig(SCPOptions{ + Host: "127.0.0.1", + Username: "admin", + PasswordBytes: []byte("testpassword"), + }) + if err != nil || len(cfgBytes.Auth) == 0 { + t.Fatalf("expected valid config with passwordBytes, got: %v", err) + } + + // KeyPath auth + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + pkcs8, err := x509.MarshalPKCS8PrivateKey(priv) + if err != nil { + t.Fatal(err) + } + pemBytes := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}) + keyFile := filepath.Join(t.TempDir(), "id_test") + if err := os.WriteFile(keyFile, pemBytes, 0600); err != nil { + t.Fatal(err) + } + + cfgKey, err := BuildSSHClientConfig(SCPOptions{ + Host: "127.0.0.1", + Username: "admin", + KeyPath: keyFile, + }) + if err != nil || len(cfgKey.Auth) == 0 { + t.Fatalf("expected valid config with keyPath, got: %v", err) + } } func TestSCPUploadMockServer(t *testing.T) { @@ -118,15 +174,9 @@ func TestSCPUploadMockServer(t *testing.T) { } serverConfig.AddHostKey(signer) - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to listen on local port: %v", err) - } + listener, port := newPipeSSHServer() defer listener.Close() - _, portStr, _ := net.SplitHostPort(listener.Addr().String()) - port, _ := strconv.Atoi(portStr) - var receivedHeader string var receivedBody []byte @@ -286,14 +336,9 @@ func TestSCPDownloadMockServer(t *testing.T) { } serverConfig.AddHostKey(signer) - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } + listener, port := newPipeSSHServer() defer listener.Close() - port := listener.Addr().(*net.TCPAddr).Port - go func() { nConn, err := listener.Accept() if err != nil { @@ -437,14 +482,9 @@ func TestQKViewSSHTmshFallback(t *testing.T) { } serverConfig.AddHostKey(signer) - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } + listener, port := newPipeSSHServer() defer listener.Close() - port := listener.Addr().(*net.TCPAddr).Port - var ( mu sync.Mutex executedCmds []string diff --git a/pkg/bigip/upload.go b/pkg/bigip/upload.go index 64053a4..5a99e7a 100644 --- a/pkg/bigip/upload.go +++ b/pkg/bigip/upload.go @@ -104,11 +104,10 @@ func (c *Client) UploadFile(ctx context.Context, localPath string, remoteFilenam if err != nil { return "", fmt.Errorf("failed to create upload request: %w", err) } - c.setAuth(req) req.Header.Set("Content-Type", "application/octet-stream") req.Header.Set("Content-Range", contentRange) - resp, err := c.HTTPClient.Do(req) + resp, err := c.doWithAuth(req) if err != nil { return "", fmt.Errorf("upload chunk failed at bytes %d-%d: %w", start, end, err) } @@ -168,10 +167,9 @@ func (c *Client) CopyRemoteFile(ctx context.Context, srcPath, destDir string) (s if err != nil { return "", err } - c.setAuth(req) req.Header.Set("Content-Type", "application/json") - resp, err := c.HTTPClient.Do(req) + resp, err := c.doWithAuth(req) if err != nil { return "", fmt.Errorf("failed executing remote copy on appliance: %w", err) } diff --git a/pkg/bigip/upload_test.go b/pkg/bigip/upload_test.go index 2cfce11..e18ed1e 100644 --- a/pkg/bigip/upload_test.go +++ b/pkg/bigip/upload_test.go @@ -4,7 +4,6 @@ import ( "context" "io" "net/http" - "net/http/httptest" "os" "path/filepath" "strings" @@ -26,7 +25,7 @@ func TestUploadFile(t *testing.T) { var uploadedBytes []byte var receivedRanges []string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/mgmt/shared/file-transfer/uploads/") { crange := r.Header.Get("Content-Range") receivedRanges = append(receivedRanges, crange) @@ -46,6 +45,7 @@ func TestUploadFile(t *testing.T) { defer server.Close() client := NewClient(server.URL, 0, "admin", "secret") + client.HTTPClient = server.Client() var lastTransferred, lastTotal int64 progressCb := func(transferred, total int64) { lastTransferred = transferred @@ -85,7 +85,7 @@ func TestUploadFileErrors(t *testing.T) { } // Server returning 500 Internal Server Error - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) _, _ = w.Write([]byte("disk full")) })) @@ -95,6 +95,7 @@ func TestUploadFileErrors(t *testing.T) { _ = os.WriteFile(tmpFile, []byte("data"), 0600) errorClient := NewClient(server.URL, 0, "admin", "secret") + errorClient.HTTPClient = server.Client() _, err = errorClient.UploadFile(context.Background(), tmpFile, "", nil) if err == nil { t.Errorf("expected error on HTTP 500, got nil") @@ -106,7 +107,7 @@ func TestUploadFileErrors(t *testing.T) { func TestCopyRemoteFile(t *testing.T) { var receivedCommand string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/mgmt/tm/util/bash" && r.Method == http.MethodPost { b, _ := io.ReadAll(r.Body) receivedCommand = string(b) @@ -119,6 +120,7 @@ func TestCopyRemoteFile(t *testing.T) { defer server.Close() client := NewClient(server.URL, 0, "admin", "secret") + client.HTTPClient = server.Client() destPath, err := client.CopyRemoteFile(context.Background(), "/var/config/rest/downloads/BIGIP-17.1.1.iso", "/shared/images") if err != nil { t.Fatalf("CopyRemoteFile failed: %v", err) diff --git a/pkg/cases/client.go b/pkg/cases/client.go index 9f46b0a..211079c 100644 --- a/pkg/cases/client.go +++ b/pkg/cases/client.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "net/url" + "os" "strings" "time" @@ -67,7 +68,11 @@ func NewClient(token string, baseFQDN string) *Client { // An empty apiKey falls back to DefaultKParam. func NewClientWithKey(token, baseFQDN, apiKey string) *Client { if baseFQDN == "" { - baseFQDN = DefaultSupportFQDN + if envFQDN := os.Getenv("F5_SUPPORT_FQDN"); envFQDN != "" { + baseFQDN = envFQDN + } else { + baseFQDN = DefaultSupportFQDN + } } if apiKey == "" { apiKey = DefaultKParam diff --git a/pkg/cases/client_test.go b/pkg/cases/client_test.go index 9babf09..db0495a 100644 --- a/pkg/cases/client_test.go +++ b/pkg/cases/client_test.go @@ -10,8 +10,35 @@ import ( "testing" ) +type roundTripFunc func(req *http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +type mockServer struct { + URL string + client *http.Client +} + +func (m *mockServer) Close() {} +func (m *mockServer) Client() *http.Client { return m.client } + +func newMockServer(handler http.Handler) *mockServer { + return &mockServer{ + URL: "https://mock.cases.f5.invalid", + client: &http.Client{ + Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + return rec.Result(), nil + }), + }, + } +} + func TestListCases(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/case-management/v1/cases" { t.Errorf("unexpected path: %s", r.URL.Path) } @@ -54,7 +81,7 @@ func TestListCases(t *testing.T) { // with a {"comments": ...} JSON payload and decodes the response envelope. func TestAddCommentRequestShape(t *testing.T) { var gotMethod, gotPath, gotBody string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotMethod = r.Method gotPath = r.URL.Path b, _ := io.ReadAll(r.Body) @@ -98,7 +125,7 @@ func TestAddCommentRequestShape(t *testing.T) { func TestListCasesDecodesLiveFieldNames(t *testing.T) { payload := `{"data":[{"caseNumber":"01234567","subject":"Example Case Subject","status":"Resolution Provided","priority":"3 - Site Not At Risk","dateOpened":"2025-09-12"}]}` - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if _, err := w.Write([]byte(payload)); err != nil { t.Fatalf("write: %v", err) @@ -135,7 +162,7 @@ func TestBodyReportedErrorsBecomeErrors(t *testing.T) { const payload = `{"status":"Error","message":"Something went wrong upstream","isError":true,"data":null}` t.Run("ListCases", func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) // 2xx despite the failure io.WriteString(w, payload) @@ -155,7 +182,7 @@ func TestBodyReportedErrorsBecomeErrors(t *testing.T) { }) t.Run("GetMetadata", func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) io.WriteString(w, payload) @@ -172,7 +199,7 @@ func TestBodyReportedErrorsBecomeErrors(t *testing.T) { }) t.Run("GetCase", func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) io.WriteString(w, payload) @@ -191,7 +218,7 @@ func TestBodyReportedErrorsBecomeErrors(t *testing.T) { // A healthy response must still succeed: the check must not reject // everything. t.Run("success is unaffected", func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") io.WriteString(w, `{"status":"Success","isError":false,"data":[]}`) })) @@ -205,3 +232,165 @@ func TestBodyReportedErrorsBecomeErrors(t *testing.T) { } }) } + +func TestClientMethods(t *testing.T) { + var nilClient *Client + if nilClient.String() != "" { + t.Errorf("nil Client.String() = %q, want ", nilClient.String()) + } + nilClient.Zero() + + c := NewClient("secret-token", "https://api.f5.com") + if !strings.Contains(c.String(), "https://api.f5.com") { + t.Errorf("String() missing BaseFQDN: %s", c.String()) + } + if strings.Contains(c.String(), "secret-token") { + t.Errorf("String() leaked token: %s", c.String()) + } + if c.GoString() != c.String() { + t.Errorf("GoString() != String()") + } + + cEmpty := NewClient("", "https://api.f5.com") + if !strings.Contains(cEmpty.String(), "[EMPTY]") { + t.Errorf("String() should show [EMPTY] for empty token") + } + + c.Zero() + if c.Token != "" || c.KParam != "" { + t.Errorf("Zero() did not clear tokens") + } +} + +func TestEntitlementAndValidation(t *testing.T) { + if got := EntitlementFieldFor("NGINX"); got != "subscriptionId" { + t.Errorf("EntitlementFieldFor(NGINX) = %s, want subscriptionId", got) + } + if got := EntitlementFieldFor("Aspen Mesh"); got != "subscriptionId" { + t.Errorf("EntitlementFieldFor(Aspen Mesh) = %s, want subscriptionId", got) + } + if got := EntitlementFieldFor("BIG-IP"); got != "serialNumber" { + t.Errorf("EntitlementFieldFor(BIG-IP) = %s, want serialNumber", got) + } + + req := RequiredCreateFields() + if len(req) == 0 { + t.Errorf("RequiredCreateFields() returned empty slice") + } + + err := &ErrMissingCreateFields{Missing: []string{"subject", "serialNumber"}} + errStr := err.Error() + if !strings.Contains(errStr, "missing required field(s)") || !strings.Contains(errStr, "Salesforce") { + t.Errorf("unexpected error string: %s", errStr) + } + + err2 := &ErrMissingCreateFields{Missing: []string{"subject"}} + if strings.Contains(err2.Error(), "Salesforce") { + t.Errorf("unexpected Salesforce notice for non-serial error") + } +} + +func TestCreateCase(t *testing.T) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("method = %s, want POST", r.Method) + } + if r.URL.Path != "/case-management/v1/cases" { + t.Errorf("path = %s, want /case-management/v1/cases", r.URL.Path) + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"status":"Success","message":"Case created","isError":false,"code":201,"data":{"caseNumber":"01234567"}}`) + })) + defer server.Close() + + c := NewClient("tok", server.URL) + c.HTTPClient = server.Client() + + _, err := c.CreateCase(context.Background(), map[string]interface{}{"subject": "test"}) + if err == nil { + t.Fatal("expected error with missing fields") + } + + payload := map[string]interface{}{ + "subject": "Test Case", + "description": "Test Description", + "priority": "3 - Site Not At Risk", + "productFamily": "BIG-IP", + "product": "BIG-IP", + "version": "17.1.0", + "reasonForContact": "Question", + "caseOwnerEmail": "user@example.com", + "preferredContactMethod": "Email", + "timezone": "UTC", + "serialNumber": "f5-1234", + } + resp, err := c.CreateCase(context.Background(), payload) + if err != nil { + t.Fatalf("CreateCase failed: %v", err) + } + if resp.Data.CaseNumber != "01234567" { + t.Errorf("got case number %s, want 01234567", resp.Data.CaseNumber) + } + + respUnchecked, err := c.CreateCaseUnchecked(context.Background(), map[string]interface{}{"foo": "bar"}) + if err != nil { + t.Fatalf("CreateCaseUnchecked failed: %v", err) + } + if respUnchecked.Data.CaseNumber != "01234567" { + t.Errorf("got case number %s, want 01234567", respUnchecked.Data.CaseNumber) + } +} + +func TestGetCaseNotFound(t *testing.T) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"status":"Success","isError":false,"data":[]}`) + })) + defer server.Close() + + c := NewClient("tok", server.URL) + c.HTTPClient = server.Client() + + _, err := c.GetCase(context.Background(), "99999999") + if err == nil || !strings.Contains(err.Error(), "not found") { + t.Errorf("expected not found error, got %v", err) + } +} + +func TestGetCaseSuccess(t *testing.T) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"status":"Success","isError":false,"data":[{"caseNumber":"01234567","subject":"test"}]}`) + })) + defer server.Close() + + c := NewClient("tok", server.URL) + c.HTTPClient = server.Client() + + detail, err := c.GetCase(context.Background(), "01234567") + if err != nil { + t.Fatalf("GetCase failed: %v", err) + } + if detail.CaseNumber != "01234567" { + t.Errorf("got case number %s, want 01234567", detail.CaseNumber) + } +} + +func TestContactDisplayName(t *testing.T) { + c1 := CaseContact{Name: "Full Name"} + if c1.DisplayName() != "Full Name" { + t.Errorf("got %s, want Full Name", c1.DisplayName()) + } + c2 := CaseContact{FirstName: "First", LastName: "Last"} + if c2.DisplayName() != "First Last" { + t.Errorf("got %s, want First Last", c2.DisplayName()) + } + c3 := CaseContact{FirstName: "OnlyFirst"} + if c3.DisplayName() != "OnlyFirst" { + t.Errorf("got %s, want OnlyFirst", c3.DisplayName()) + } + c4 := CaseContact{LastName: "OnlyLast"} + if c4.DisplayName() != "OnlyLast" { + t.Errorf("got %s, want OnlyLast", c4.DisplayName()) + } +} diff --git a/pkg/client/proxy.go b/pkg/client/proxy.go index 970073a..38d9d83 100644 --- a/pkg/client/proxy.go +++ b/pkg/client/proxy.go @@ -20,8 +20,27 @@ import ( var ( globalProxyMu sync.RWMutex globalProxyURL *url.URL + + proxyDialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, network, addr) + } ) +// SetDialContext overrides the internal dialer for testing or custom transports. +func SetDialContext(fn func(ctx context.Context, network, addr string) (net.Conn, error)) { + globalProxyMu.Lock() + defer globalProxyMu.Unlock() + if fn == nil { + proxyDialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, network, addr) + } + return + } + proxyDialContext = fn +} + // SetGlobalProxy sets the global proxy URL for all HTTP clients and dialers. func SetGlobalProxy(proxyStr string) error { globalProxyMu.Lock() @@ -269,8 +288,7 @@ func DialProxy(ctx context.Context, network, targetAddr string, explicitProxy *u // If no proxy is configured, or targetAddr is bypassed via NO_PROXY, dial directly if proxyURL == nil || ShouldBypassProxy(targetAddr, getNoProxyEnv()) { - var d net.Dialer - return d.DialContext(ctx, network, targetAddr) + return proxyDialContext(ctx, network, targetAddr) } scheme := strings.ToLower(proxyURL.Scheme) @@ -295,8 +313,7 @@ func dialHTTPConnect(ctx context.Context, proxyURL *url.URL, targetAddr string) } } - var d net.Dialer - conn, err := d.DialContext(ctx, "tcp", proxyHost) + conn, err := proxyDialContext(ctx, "tcp", proxyHost) if err != nil { return nil, fmt.Errorf("failed connecting to proxy %s: %w", proxyHost, err) } @@ -362,8 +379,7 @@ func dialSOCKS5(ctx context.Context, proxyURL *url.URL, targetAddr string) (net. proxyHost += ":1080" } - var d net.Dialer - conn, err := d.DialContext(ctx, "tcp", proxyHost) + conn, err := proxyDialContext(ctx, "tcp", proxyHost) if err != nil { return nil, fmt.Errorf("failed connecting to SOCKS5 proxy %s: %w", proxyHost, err) } diff --git a/pkg/client/proxy_test.go b/pkg/client/proxy_test.go index 5d6fd8e..c06847c 100644 --- a/pkg/client/proxy_test.go +++ b/pkg/client/proxy_test.go @@ -3,17 +3,102 @@ package client import ( "bufio" "context" + "fmt" "io" "net" "net/http" - "net/http/httptest" "net/url" "os" "strconv" + "strings" + "sync" "testing" "time" ) +var ( + memListenersMu sync.Mutex + memListeners = make(map[string]*inMemoryListener) + portSeq = 10000 +) + +type inMemoryListener struct { + addr string + conns chan net.Conn + done chan struct{} + once sync.Once +} + +func newMemListener() *inMemoryListener { + memListenersMu.Lock() + portSeq++ + addr := fmt.Sprintf("127.0.0.1:%d", portSeq) + l := &inMemoryListener{ + addr: addr, + conns: make(chan net.Conn), + done: make(chan struct{}), + } + memListeners[addr] = l + memListenersMu.Unlock() + return l +} + +func (l *inMemoryListener) Accept() (net.Conn, error) { + select { + case c := <-l.conns: + return c, nil + case <-l.done: + return nil, net.ErrClosed + } +} + +func (l *inMemoryListener) Close() error { + l.once.Do(func() { + close(l.done) + memListenersMu.Lock() + delete(memListeners, l.addr) + memListenersMu.Unlock() + }) + return nil +} + +func (l *inMemoryListener) Addr() net.Addr { + return &testAddr{addr: l.addr} +} + +type testAddr struct { + addr string +} + +func (a *testAddr) Network() string { return "tcp" } +func (a *testAddr) String() string { return a.addr } + +func memDial(ctx context.Context, network, addr string) (net.Conn, error) { + memListenersMu.Lock() + l, ok := memListeners[addr] + memListenersMu.Unlock() + if !ok { + return nil, fmt.Errorf("connect: operation not permitted (mock %s)", addr) + } + c1, c2 := net.Pipe() + select { + case l.conns <- c2: + return c1, nil + case <-ctx.Done(): + c1.Close() + c2.Close() + return nil, ctx.Err() + case <-l.done: + c1.Close() + c2.Close() + return nil, net.ErrClosed + } +} + +func init() { + proxyDialContext = memDial +} + func TestParseProxyURL(t *testing.T) { tests := []struct { name string @@ -152,10 +237,7 @@ func TestShouldBypassProxy(t *testing.T) { func TestHTTPConnectProxyTunnel(t *testing.T) { // Start target backend echo server backendReceived := make(chan string, 1) - backendListener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to start backend listener: %v", err) - } + backendListener := newMemListener() defer backendListener.Close() go func() { @@ -174,10 +256,7 @@ func TestHTTPConnectProxyTunnel(t *testing.T) { // Start mock HTTP CONNECT proxy connectHostReceived := make(chan string, 1) - proxyListener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to start proxy listener: %v", err) - } + proxyListener := newMemListener() defer proxyListener.Close() go func() { @@ -195,7 +274,7 @@ func TestHTTPConnectProxyTunnel(t *testing.T) { if req.Method == http.MethodConnect { connectHostReceived <- req.Host // Dial target - targetConn, err := net.Dial("tcp", req.Host) + targetConn, err := memDial(context.Background(), "tcp", req.Host) if err != nil { _, _ = clientConn.Write([]byte("HTTP/1.1 502 Bad Gateway\r\n\r\n")) return @@ -258,10 +337,7 @@ func TestHTTPConnectProxyTunnel(t *testing.T) { func TestSOCKS5ProxyTunnel(t *testing.T) { // Start target backend echo server - backendListener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to start backend listener: %v", err) - } + backendListener := newMemListener() defer backendListener.Close() go func() { @@ -278,10 +354,7 @@ func TestSOCKS5ProxyTunnel(t *testing.T) { backendAddr := backendListener.Addr().String() // Start mock SOCKS5 server - socksListener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to start socks5 listener: %v", err) - } + socksListener := newMemListener() defer socksListener.Close() go func() { @@ -318,7 +391,7 @@ func TestSOCKS5ProxyTunnel(t *testing.T) { port := int(addrPort[4])<<8 | int(addrPort[5]) target := net.JoinHostPort(ip.String(), strconv.Itoa(port)) - targetConn, err := net.Dial("tcp", target) + targetConn, err := memDial(context.Background(), "tcp", target) if err != nil { _, _ = clientConn.Write([]byte{0x05, 0x05, 0x00, 0x01, 0, 0, 0, 0, 0, 0}) return @@ -361,10 +434,7 @@ func TestSOCKS5ProxyTunnel(t *testing.T) { func TestSOCKS5ProxyTunnel_IPv6Target(t *testing.T) { // Start mock SOCKS5 server that verifies ATYP=4 (IPv6) request serialization - socksListener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to start socks5 listener: %v", err) - } + socksListener := newMemListener() defer socksListener.Close() reqReceived := make(chan []byte, 1) @@ -458,20 +528,27 @@ func TestSOCKS5ProxyTunnel_IPv6Target(t *testing.T) { func TestHTTPTransportHonorsProxy(t *testing.T) { proxyHit := false - proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - proxyHit = true - w.Header().Set("Content-Type", "text/plain") - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte("proxied-response")) - })) + proxyServerListener := newMemListener() + proxyServer := &http.Server{ + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxyHit = true + w.Header().Set("Content-Type", "text/plain") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("proxied-response")) + }), + } + go func() { + _ = proxyServer.Serve(proxyServerListener) + }() defer proxyServer.Close() - proxyURL, err := url.Parse(proxyServer.URL) + proxyURL, err := url.Parse("http://" + proxyServerListener.Addr().String()) if err != nil { t.Fatalf("failed to parse proxy URL: %v", err) } transport := NewProductionTransportWithProxy(SecureTLSConfig(true), proxyURL) + transport.DialContext = memDial httpClient := &http.Client{Transport: transport, Timeout: 5 * time.Second} req, err := http.NewRequest(http.MethodGet, "http://target.example.invalid/test", nil) @@ -525,3 +602,261 @@ func TestResolveEnvProxy(t *testing.T) { func bufioReader(conn net.Conn) *bufio.Reader { return bufio.NewReader(conn) } + +func TestProxyFuncAndCheckNoProxy(t *testing.T) { + os.Setenv("NO_PROXY", "example.com,.internal") + defer os.Unsetenv("NO_PROXY") + + explicit, _ := url.Parse("http://explicit-proxy:8080") + fn := ProxyFunc(explicit) + + req1, _ := http.NewRequest(http.MethodGet, "https://api.f5.com/path", nil) + u, err := fn(req1) + if err != nil || u == nil || u.String() != "http://explicit-proxy:8080" { + t.Errorf("expected explicit proxy, got %v (err: %v)", u, err) + } + + req2, _ := http.NewRequest(http.MethodGet, "https://example.com/path", nil) + u2, err := fn(req2) + if err != nil || u2 != nil { + t.Errorf("expected nil proxy for NO_PROXY target, got %v", u2) + } + + uNilTarget, err := checkNoProxy(explicit, nil) + if err != nil || uNilTarget != explicit { + t.Errorf("checkNoProxy with nil target should return proxyURL") + } + + fnGlobal := ProxyFunc(nil) + SetGlobalProxy("http://global-proxy:8080") + defer ClearGlobalProxy() + + uGlobal, err := fnGlobal(req1) + if err != nil || uGlobal == nil || uGlobal.String() != "http://global-proxy:8080" { + t.Errorf("expected global proxy, got %v", uGlobal) + } + ClearGlobalProxy() + + os.Setenv("MYF5_PROXY", "http://env-myf5-proxy:8080") + defer os.Unsetenv("MYF5_PROXY") + uEnv, err := fnGlobal(req1) + if err != nil || uEnv == nil || uEnv.String() != "http://env-myf5-proxy:8080" { + t.Errorf("expected MYF5_PROXY, got %v", uEnv) + } + os.Unsetenv("MYF5_PROXY") + + os.Setenv("F5_PROXY", "http://env-f5-proxy:8080") + defer os.Unsetenv("F5_PROXY") + uF5Env, err := fnGlobal(req1) + if err != nil || uF5Env == nil || uF5Env.String() != "http://env-f5-proxy:8080" { + t.Errorf("expected F5_PROXY, got %v", uF5Env) + } +} + +func TestDialProxyBranches(t *testing.T) { + ClearGlobalProxy() + for _, envKey := range []string{"MYF5_PROXY", "F5_PROXY", "ALL_PROXY", "all_proxy", "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "NO_PROXY", "no_proxy"} { + oldVal := os.Getenv(envKey) + defer os.Setenv(envKey, oldVal) + os.Unsetenv(envKey) + } + + ctx := context.Background() + + listener := newMemListener() + defer listener.Close() + + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + conn.Close() + } + }() + + conn, err := DialProxy(ctx, "tcp", listener.Addr().String(), nil) + if err != nil { + t.Fatalf("DialProxy direct dial failed: %v", err) + } + conn.Close() + + badScheme, _ := url.Parse("ftp://proxy.example.com:21") + _, err = DialProxy(ctx, "tcp", "example.com:80", badScheme) + if err == nil || !strings.Contains(err.Error(), "unsupported proxy protocol") { + t.Errorf("expected unsupported proxy protocol error, got %v", err) + } + + os.Setenv("NO_PROXY", "127.0.0.1") + dummyProxy, _ := url.Parse("http://192.0.2.1:8080") + connBypass, err := DialProxy(ctx, "tcp", listener.Addr().String(), dummyProxy) + if err != nil { + t.Fatalf("DialProxy with NO_PROXY bypass failed: %v", err) + } + connBypass.Close() +} + +func TestHTTPConnectProxyErrorsAndAuth(t *testing.T) { + proxy407 := newMemListener() + defer proxy407.Close() + + go func() { + for { + conn, err := proxy407.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer c.Close() + r := bufio.NewReader(c) + req, err := http.ReadRequest(r) + if err != nil { + return + } + if req.Header.Get("Proxy-Authorization") == "" { + io.WriteString(c, "HTTP/1.1 407 Proxy Authentication Required\r\n\r\n") + } else { + io.WriteString(c, "HTTP/1.1 200 Connection Established\r\n\r\n") + } + }(conn) + } + }() + + proxyURL407, _ := ParseProxyURL("http://" + proxy407.Addr().String()) + ctx := context.Background() + + _, err := DialProxy(ctx, "tcp", "target.corp:443", proxyURL407) + if err == nil || !strings.Contains(err.Error(), "HTTP 407") { + t.Errorf("expected HTTP 407 error, got %v", err) + } + + proxyWithAuth, _ := ParseProxyURL("http://user:pass@" + proxy407.Addr().String()) + connAuth, err := DialProxy(ctx, "tcp", "target.corp:443", proxyWithAuth) + if err != nil { + t.Fatalf("expected proxy with auth to succeed, got %v", err) + } + connAuth.Close() + + proxy500 := newMemListener() + defer proxy500.Close() + go func() { + conn, err := proxy500.Accept() + if err == nil { + defer conn.Close() + r := bufio.NewReader(conn) + _, _ = http.ReadRequest(r) + io.WriteString(conn, "HTTP/1.1 500 Internal Server Error\r\n\r\n") + } + }() + proxyURL500, _ := ParseProxyURL("http://" + proxy500.Addr().String()) + _, err = DialProxy(ctx, "tcp", "target.corp:443", proxyURL500) + if err == nil || !strings.Contains(err.Error(), "500") { + t.Errorf("expected 500 error from proxy, got %v", err) + } +} + +func TestSOCKS5ErrorsAndAuth(t *testing.T) { + socksAuth := newMemListener() + defer socksAuth.Close() + + go func() { + for { + conn, err := socksAuth.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer c.Close() + greet := make([]byte, 128) + n, err := c.Read(greet) + if err != nil || n < 3 { + return + } + c.Write([]byte{0x05, 0x02}) + + authBuf := make([]byte, 128) + an, err := c.Read(authBuf) + if err != nil || an < 2 { + return + } + c.Write([]byte{0x01, 0x00}) + + reqBuf := make([]byte, 128) + rn, err := c.Read(reqBuf) + if err != nil || rn < 4 { + return + } + c.Write([]byte{0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0}) + }(conn) + } + }() + + proxyAuthURL, _ := ParseProxyURL("socks5://testuser:testpass@" + socksAuth.Addr().String()) + ctx := context.Background() + + conn, err := DialProxy(ctx, "tcp", "127.0.0.1:8080", proxyAuthURL) + if err != nil { + t.Fatalf("SOCKS5 auth connection failed: %v", err) + } + conn.Close() + + socksReject := newMemListener() + defer socksReject.Close() + go func() { + c, err := socksReject.Accept() + if err == nil { + defer c.Close() + buf := make([]byte, 128) + c.Read(buf) + c.Write([]byte{0x05, 0xFF}) + } + }() + proxyRejectURL, _ := ParseProxyURL("socks5://" + socksReject.Addr().String()) + _, err = DialProxy(ctx, "tcp", "127.0.0.1:8080", proxyRejectURL) + if err == nil || !strings.Contains(err.Error(), "rejected") { + t.Errorf("expected SOCKS5 rejected auth error, got %v", err) + } + + socksBadVer := newMemListener() + defer socksBadVer.Close() + go func() { + c, err := socksBadVer.Accept() + if err == nil { + defer c.Close() + buf := make([]byte, 128) + c.Read(buf) + c.Write([]byte{0x04, 0x00}) + } + }() + proxyBadVerURL, _ := ParseProxyURL("socks5://" + socksBadVer.Addr().String()) + _, err = DialProxy(ctx, "tcp", "127.0.0.1:8080", proxyBadVerURL) + if err == nil || !strings.Contains(err.Error(), "invalid SOCKS version") { + t.Errorf("expected invalid SOCKS version error, got %v", err) + } +} + +func TestSetDialContext(t *testing.T) { + customDialed := false + customFn := func(ctx context.Context, network, addr string) (net.Conn, error) { + customDialed = true + c1, _ := net.Pipe() + return c1, nil + } + + SetDialContext(customFn) + conn, err := proxyDialContext(context.Background(), "tcp", "127.0.0.1:9999") + if err != nil { + t.Fatalf("unexpected dial error: %v", err) + } + conn.Close() + if !customDialed { + t.Errorf("expected custom dialer to be invoked") + } + + // Reset to nil + SetDialContext(nil) + if proxyDialContext == nil { + t.Errorf("expected non-nil default dialer after SetDialContext(nil)") + } +} diff --git a/pkg/client/tls.go b/pkg/client/tls.go index a0d2094..72aeeb6 100644 --- a/pkg/client/tls.go +++ b/pkg/client/tls.go @@ -1,6 +1,7 @@ package client import ( + "context" "crypto/tls" "fmt" "net" @@ -50,10 +51,12 @@ func NewProductionTransportWithProxy(tlsConfig *tls.Config, explicitProxy *url.U return &http.Transport{ Proxy: ProxyFunc(explicitProxy), // Restrict TCP connect and DNS dial phases to prevent slowloris hanging - DialContext: (&net.Dialer{ - Timeout: 15 * time.Second, - KeepAlive: 30 * time.Second, - }).DialContext, + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + globalProxyMu.RLock() + d := proxyDialContext + globalProxyMu.RUnlock() + return d(ctx, network, addr) + }, TLSClientConfig: tlsConfig, // Limit TLS negotiation phase duration TLSHandshakeTimeout: 10 * time.Second, diff --git a/pkg/client/tls_test.go b/pkg/client/tls_test.go index 9433105..36d31e2 100644 --- a/pkg/client/tls_test.go +++ b/pkg/client/tls_test.go @@ -1,6 +1,7 @@ package client import ( + "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" @@ -9,6 +10,7 @@ import ( "crypto/x509/pkix" "encoding/pem" "math/big" + "net" "net/http" "os" "path/filepath" @@ -61,6 +63,30 @@ func TestNewClients(t *testing.T) { } } +func TestNewProductionTransportWithProxy(t *testing.T) { + customDialed := false + SetDialContext(func(ctx context.Context, network, addr string) (net.Conn, error) { + customDialed = true + c1, c2 := net.Pipe() + c2.Close() + return c1, nil + }) + defer SetDialContext(nil) + + tr := NewProductionTransport(SecureTLSConfig(true)) + if tr == nil { + t.Fatal("expected non-nil transport") + } + conn, err := tr.DialContext(context.Background(), "tcp", "127.0.0.1:80") + if err != nil { + t.Fatalf("unexpected dial error: %v", err) + } + conn.Close() + if !customDialed { + t.Errorf("expected custom dialer to be invoked from transport") + } +} + func TestSecureRedirectPolicy(t *testing.T) { origReq, err := http.NewRequest(http.MethodGet, "https://api.example.com/cases", nil) if err != nil { diff --git a/pkg/downloads/client_test.go b/pkg/downloads/client_test.go index 64519eb..0b837cb 100644 --- a/pkg/downloads/client_test.go +++ b/pkg/downloads/client_test.go @@ -3,14 +3,38 @@ package downloads import ( "context" "encoding/json" + "io" "net/http" "net/http/httptest" "strings" "testing" ) +type mockServer struct { + URL string + client *http.Client +} + +func (m *mockServer) Close() {} +func (m *mockServer) Client() *http.Client { return m.client } + +func newMockServer(handler http.Handler) *mockServer { + return &mockServer{ + URL: "http://mock.downloads.f5.invalid", + client: &http.Client{ + Transport: &mockRoundTripper{ + fn: func(req *http.Request) (*http.Response, error) { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + return rec.Result(), nil + }, + }, + }, + } +} + func TestGetMetadata(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // The leading /v1 is required by the gateway. Serving the path without // it returns 404 live, so this assertion pins the doubled-v1 shape // deliberately; see DownloadsPrefix. @@ -48,7 +72,7 @@ func TestGetMetadata(t *testing.T) { } func TestGetProductVersions(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !strings.Contains(r.URL.Path, "/BIG-IP/big-ip_v17.x") { t.Errorf("unexpected path: %s", r.URL.Path) } @@ -132,3 +156,209 @@ func TestContainerCategories(t *testing.T) { } } } + +type mockRoundTripper struct { + fn func(req *http.Request) (*http.Response, error) +} + +func (m *mockRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + return m.fn(req) +} + +func TestDownloadsClientMethods(t *testing.T) { + var nilClient *Client + if nilClient.String() != "" { + t.Errorf("nil Client.String() = %q, want ", nilClient.String()) + } + nilClient.Zero() + + c := NewClientWithKey("tok123", "downloads.example.com", "key123") + if !strings.Contains(c.String(), "downloads.example.com") { + t.Errorf("String() missing BaseFQDN: %s", c.String()) + } + if strings.Contains(c.String(), "tok123") { + t.Errorf("String() leaked token: %s", c.String()) + } + if c.GoString() != c.String() { + t.Errorf("GoString() != String()") + } + + cEmpty := NewClient("", "") + if !strings.Contains(cEmpty.String(), "[EMPTY]") { + t.Errorf("String() should show [EMPTY] for empty token") + } + if cEmpty.BaseFQDN != DefaultDownloadsFQDN { + t.Errorf("BaseFQDN = %s, want %s", cEmpty.BaseFQDN, DefaultDownloadsFQDN) + } + + c.Zero() + if c.Token != "" || c.APIKey != "" { + t.Errorf("Zero() did not clear tokens") + } +} + +func TestGetFileLinks(t *testing.T) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.Contains(r.URL.Path, "BIG-IP") { + t.Errorf("unexpected path: %s", r.URL.Path) + } + resp := FileLinksResponse{ + Filename: "BIGIP.iso", + DownloadLinks: []DownloadLink{ + {Href: "https://cdn.example.com/BIGIP.iso", Region: "us-east"}, + }, + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(resp) + })) + defer server.Close() + + c := NewClient("tok", server.URL) + c.HTTPClient = server.Client() + + resp, err := c.GetFileLinks(context.Background(), "BIG-IP", "v17", "17.1.0", "Release", "BIGIP.iso", "") + if err != nil { + t.Fatalf("GetFileLinks failed: %v", err) + } + if len(resp.DownloadLinks) != 1 || resp.DownloadLinks[0].Region != "us-east" { + t.Errorf("unexpected response: %+v", resp) + } +} + +func TestDoLegacyFallback(t *testing.T) { + c := NewClientWithKey("tok", "http://primary.invalid", "my-k-param") + c.HTTPClient = &http.Client{ + Transport: &mockRoundTripper{ + fn: func(req *http.Request) (*http.Response, error) { + if !strings.Contains(req.URL.String(), LegacySupportFQDN) { + t.Errorf("expected legacy URL %s, got %s", LegacySupportFQDN, req.URL.String()) + } + if req.URL.Query().Get("k") != "my-k-param" { + t.Errorf("expected k=my-k-param, got %s", req.URL.Query().Get("k")) + } + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"status":"ok"}`)), + Header: make(http.Header), + }, nil + }, + }, + } + + body, err := c.doLegacyFallback(context.Background(), "/test/path") + if err != nil { + t.Fatalf("doLegacyFallback failed: %v", err) + } + if string(body) != `{"status":"ok"}` { + t.Errorf("got %s, want {\"status\":\"ok\"}", string(body)) + } + + c2 := NewClient("tok", "http://primary.invalid") + c2.HTTPClient = &http.Client{ + Transport: &mockRoundTripper{ + fn: func(req *http.Request) (*http.Response, error) { + if req.URL.Query().Get("k") != LegacyKParam { + t.Errorf("expected default LegacyKParam, got %s", req.URL.Query().Get("k")) + } + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"status":"default"}`)), + Header: make(http.Header), + }, nil + }, + }, + } + body2, err := c2.doLegacyFallback(context.Background(), "/test/path") + if err != nil { + t.Fatalf("doLegacyFallback failed: %v", err) + } + if string(body2) != `{"status":"default"}` { + t.Errorf("got %s, want {\"status\":\"default\"}", string(body2)) + } +} + +func TestDownloadsModels(t *testing.T) { + pl := ProductLine{Name: "v17", DisplayName: "Version 17.x"} + if pl.GetTitle() != "Version 17.x" { + t.Errorf("ProductLine.GetTitle() = %s, want Version 17.x", pl.GetTitle()) + } + plEmpty := ProductLine{Name: "v17"} + if plEmpty.GetTitle() != "v17" { + t.Errorf("ProductLine.GetTitle() = %s, want v17", plEmpty.GetTitle()) + } + + pf := ProductFamily{Name: "BIG-IP", DisplayName: "F5 BIG-IP"} + if pf.GetTitle() != "F5 BIG-IP" { + t.Errorf("ProductFamily.GetTitle() = %s, want F5 BIG-IP", pf.GetTitle()) + } + pfEmpty := ProductFamily{Name: "BIG-IP"} + if pfEmpty.GetTitle() != "BIG-IP" { + t.Errorf("ProductFamily.GetTitle() = %s, want BIG-IP", pfEmpty.GetTitle()) + } + + pvr1 := ProductVersionsResponse{Versions: []ProductVersion{{Name: "17.1.0"}}} + if len(pvr1.GetVersions()) != 1 { + t.Errorf("GetVersions() len = %d, want 1", len(pvr1.GetVersions())) + } + pvr2 := ProductVersionsResponse{} + pvr2.Data.ProductVersions = []ProductVersion{{Name: "16.1.0"}} + if len(pvr2.GetVersions()) != 1 || pvr2.GetVersions()[0].Name != "16.1.0" { + t.Errorf("GetVersions() from Data failed") + } + + dl1 := DownloadLink{Region: "us-west", Location: "Oregon"} + if dl1.GetRegion() != "us-west" { + t.Errorf("GetRegion() = %s, want us-west", dl1.GetRegion()) + } + dl2 := DownloadLink{Location: "Frankfurt"} + if dl2.GetRegion() != "Frankfurt" { + t.Errorf("GetRegion() = %s, want Frankfurt", dl2.GetRegion()) + } + + var nilDl *DownloadLink + if _, ok := nilDl.ExpirationTime(); ok { + t.Errorf("nilDl.ExpirationTime() ok = true, want false") + } + dlRFC := DownloadLink{ExpiresAt: "2030-01-01T00:00:00Z"} + if _, ok := dlRFC.ExpirationTime(); !ok { + t.Errorf("RFC3339 ExpirationTime failed") + } + dlNoTZ := DownloadLink{ExpiresAt: "2030-01-01T00:00:00"} + if _, ok := dlNoTZ.ExpirationTime(); !ok { + t.Errorf("NoTZ ExpirationTime failed") + } + dlUnix := DownloadLink{ExpiresAt: "1893456000"} + if _, ok := dlUnix.ExpirationTime(); !ok { + t.Errorf("Unix ExpirationTime failed") + } + dlAWS := DownloadLink{Href: "https://cdn.example.com/file.iso?Expires=1893456000"} + if _, ok := dlAWS.ExpirationTime(); !ok { + t.Errorf("AWS Query ExpirationTime failed") + } + dlAmz := DownloadLink{Href: "https://cdn.example.com/file.iso?X-Amz-Date=20300101T000000Z&X-Amz-Expires=3600"} + if _, ok := dlAmz.ExpirationTime(); !ok { + t.Errorf("AWS X-Amz ExpirationTime failed") + } + + flr1 := FileLinksResponse{DownloadLinks: []DownloadLink{{Region: "eu-central"}}} + if len(flr1.GetLinks()) != 1 { + t.Errorf("GetLinks() from root failed") + } + flr2 := FileLinksResponse{} + flr2.Data.DownloadLinks = []DownloadLink{{Region: "ap-southeast"}} + if len(flr2.GetLinks()) != 1 { + t.Errorf("GetLinks() from Data failed") + } + + flrHashes := FileLinksResponse{ + MD5: "d41d8cd98f00b204e9800998ecf8427e", + Meta: map[string]any{ + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + }, + } + flrHashes.Data.Hashes = []HashItem{{Algorithm: "sha512", Value: "cf83e135"}} + hashes := flrHashes.GetAllHashes() + if len(hashes) != 3 { + t.Errorf("GetAllHashes() count = %d, want 3", len(hashes)) + } +} diff --git a/pkg/downloads/downloader.go b/pkg/downloads/downloader.go index 10b400b..26a96f6 100644 --- a/pkg/downloads/downloader.go +++ b/pkg/downloads/downloader.go @@ -25,6 +25,8 @@ import ( // ProgressCallback is called periodically during download with bytes transferred and total size. type ProgressCallback func(transferred, total int64, speedBytesPerSec float64) +var downloadHTTPClient *http.Client + // DownloadFile streams a file from downloadURL directly to outputPath, calculating // checksums in real-time and updating progress. func DownloadFile( @@ -42,7 +44,10 @@ func DownloadFile( req.Header.Set("User-Agent", "myf5-cli-go-downloader/1.0.0") // Long timeout for large image downloads (e.g. 10 GB ISOs) - httpClient := client.NewSecureHTTPClient(6 * time.Hour) + httpClient := downloadHTTPClient + if httpClient == nil { + httpClient = client.NewSecureHTTPClient(6 * time.Hour) + } resp, err := httpClient.Do(req) if err != nil { return fmt.Errorf("download connection failed: %w", err) diff --git a/pkg/downloads/downloader_test.go b/pkg/downloads/downloader_test.go index 38b6843..8369b22 100644 --- a/pkg/downloads/downloader_test.go +++ b/pkg/downloads/downloader_test.go @@ -6,7 +6,6 @@ import ( "encoding/hex" "fmt" "net/http" - "net/http/httptest" "os" "path/filepath" "strconv" @@ -21,11 +20,13 @@ func TestDownloadFileWithChecksum(t *testing.T) { hasher.Write(testData) expectedSHA256 := hex.EncodeToString(hasher.Sum(nil)) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Length", strconv.Itoa(len(testData))) w.Write(testData) })) defer server.Close() + downloadHTTPClient = server.Client() + defer func() { downloadHTTPClient = nil }() tempDir := t.TempDir() outFile := filepath.Join(tempDir, "test_image.iso") @@ -70,11 +71,13 @@ func TestDownloadFileWithChecksum(t *testing.T) { func TestDownloadFile_DirectoryTarget(t *testing.T) { testData := []byte("directory-target-data") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Length", strconv.Itoa(len(testData))) w.Write(testData) })) defer server.Close() + downloadHTTPClient = server.Client() + defer func() { downloadHTTPClient = nil }() tempDir := t.TempDir() // Download into directory with trailing slash @@ -165,11 +168,13 @@ func TestDownloadLink_Expiration(t *testing.T) { } func TestDownloadFile_ExpiredLink(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusForbidden) w.Write([]byte("AccessDeniedRequest has expired")) })) defer server.Close() + downloadHTTPClient = server.Client() + defer func() { downloadHTTPClient = nil }() tempDir := t.TempDir() outFile := filepath.Join(tempDir, "expired.iso") diff --git a/pkg/downloads/folder_test.go b/pkg/downloads/folder_test.go index f125299..b62c429 100644 --- a/pkg/downloads/folder_test.go +++ b/pkg/downloads/folder_test.go @@ -124,3 +124,23 @@ func TestResolveOSDownloadsDir(t *testing.T) { }) } } + +func TestDefaultDownloadsDir(t *testing.T) { + dir := DefaultDownloadsDir() + if dir == "" { + t.Errorf("DefaultDownloadsDir() returned empty string") + } +} + +func TestExpandHome(t *testing.T) { + home := "/Users/test" + if got := expandHome("$HOME/Downloads", home); got != "/Users/test/Downloads" { + t.Errorf("got %s, want /Users/test/Downloads", got) + } + if got := expandHome("${HOME}/Downloads", home); got != "/Users/test/Downloads" { + t.Errorf("got %s, want /Users/test/Downloads", got) + } + if got := expandHome("/var/tmp", home); got != "/var/tmp" { + t.Errorf("got %s, want /var/tmp", got) + } +} diff --git a/pkg/ihealth/client.go b/pkg/ihealth/client.go index 72380d4..66a1fe3 100644 --- a/pkg/ihealth/client.go +++ b/pkg/ihealth/client.go @@ -75,7 +75,11 @@ func (c *Client) Zero() { // NewClient initializes a new iHealth API client. func NewClient(token string, baseFQDN string) *Client { if baseFQDN == "" { - baseFQDN = DefaultIHealthFQDN + if envFQDN := os.Getenv("F5_IHEALTH_FQDN"); envFQDN != "" { + baseFQDN = envFQDN + } else { + baseFQDN = DefaultIHealthFQDN + } } return &Client{ HTTPClient: client.NewSecureHTTPClient(60 * time.Minute), diff --git a/pkg/ihealth/client_test.go b/pkg/ihealth/client_test.go index 9f30b67..904adc9 100644 --- a/pkg/ihealth/client_test.go +++ b/pkg/ihealth/client_test.go @@ -2,6 +2,8 @@ package ihealth import ( "context" + "encoding/json" + "fmt" "io" "log" "net/http" @@ -14,12 +16,46 @@ import ( "time" ) +type roundTripFunc func(req *http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +type mockServer struct { + URL string + client *http.Client + Config *http.Server +} + +func (m *mockServer) Close() {} +func (m *mockServer) Client() *http.Client { return m.client } + +func newMockServer(handler http.Handler) *mockServer { + return &mockServer{ + URL: "http://mock.ihealth.f5.invalid", + Config: &http.Server{}, + client: &http.Client{ + Transport: roundTripFunc(func(req *http.Request) (resp *http.Response, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("connection reset by peer: %v", r) + } + }() + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + return rec.Result(), nil + }), + }, + } +} + // TestListQKViewsFetchesDetailPerID verifies that ListQKViews negotiates JSON // via the +json vendor media type and populates summary metadata by fetching // each QKView detail resource. func TestListQKViewsFetchesDetailPerID(t *testing.T) { var sawAccept string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { sawAccept = r.Header.Get("Accept") // A server that honours the header the way iHealth does: the bare @@ -82,7 +118,7 @@ func TestListQKViewsFetchesDetailPerID(t *testing.T) { } func TestUploadQKView(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { t.Errorf("expected POST, got %s", r.Method) } @@ -159,7 +195,7 @@ func TestUploadQKView(t *testing.T) { // this one counts goroutines after forcing a failure. func TestUploadQKViewReleasesWriterOnRequestFailure(t *testing.T) { // A server that hangs up immediately, so Do() fails mid-request. - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { panic("closing connection to force a client-side failure") })) server.Config.ErrorLog = log.New(io.Discard, "", 0) @@ -258,7 +294,7 @@ func TestParseUploadResponse(t *testing.T) { } func TestGetQKViewHTTP202Accepted(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := newMockServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != QKViewsPath+"/26991271" { t.Errorf("unexpected path: %s", r.URL.Path) } @@ -300,3 +336,75 @@ func TestGetQKViewHTTP202Accepted(t *testing.T) { t.Errorf("GUIURL = %q, want fallback %q", summary.GUIURL, wantGUI) } } + +func TestIHealthClientMethods(t *testing.T) { + var nilClient *Client + if nilClient.String() != "" { + t.Errorf("nil Client.String() = %q, want ", nilClient.String()) + } + nilClient.Zero() + + c := NewClient("tok123", "ihealth.example.com") + if !strings.Contains(c.String(), "ihealth.example.com") { + t.Errorf("String() missing BaseFQDN: %s", c.String()) + } + if strings.Contains(c.String(), "tok123") { + t.Errorf("String() leaked token: %s", c.String()) + } + if c.GoString() != c.String() { + t.Errorf("GoString() != String()") + } + + cEmpty := NewClient("", "") + if !strings.Contains(cEmpty.String(), "[EMPTY]") { + t.Errorf("String() should show [EMPTY] for empty token") + } + if cEmpty.BaseFQDN != DefaultIHealthFQDN { + t.Errorf("BaseFQDN = %s, want %s", cEmpty.BaseFQDN, DefaultIHealthFQDN) + } + + c.Zero() + if c.Token != "" { + t.Errorf("Zero() did not clear token") + } +} + +func TestStringifyUploadID(t *testing.T) { + cases := []struct { + input any + want string + }{ + {nil, ""}, + {" 12345 ", "12345"}, + {float64(12345), "12345"}, + {int64(12345), "12345"}, + {int(12345), "12345"}, + {json.Number("12345"), "12345"}, + {true, "true"}, + } + for _, tc := range cases { + got := stringifyUploadID(tc.input) + if got != tc.want { + t.Errorf("stringifyUploadID(%v) = %q, want %q", tc.input, got, tc.want) + } + } +} + +func TestIDFromURL(t *testing.T) { + cases := []struct { + input string + want string + }{ + {"", ""}, + {"https://ihealth.f5.com/qkview-analyzer/api/qkviews/12345", "12345"}, + {"https://ihealth.f5.com/qkview-analyzer/api/qkviews/12345/", "12345"}, + {"https://ihealth.f5.com/", ""}, + {"://invalid-url/path/foo", "foo"}, + } + for _, tc := range cases { + got := idFromURL(tc.input) + if got != tc.want { + t.Errorf("idFromURL(%q) = %q, want %q", tc.input, got, tc.want) + } + } +} diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go index f34dfc5..e392f94 100644 --- a/pkg/logger/logger_test.go +++ b/pkg/logger/logger_test.go @@ -95,3 +95,28 @@ func TestGetDefaultLogger(t *testing.T) { l.Warn("myf5 test warning message") l.Error("myf5 test error message") } + +func TestLoggerClose(t *testing.T) { + var buf bytes.Buffer + fl := NewFallbackLogger(&buf) + if err := fl.Close(); err != nil { + t.Errorf("FallbackLogger.Close() error: %v", err) + } + + slNil := &SyslogLogger{writer: nil} + if err := slNil.Close(); err != nil { + t.Errorf("SyslogLogger.Close() with nil writer error: %v", err) + } + + l := Get() + if err := l.Close(); err != nil { + t.Errorf("Get().Close() error: %v", err) + } +} + +func TestSyslogLoggerMethods(t *testing.T) { + sl := &SyslogLogger{} + sl.Info("test info with token %s", "Bearer token123") + sl.Warn("test warn with password %s", "secretpass") + sl.Error("test error with url %s", "https://admin:pass@host") +} diff --git a/pkg/logger/logger_unix.go b/pkg/logger/logger_unix.go index 254bf72..80242ea 100644 --- a/pkg/logger/logger_unix.go +++ b/pkg/logger/logger_unix.go @@ -23,16 +23,25 @@ func newOSLogger() Logger { } func (l *SyslogLogger) Info(format string, args ...any) { + if l.writer == nil { + return + } msg := ScrubSecrets(fmt.Sprintf(format, args...)) _ = l.writer.Info(msg) } func (l *SyslogLogger) Warn(format string, args ...any) { + if l.writer == nil { + return + } msg := ScrubSecrets(fmt.Sprintf(format, args...)) _ = l.writer.Warning(msg) } func (l *SyslogLogger) Error(format string, args ...any) { + if l.writer == nil { + return + } msg := ScrubSecrets(fmt.Sprintf(format, args...)) _ = l.writer.Err(msg) } diff --git a/pkg/progress/progress_test.go b/pkg/progress/progress_test.go index de3977a..702635f 100644 --- a/pkg/progress/progress_test.go +++ b/pkg/progress/progress_test.go @@ -2,6 +2,7 @@ package progress import ( "bytes" + "os" "strings" "testing" "time" @@ -115,3 +116,87 @@ func TestSpinnerAbort(t *testing.T) { t.Errorf("expected abort message, got: %s", out) } } + +func TestGetTerminalWidth(t *testing.T) { + var buf bytes.Buffer + w := getTerminalWidth(&buf) + if w != 80 { + t.Errorf("expected default 80, got %d", w) + } + + wOut := getTerminalWidth(os.Stdout) + if wOut <= 0 { + t.Errorf("expected > 0 for stdout, got %d", wOut) + } +} + +func TestProgressBarTTY(t *testing.T) { + var buf bytes.Buffer + bar := NewBar(1000, "Downloading") + bar.Writer = &buf + bar.isTTY = true + + bar.Update(0) + bar.LastUpdate = time.Now().Add(-time.Second) + bar.Update(500) + bar.LastUpdate = time.Now().Add(-time.Second) + bar.Update(1000) + bar.Finish("Done") + + // Update after finish should be no-op + bar.Update(1200) + + out := buf.String() + if !strings.Contains(out, "Downloading") { + t.Errorf("expected Downloading label in TTY output, got %s", out) + } + if !strings.Contains(out, "[✔] Done") { + t.Errorf("expected [✔] Done in TTY output, got %s", out) + } + + var buf2 bytes.Buffer + bar2 := NewBar(1000, "Downloading") + bar2.Writer = &buf2 + bar2.isTTY = true + bar2.Abort("Failed") + if !strings.Contains(buf2.String(), "[✖] Failed") { + t.Errorf("expected [✖] Failed, got %s", buf2.String()) + } +} + +func TestSpinnerTTY(t *testing.T) { + var buf bytes.Buffer + spin := NewSpinner("Working") + spin.Writer = &buf + spin.isTTY = true + + spin.Start() + spin.Start() // no-op + + spin.SetMessage("step 1") + time.Sleep(120 * time.Millisecond) // Let ticker fire + + spin.Fail("failed step") + + out := buf.String() + if !strings.Contains(out, "[✖] failed step") { + t.Errorf("expected [✖] failed step, got %s", out) + } + + spin.stop() // no-op +} + +func TestSpinnerFailNonTTY(t *testing.T) { + var buf bytes.Buffer + spin := NewSpinner("Working") + spin.Writer = &buf + spin.isTTY = false + + spin.Start() + spin.Fail("failed operation") + + out := buf.String() + if !strings.Contains(out, "[✖] failed operation") { + t.Errorf("expected [✖] failed operation, got %s", out) + } +} From 15c215129a85f600531b3f0c11aff7c0097d0d98 Mon Sep 17 00:00:00 2001 From: Greg Robinson Date: Mon, 16 Nov 2026 16:00:51 -0500 Subject: [PATCH 8/9] fix(bigip,test): resolve SSH stdout/stderr data race and Windows test portability --- cmd/myf5/coverage_test.go | 19 ++++++++++++------- pkg/bigip/geoip.go | 21 ++++++++++++--------- pkg/client/proxy_test.go | 3 +++ pkg/client/tls_test.go | 2 +- pkg/downloads/folder_test.go | 9 +++++---- pkg/logger/logger_test.go | 12 ------------ pkg/logger/logger_unix_test.go | 19 +++++++++++++++++++ 7 files changed, 52 insertions(+), 33 deletions(-) create mode 100644 pkg/logger/logger_unix_test.go diff --git a/cmd/myf5/coverage_test.go b/cmd/myf5/coverage_test.go index 41270bd..b7bd47f 100644 --- a/cmd/myf5/coverage_test.go +++ b/cmd/myf5/coverage_test.go @@ -334,17 +334,18 @@ func TestResolveApplianceCreds_Validations(t *testing.T) { func TestHasDefaultSSHAuth(t *testing.T) { // 1. With SSH_AUTH_SOCK set - os.Setenv("SSH_AUTH_SOCK", "/tmp/fake-ssh-agent.sock") + t.Setenv("SSH_AUTH_SOCK", "/tmp/fake-ssh-agent.sock") if !hasDefaultSSHAuth() { t.Errorf("expected hasDefaultSSHAuth to be true with SSH_AUTH_SOCK") } - os.Unsetenv("SSH_AUTH_SOCK") + t.Setenv("SSH_AUTH_SOCK", "") // 2. With clean temp home directory without keys fakeHome := t.TempDir() - origHome := os.Getenv("HOME") - os.Setenv("HOME", fakeHome) - defer os.Setenv("HOME", origHome) + t.Setenv("HOME", fakeHome) + t.Setenv("USERPROFILE", fakeHome) + t.Setenv("HOMEDRIVE", "") + t.Setenv("HOMEPATH", "") if hasDefaultSSHAuth() { t.Errorf("expected hasDefaultSSHAuth to be false in empty home") @@ -352,8 +353,12 @@ func TestHasDefaultSSHAuth(t *testing.T) { // 3. With id_rsa created sshDir := filepath.Join(fakeHome, ".ssh") - os.MkdirAll(sshDir, 0700) - os.WriteFile(filepath.Join(sshDir, "id_rsa"), []byte("dummy-key"), 0600) + if err := os.MkdirAll(sshDir, 0700); err != nil { + t.Fatalf("failed to create sshDir: %v", err) + } + if err := os.WriteFile(filepath.Join(sshDir, "id_rsa"), []byte("dummy-key"), 0600); err != nil { + t.Fatalf("failed to write id_rsa: %v", err) + } if !hasDefaultSSHAuth() { t.Errorf("expected hasDefaultSSHAuth to be true with id_rsa present") diff --git a/pkg/bigip/geoip.go b/pkg/bigip/geoip.go index 5883782..1d0eca5 100644 --- a/pkg/bigip/geoip.go +++ b/pkg/bigip/geoip.go @@ -403,25 +403,28 @@ func applyGeoIPSSH(ctx context.Context, host, scriptB64 string, opts GeoIPOption } defer session.Close() - var outBuf bytes.Buffer - session.Stdout = &outBuf - session.Stderr = &outBuf - cmd := fmt.Sprintf("echo '%s' | base64 -d | bash", scriptB64) - runDone := make(chan error, 1) + type runResult struct { + output []byte + err error + } + runDone := make(chan runResult, 1) go func() { - runDone <- session.Run(cmd) + out, rErr := session.CombinedOutput(cmd) + runDone <- runResult{output: out, err: rErr} }() var runErr error + var rawOutput string select { case <-ctx.Done(): _ = session.Signal(ssh.SIGINT) _ = session.Close() - return outBuf.String(), ctx.Err() - case runErr = <-runDone: + return "", ctx.Err() + case res := <-runDone: + rawOutput = string(res.output) + runErr = res.err } - rawOutput := outBuf.String() if runErr != nil && !strings.Contains(rawOutput, "--- SCRIPT_EXIT_CODE:") { return rawOutput, fmt.Errorf("SSH execution error: %w (output: %s)", runErr, strings.TrimSpace(rawOutput)) diff --git a/pkg/client/proxy_test.go b/pkg/client/proxy_test.go index c06847c..47806d1 100644 --- a/pkg/client/proxy_test.go +++ b/pkg/client/proxy_test.go @@ -837,6 +837,9 @@ func TestSOCKS5ErrorsAndAuth(t *testing.T) { } func TestSetDialContext(t *testing.T) { + t.Cleanup(func() { + SetDialContext(memDial) + }) customDialed := false customFn := func(ctx context.Context, network, addr string) (net.Conn, error) { customDialed = true diff --git a/pkg/client/tls_test.go b/pkg/client/tls_test.go index 36d31e2..7ee3130 100644 --- a/pkg/client/tls_test.go +++ b/pkg/client/tls_test.go @@ -71,7 +71,7 @@ func TestNewProductionTransportWithProxy(t *testing.T) { c2.Close() return c1, nil }) - defer SetDialContext(nil) + defer SetDialContext(memDial) tr := NewProductionTransport(SecureTLSConfig(true)) if tr == nil { diff --git a/pkg/downloads/folder_test.go b/pkg/downloads/folder_test.go index b62c429..1b9f341 100644 --- a/pkg/downloads/folder_test.go +++ b/pkg/downloads/folder_test.go @@ -134,11 +134,12 @@ func TestDefaultDownloadsDir(t *testing.T) { func TestExpandHome(t *testing.T) { home := "/Users/test" - if got := expandHome("$HOME/Downloads", home); got != "/Users/test/Downloads" { - t.Errorf("got %s, want /Users/test/Downloads", got) + expected := filepath.Join(home, "Downloads") + if got := expandHome("$HOME/Downloads", home); got != expected { + t.Errorf("got %s, want %s", got, expected) } - if got := expandHome("${HOME}/Downloads", home); got != "/Users/test/Downloads" { - t.Errorf("got %s, want /Users/test/Downloads", got) + if got := expandHome("${HOME}/Downloads", home); got != expected { + t.Errorf("got %s, want %s", got, expected) } if got := expandHome("/var/tmp", home); got != "/var/tmp" { t.Errorf("got %s, want /var/tmp", got) diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go index e392f94..9f92dcd 100644 --- a/pkg/logger/logger_test.go +++ b/pkg/logger/logger_test.go @@ -103,20 +103,8 @@ func TestLoggerClose(t *testing.T) { t.Errorf("FallbackLogger.Close() error: %v", err) } - slNil := &SyslogLogger{writer: nil} - if err := slNil.Close(); err != nil { - t.Errorf("SyslogLogger.Close() with nil writer error: %v", err) - } - l := Get() if err := l.Close(); err != nil { t.Errorf("Get().Close() error: %v", err) } } - -func TestSyslogLoggerMethods(t *testing.T) { - sl := &SyslogLogger{} - sl.Info("test info with token %s", "Bearer token123") - sl.Warn("test warn with password %s", "secretpass") - sl.Error("test error with url %s", "https://admin:pass@host") -} diff --git a/pkg/logger/logger_unix_test.go b/pkg/logger/logger_unix_test.go new file mode 100644 index 0000000..bf89717 --- /dev/null +++ b/pkg/logger/logger_unix_test.go @@ -0,0 +1,19 @@ +//go:build !windows + +package logger + +import "testing" + +func TestSyslogLoggerClose(t *testing.T) { + slNil := &SyslogLogger{writer: nil} + if err := slNil.Close(); err != nil { + t.Errorf("SyslogLogger.Close() with nil writer error: %v", err) + } +} + +func TestSyslogLoggerMethods(t *testing.T) { + sl := &SyslogLogger{} + sl.Info("test info with token %s", "Bearer token123") + sl.Warn("test warn with password %s", "secretpass") + sl.Error("test error with url %s", "https://admin:pass@host") +} From 727abf32f186b6abc61061eae7c80aa9b6293388 Mon Sep 17 00:00:00 2001 From: Greg Robinson Date: Mon, 16 Nov 2026 20:44:52 -0500 Subject: [PATCH 9/9] fix(test): drain mock HTTP request body in coverage tests to prevent pipe closure --- cmd/myf5/coverage_test.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/cmd/myf5/coverage_test.go b/cmd/myf5/coverage_test.go index b7bd47f..0d3faf7 100644 --- a/cmd/myf5/coverage_test.go +++ b/cmd/myf5/coverage_test.go @@ -2001,16 +2001,17 @@ func TestExecutePushToApplianceSuccess(t *testing.T) { dialer := func(ctx context.Context, network, addr string) (net.Conn, error) { c1, c2 := net.Pipe() go func() { + defer c2.Close() req, err := http.ReadRequest(bufio.NewReader(c2)) if err != nil { - c2.Close() return } rec := httptest.NewRecorder() mockMux.ServeHTTP(rec, req) + _, _ = io.Copy(io.Discard, req.Body) + _ = req.Body.Close() resp := rec.Result() _ = resp.Write(c2) - c2.Close() }() return c1, nil } @@ -2132,16 +2133,17 @@ func TestHandleCasesWithMockServer(t *testing.T) { dialer := func(ctx context.Context, network, addr string) (net.Conn, error) { c1, c2 := net.Pipe() go func() { + defer c2.Close() req, err := http.ReadRequest(bufio.NewReader(c2)) if err != nil { - c2.Close() return } rec := httptest.NewRecorder() mockMux.ServeHTTP(rec, req) + _, _ = io.Copy(io.Discard, req.Body) + _ = req.Body.Close() resp := rec.Result() _ = resp.Write(c2) - c2.Close() }() return c1, nil } @@ -2198,16 +2200,17 @@ func TestHandleIHealthWithMockServer(t *testing.T) { dialer := func(ctx context.Context, network, addr string) (net.Conn, error) { c1, c2 := net.Pipe() go func() { + defer c2.Close() req, err := http.ReadRequest(bufio.NewReader(c2)) if err != nil { - c2.Close() return } rec := httptest.NewRecorder() mockMux.ServeHTTP(rec, req) + _, _ = io.Copy(io.Discard, req.Body) + _ = req.Body.Close() resp := rec.Result() _ = resp.Write(c2) - c2.Close() }() return c1, nil }