diff --git a/cmd/browsers.go b/cmd/browsers.go index 079f94e0..4add9d4a 100644 --- a/cmd/browsers.go +++ b/cmd/browsers.go @@ -247,6 +247,21 @@ func parseFingerprintOS(os string) (kernel.BrowserFingerprintOs, error) { } } +// parseBrowserPlatformOS validates the operating system of the browser host. +// This is distinct from --fingerprint-os, which only changes what a Linux +// browser reports to websites. +func parseBrowserPlatformOS(os string) (kernel.BrowserOs, error) { + if os == "" { + return "", nil + } + switch kernel.BrowserOs(os) { + case kernel.BrowserOsLinux, kernel.BrowserOsMacos: + return kernel.BrowserOs(os), nil + default: + return "", fmt.Errorf("invalid --platform-os value: %s (must be linux or macos)", os) + } +} + // maxPrivateHosts mirrors the API's cap on network.private_hosts entries. const maxPrivateHosts = 32 @@ -404,6 +419,13 @@ func formatBrowserLocationField(value string, source kernel.BrowserLocationSourc return fmt.Sprintf("%s (%s)", value, source) } +func formatBrowserPlatform(platform kernel.BrowserPlatform) string { + if platform.Os == "" { + return string(kernel.BrowserOsLinux) + } + return string(platform.Os) +} + // formatVaultReferences renders the vaults linked to a session for table output, // preferring each vault's name and falling back to its ID. It returns an empty // string when no vaults are linked, so the row can be omitted entirely. @@ -544,6 +566,7 @@ type BrowsersCreateInput struct { Memory string VideoMemory string FingerprintOS string + PlatformOS string InvocationID string Kiosk BoolFlag ProfileID string @@ -594,6 +617,7 @@ type BrowsersLiveViewCreateInput struct { type BrowsersGetInput struct { Identifier string + IncludeCost bool IncludeDeleted bool Output string } @@ -743,7 +767,7 @@ func (b BrowsersCmd) List(ctx context.Context, in BrowsersListInput) error { if showLeasedAt { headers = append(headers, "Leased At") } - headers = append(headers, "Region", "Profile", "Pool") + headers = append(headers, "Region", "Host OS", "Profile", "Pool") if showReplay { headers = append(headers, "Replay ID") } @@ -783,6 +807,7 @@ func (b BrowsersCmd) List(ctx context.Context, in BrowsersListInput) error { } row = append(row, util.OrDash(string(browser.Region)), + formatBrowserPlatform(browser.Platform), profile, pool, ) @@ -860,6 +885,13 @@ func (b BrowsersCmd) Create(ctx context.Context, in BrowsersCreateInput) error { if fingerprintOS != "" { params.Fingerprint = kernel.BrowserFingerprintParam{Os: fingerprintOS} } + platformOS, err := parseBrowserPlatformOS(in.PlatformOS) + if err != nil { + return err + } + if platformOS != "" { + params.Platform = kernel.BrowserPlatformParam{Os: platformOS} + } if in.InvocationID != "" { params.InvocationID = kernel.Opt(in.InvocationID) } @@ -1013,6 +1045,7 @@ func (b BrowsersCmd) Create(ctx context.Context, in BrowsersCreateInput) error { tableData := buildBrowserTableData(browser.SessionID, browser.CdpWsURL, browser.BrowserLiveViewURL, browser.Profile, browser.ProfileSaveChanges, browser.StartURL, browser.Name, browser.Tags) tableData = appendBrowserLeasedAtRow(tableData, browser.LeasedAt) tableData = appendReplayRows(tableData, browser.Replay.ReplayID, browser.Replay.ReplayViewURL, browser.Replay.StartedAt, browser.Replay.FinishedAt) + tableData = append(tableData, []string{"Host OS", formatBrowserPlatform(browser.Platform)}) tableData = append(tableData, []string{"CAPTCHA Solver", fmt.Sprintf("%t", browser.CaptchaSolver.Enabled)}) if browser.Fingerprint.Os != "" { tableData = append(tableData, []string{"Fingerprint OS", string(browser.Fingerprint.Os)}) @@ -1040,6 +1073,7 @@ func printBrowserPoolAcquireResult(resp *kernel.BrowserPoolAcquireResponse) { tableData := buildBrowserTableData(resp.SessionID, resp.CdpWsURL, resp.BrowserLiveViewURL, resp.Profile, resp.ProfileSaveChanges, resp.StartURL, resp.Name, resp.Tags) tableData = appendBrowserLeasedAtRow(tableData, resp.LeasedAt) tableData = appendReplayRows(tableData, resp.Replay.ReplayID, resp.Replay.ReplayViewURL, resp.Replay.StartedAt, resp.Replay.FinishedAt) + tableData = append(tableData, []string{"Host OS", formatBrowserPlatform(resp.Platform)}) tableData = append(tableData, []string{"CAPTCHA Solver", fmt.Sprintf("%t", resp.CaptchaSolver.Enabled)}) if resp.Fingerprint.Os != "" { tableData = append(tableData, []string{"Fingerprint OS", string(resp.Fingerprint.Os)}) @@ -1197,6 +1231,9 @@ func (b BrowsersCmd) Get(ctx context.Context, in BrowsersGetInput) error { } query := kernel.BrowserGetParams{} + if in.IncludeCost { + query.IncludeCost = kernel.Opt(true) + } if in.IncludeDeleted { query.IncludeDeleted = kernel.Opt(true) } @@ -1226,6 +1263,7 @@ func (b BrowsersCmd) Get(ctx context.Context, in BrowsersGetInput) error { tableData = appendBrowserLeasedAtRow(tableData, browser.LeasedAt) tableData = appendReplayRows(tableData, browser.Replay.ReplayID, browser.Replay.ReplayViewURL, browser.Replay.StartedAt, browser.Replay.FinishedAt) tableData = append(tableData, []string{"Region", util.OrDash(string(browser.Region))}) + tableData = append(tableData, []string{"Host OS", formatBrowserPlatform(browser.Platform)}) tableData = append(tableData, browserLocationRows(browser.Location)...) tableData = append(tableData, []string{"Timeout (seconds)", fmt.Sprintf("%d", browser.TimeoutSeconds)}) tableData = append(tableData, []string{"Headless", fmt.Sprintf("%t", browser.Headless)}) @@ -1270,6 +1308,15 @@ func (b BrowsersCmd) Get(ctx context.Context, in BrowsersGetInput) error { if browser.UsageStatus != "" { tableData = append(tableData, []string{"Usage Status", string(browser.UsageStatus)}) } + if browser.Cost.JSON.Status.Valid() { + tableData = append(tableData, []string{"Cost Status", string(browser.Cost.Status)}) + if browser.Cost.JSON.EstimatedUsageSpendUsd.Valid() { + tableData = append(tableData, []string{"Estimated Usage Spend (USD)", browser.Cost.EstimatedUsageSpendUsd}) + } + if browser.Cost.JSON.AsOf.Valid() && !browser.Cost.AsOf.IsZero() { + tableData = append(tableData, []string{"Cost As Of", util.FormatLocal(browser.Cost.AsOf)}) + } + } PrintTableNoPad(tableData, true) return nil @@ -1576,6 +1623,7 @@ func (b BrowsersCmd) Update(ctx context.Context, in BrowsersUpdateInput) error { } pterm.Success.Printf("Updated browser %s\n", browser.SessionID) + pterm.Info.Printf("Host OS: %s\n", formatBrowserPlatform(browser.Platform)) if !browser.LeasedAt.IsZero() { pterm.Info.Printf("Leased At: %s\n", util.FormatLocal(browser.LeasedAt)) } @@ -3242,7 +3290,16 @@ var browsersListCmd = &cobra.Command{ var browsersCreateCmd = &cobra.Command{ Use: "create", Short: "Create a new browser session", - RunE: runBrowsersCreate, + Long: `Create a new browser session. + +The host platform defaults to Linux. --platform-os controls the operating system +that runs the browser, while --fingerprint-os only changes what a Linux browser +reports to websites. macOS browsers are not available yet; requests currently +return platform_unavailable. When available, macOS browsers are headful, run only +in us-east, and cannot use memory, GPU, video memory, profiles, location overrides, +or fingerprint overrides. Incompatible requests return unsupported_configuration +and identify the offending fields.`, + RunE: runBrowsersCreate, } var browsersDeleteCmd = &cobra.Command{ @@ -3281,9 +3338,15 @@ URL is not stored and cannot be revoked early, so treat it as a credential.`, var browsersGetCmd = &cobra.Command{ Use: "get ", Short: "Get detailed information about a browser session by ID or name", - Long: "Retrieve and display detailed information about a specific browser session (by ID or name) including configuration, URLs, and status.", - Args: cobra.ExactArgs(1), - RunE: runBrowsersGet, + Long: `Retrieve and display a browser session's configuration, URLs, and status. + +Use --include-cost to request the session's provisional usage cost. Cost is +omitted by default and is not returned by browser list or other browser commands. +A provisional amount is gross browser-meter spend before credits, subscriptions, +tax, and adjustments, not an invoice total. The API may instead report pending or +unavailable, and a running or recently deleted session may accrue after cost.as_of.`, + Args: cobra.ExactArgs(1), + RunE: runBrowsersGet, } var browsersSaveProfileCmd = &cobra.Command{ @@ -3389,6 +3452,7 @@ func init() { // get flags addJSONOutputFlag(browsersGetCmd) + browsersGetCmd.Flags().Bool("include-cost", false, "Include the session's provisional usage cost") browsersGetCmd.Flags().Bool("include-deleted", false, "Include soft-deleted browser sessions in the lookup") // view flags @@ -3719,6 +3783,7 @@ unrestricted code execution inside the browser VM and is not sandboxed.`, browsersCreateCmd.Flags().String("memory", "", "Memory for a non-GPU browser session. Headless: '1GiB' (default), '2GiB' or '4GiB'. Headful: '8GiB' (default) or '16GiB'") browsersCreateCmd.Flags().String("video-memory", "", "Video memory (VRAM) for a GPU browser session (requires --gpu): '3GiB' (default, 4 vCPU/6GiB memory) or '6GiB' (8 vCPU/12GiB memory)") browsersCreateCmd.Flags().String("fingerprint-os", "", "Closed beta browser fingerprint OS override: linux or macos. Contact Kernel to enable; requires --captcha-solver=true, --headless=false, --gpu=false, and default memory") + browsersCreateCmd.Flags().String("platform-os", "", "Browser host operating system: linux (default) or macos; see command help for macOS availability and restrictions") browsersCreateCmd.Flags().String("invocation-id", "", "Associate the browser session with an invocation") browsersCreateCmd.Flags().Bool("kiosk", false, "Launch browser in kiosk mode") browsersCreateCmd.Flags().IntP("timeout", "t", 60, "Timeout in seconds for the browser session") @@ -3866,6 +3931,7 @@ func runBrowsersCreate(cmd *cobra.Command, args []string) error { memory, _ := cmd.Flags().GetString("memory") videoMemory, _ := cmd.Flags().GetString("video-memory") fingerprintOS, _ := cmd.Flags().GetString("fingerprint-os") + platformOS, _ := cmd.Flags().GetString("platform-os") invocationID, _ := cmd.Flags().GetString("invocation-id") kioskVal, _ := cmd.Flags().GetBool("kiosk") timeout, _ := cmd.Flags().GetInt("timeout") @@ -4029,6 +4095,7 @@ func runBrowsersCreate(cmd *cobra.Command, args []string) error { Memory: memory, VideoMemory: videoMemory, FingerprintOS: fingerprintOS, + PlatformOS: platformOS, InvocationID: invocationID, Kiosk: BoolFlag{Set: cmd.Flags().Changed("kiosk"), Value: kioskVal}, ProfileID: profileID, @@ -4111,12 +4178,14 @@ func runBrowsersLiveViewCreate(cmd *cobra.Command, args []string) error { func runBrowsersGet(cmd *cobra.Command, args []string) error { client := getKernelClient(cmd) out, _ := cmd.Flags().GetString("output") + includeCost, _ := cmd.Flags().GetBool("include-cost") includeDeleted, _ := cmd.Flags().GetBool("include-deleted") svc := client.Browsers b := BrowsersCmd{browsers: &svc} return b.Get(cmd.Context(), BrowsersGetInput{ Identifier: args[0], + IncludeCost: includeCost, IncludeDeleted: includeDeleted, Output: out, }) diff --git a/cmd/browsers_test.go b/cmd/browsers_test.go index 15f625e2..3367dcc3 100644 --- a/cmd/browsers_test.go +++ b/cmd/browsers_test.go @@ -1215,6 +1215,52 @@ func TestBrowsersCreate_WithFingerprintOS(t *testing.T) { assert.Equal(t, 2, calls) } +func TestBrowsersCreate_WithPlatformOS(t *testing.T) { + setupStdoutCapture(t) + + var captured kernel.BrowserNewParams + calls := 0 + fake := &FakeBrowsersService{ + NewFunc: func(ctx context.Context, body kernel.BrowserNewParams, opts ...option.RequestOption) (*kernel.BrowserNewResponse, error) { + calls++ + captured = body + return &kernel.BrowserNewResponse{SessionID: "sess-platform", Platform: kernel.BrowserPlatform{Os: body.Platform.Os}}, nil + }, + } + b := BrowsersCmd{browsers: fake} + + err := b.Create(context.Background(), BrowsersCreateInput{PlatformOS: "macos"}) + require.NoError(t, err) + assert.Equal(t, kernel.BrowserOsMacos, captured.Platform.Os) + raw, err := captured.MarshalJSON() + require.NoError(t, err) + assert.Contains(t, string(raw), `"platform":{"os":"macos"}`) + assert.Contains(t, outBuf.String(), "Host OS") + assert.Contains(t, outBuf.String(), "macos") + + err = b.Create(context.Background(), BrowsersCreateInput{PlatformOS: "linux"}) + require.NoError(t, err) + assert.Equal(t, kernel.BrowserOsLinux, captured.Platform.Os) + + err = b.Create(context.Background(), BrowsersCreateInput{PlatformOS: "windows"}) + require.ErrorContains(t, err, "--platform-os") + assert.Equal(t, 2, calls) +} + +func TestBrowsersPlatformAndCostHelp(t *testing.T) { + require.NotNil(t, browsersCreateCmd.Flags().Lookup("platform-os")) + assert.Contains(t, browsersCreateCmd.Long, "--fingerprint-os") + assert.Contains(t, browsersCreateCmd.Long, "not available yet") + assert.Contains(t, browsersCreateCmd.Long, "us-east") + assert.Contains(t, browsersCreateCmd.Long, "unsupported_configuration") + + require.NotNil(t, browsersGetCmd.Flags().Lookup("include-cost")) + assert.Contains(t, browsersGetCmd.Long, "provisional usage cost") + assert.Contains(t, browsersGetCmd.Long, "omitted by default") + assert.Contains(t, browsersGetCmd.Long, "not an invoice total") + assert.Contains(t, browsersGetCmd.Long, "pending or") +} + func TestBrowsersCreate_WithCaptchaSolver(t *testing.T) { setupStdoutCapture(t) @@ -1812,6 +1858,34 @@ func TestBrowsersGet_Error(t *testing.T) { assert.Contains(t, err.Error(), "get failed") } +func TestBrowsersGet_WithIncludeCost(t *testing.T) { + setupStdoutCapture(t) + var captured kernel.BrowserGetParams + fake := &FakeBrowsersService{ + GetFunc: func(ctx context.Context, id string, query kernel.BrowserGetParams, opts ...option.RequestOption) (*kernel.BrowserGetResponse, error) { + captured = query + var response kernel.BrowserGetResponse + require.NoError(t, json.Unmarshal([]byte(`{ + "session_id":"sess-cost", + "platform":{"os":"macos"}, + "cost":{"status":"provisional","estimated_usage_spend_usd":"1.25","as_of":"2026-01-02T03:04:05Z"} + }`), &response)) + return &response, nil + }, + } + + err := (BrowsersCmd{browsers: fake}).Get(context.Background(), BrowsersGetInput{ + Identifier: "sess-cost", + IncludeCost: true, + }) + require.NoError(t, err) + assert.True(t, captured.IncludeCost.Valid()) + assert.True(t, captured.IncludeCost.Value) + for _, want := range []string{"Host OS", "macos", "Cost Status", "provisional", "Estimated Usage Spend (USD)", "1.25", "Cost As Of"} { + assert.Contains(t, outBuf.String(), want) + } +} + func TestBrowsersGet_WithIncludeDeleted(t *testing.T) { setupStdoutCapture(t) var captured kernel.BrowserGetParams @@ -3198,6 +3272,7 @@ func captureUpdateParams(t *testing.T) (*FakeBrowsersService, *kernel.BrowserUpd SessionID: "session123", Name: body.Name.Value, Tags: body.Tags, + Platform: kernel.BrowserPlatform{Os: kernel.BrowserOsMacos}, LeasedAt: time.Date(2033, 6, 7, 8, 9, 10, 0, time.UTC), }, nil }} @@ -3218,6 +3293,8 @@ func TestBrowsersUpdate_WithName_ForwardsParam(t *testing.T) { assert.NoError(t, err) assert.True(t, captured.Name.Valid()) assert.Equal(t, "new-name", captured.Name.Value) + assert.Contains(t, outBuf.String(), "Host OS") + assert.Contains(t, outBuf.String(), "macos") assert.Contains(t, outBuf.String(), "Leased At") assert.Contains(t, outBuf.String(), "2033") } diff --git a/cmd/invoke.go b/cmd/invoke.go index 695f90a0..ecd1c8c8 100644 --- a/cmd/invoke.go +++ b/cmd/invoke.go @@ -600,7 +600,7 @@ func runInvocationBrowsers(cmd *cobra.Command, args []string) error { if showLeasedAt { headers = append(headers, "Leased At") } - headers = append(headers, "Region", "Headless", "Stealth", "Timeout") + headers = append(headers, "Region", "Host OS", "Headless", "Stealth", "Timeout") if showReplay { headers = append(headers, "Replay ID") } @@ -624,6 +624,7 @@ func runInvocationBrowsers(cmd *cobra.Command, args []string) error { } row = append(row, util.OrDash(browser.Region), + formatBrowserPlatform(browser.Platform), fmt.Sprintf("%v", browser.Headless), fmt.Sprintf("%v", browser.Stealth), fmt.Sprintf("%d", browser.TimeoutSeconds), diff --git a/cmd/vaults.go b/cmd/vaults.go index 1978a83c..7673a04d 100644 --- a/cmd/vaults.go +++ b/cmd/vaults.go @@ -324,6 +324,9 @@ func (c VaultsCmd) Invoke(ctx context.Context, vault, key, operation string, par if (operation == "add_payment_method" || operation == "remove_payment_method") && (params == nil || params.PaymentMethod == nil) { return fmt.Errorf("%s requires its documented parameters", operation) } + if operation == "link_balance_setup" && (params == nil || params.LinkBalanceSetup == nil) { + return fmt.Errorf("link_balance_setup parameters were not initialized") + } if operation == "update_access_token" && (params == nil || params.UpdateAccessToken == nil) { return fmt.Errorf("update_access_token requires --spec-file with access_token") } @@ -410,6 +413,9 @@ func (c VaultsCmd) Invoke(ctx context.Context, vault, key, operation string, par } else if params != nil && params.PaymentMethod != nil { request = *params.PaymentMethod request.IDOrName = vault + } else if params != nil && params.LinkBalanceSetup != nil { + request = *params.LinkBalanceSetup + request.IDOrName = vault } else if params != nil && params.UpdateAccessToken != nil { request = *params.UpdateAccessToken request.IDOrName = vault @@ -454,6 +460,16 @@ func (c VaultsCmd) Invoke(ctx context.Context, vault, key, operation string, par if operation == "add_payment_method" || operation == "remove_payment_method" { return printVaultPaymentMethodOperationResult(response, operation, output) } + if operation == "link_balance_setup" { + setupURL, err := printVaultLinkBalanceSetupResult(response, output) + if err != nil || !open { + return err + } + if err := c.openURL(setupURL); err != nil { + return fmt.Errorf("could not open the browser; open the returned Link balance setup URL manually") + } + return nil + } if response == nil || (response.Type != "card" && response.Type != "payment_request" && response.Type != "wallet" && response.Type != "credential" && response.Type != "credential_account") { if item.Spec.Provider == "kernel" { return fmt.Errorf("unexpected vault operation response; %s", kernelVaultRetryGuidance(operation)) diff --git a/cmd/vaults_commands.go b/cmd/vaults_commands.go index 99fa85f0..0f235da3 100644 --- a/cmd/vaults_commands.go +++ b/cmd/vaults_commands.go @@ -195,7 +195,7 @@ each vault has its own key; it is created on first request and may be cached.`, }} addVaultJSONOutputFlag(itemList) itemGet := &cobra.Command{Use: "get ", Short: "get item state, available operations, and requested live data", Args: cobra.ExactArgs(2), PreRunE: vaultPreRun, - Long: "get item state, available operations, provider actions, and returned AgentCard checkout aliases.\n--expand fetches live, non-persisted provider data only when the item advertises that expansion; requesting unavailable data fails rather than returning a partial item. Link user info and shipping addresses can contain personal data. use -o json to preserve null versus omitted fields.\n--wait is a single bounded server-side observation, not a retry or a guarantee of readiness.\nan item still pending after the wait is returned as-is; ready means populated for credentials, not logged in or paid.\nfor credential edits on an already-ready item, compare versions without --wait. explicitly non-sensitive text/email values are returned; sensitive values and totp seeds are omitted.\nrecovery_required stops waiting and means unresolved, not declined or expired.\na 1Password credential_account in revoking cannot be used while KERNEL keeps retrying its revoke in the background.\nfor AgentCard authorization json, amount_authority identifies the approved amount's source; agent and display_only do not prove what the processor charged. amount_verified and charged_* may be absent when there is no observed charge. charged_kind none means the checkout produced a token or payment method for a later merchant charge; inspect item events and the merchant order record.\n" + vaultRecoveryHelp, + Long: "get item state, available operations, provider actions, and returned AgentCard checkout aliases.\n--expand fetches live, non-persisted provider data only when the item advertises that expansion; requesting unavailable data fails rather than returning a partial item. Link user info and shipping addresses can contain personal data. payment_methods may include a stored-value balance whose available amount is read live from the provider and omitted when the provider does not report it. use -o json to preserve null versus omitted fields.\n--wait is a single bounded server-side observation, not a retry or a guarantee of readiness.\nan item still pending after the wait is returned as-is; ready means populated for credentials, not logged in or paid.\nfor credential edits on an already-ready item, compare versions without --wait. explicitly non-sensitive text/email values are returned; sensitive values and totp seeds are omitted.\nrecovery_required stops waiting and means unresolved, not declined or expired.\na 1Password credential_account in revoking cannot be used while KERNEL keeps retrying its revoke in the background.\nfor AgentCard authorization json, amount_authority identifies the approved amount's source; agent and display_only do not prove what the processor charged. amount_verified and charged_* may be absent when there is no observed charge. charged_kind none means the checkout produced a token or payment method for a later merchant charge; inspect item events and the merchant order record.\n" + vaultRecoveryHelp, Example: " kernel vaults items get checkout wallet-1 --expand payment_methods\n kernel vaults items get checkout wallet-1 --expand link_user_info,link_shipping_addresses -o json", RunE: func(cmd *cobra.Command, args []string) error { wait, _ := cmd.Flags().GetInt64("wait") @@ -301,10 +301,25 @@ funded by that method without disconnecting the wallet or changing other methods unresolved purchase can block removal; an uncertain provider outcome leaves removal_pending and must be re-checked before an explicit retry. removal is not proof that a payment did not occur. scoped keys need both vaults:use and vaults:write. +link_balance_setup is valid only when advertised by a connected Link wallet. Kernel first +reads live Link user info and returns 409 unless eligible_for_balance is true, which depends +on both the user and the wallet's Link client. its optional values are suggestions that the +user can change. desired_balance_amount is the target balance in cents; the page asks for the +difference and skips adding money when the current balance covers it. desired_transaction_limit +is the approval threshold in cents; setting it always shows that step, while omitting it skips +the step. pass either value through --params or --spec-file, both for first-time setup, or +neither when no prefill is needed. each value must be a whole-dollar amount of at least 100 +cents, and the transaction limit is at most 50000 cents. Link refuses a page that would ask +the user to add more than $150 at once. the returned URL does not expire and is the same for +setup, adding money, and changing the threshold. only the Link user can complete it; use +--open only on that user's machine, otherwise share it privately. do not assume completion: +inspect wallets payment-methods for a balance method and its live available amount. Kernel +cards do not yet use Link's approval policy, so they still require user approval even when +funded from the balance. restart_verification takes no parameters. in recovery_required, ` + vaultRecoveryHelp + ` it rotates the approval link without a provider call, only after a classified initial attestation failure with proof no intent was dispatched. other recovery states must not be retried. -collect/authorize/prepare_checkout/1pw_recover/restart_verification may use --open. +collect/authorize/prepare_checkout/link_balance_setup/1pw_recover/restart_verification may use --open. --open on card_enrollment or spend_approval is for a human cardholder on their own machine. agents must omit --open and share capability links privately, never open them for cardholders. fill returns value-free per-field outcomes; @@ -388,6 +403,7 @@ JSON kernel vaults items invoke checkout cardholder add_payment_method kernel vaults items invoke checkout cardholder add_payment_method --enrollment server kernel vaults items invoke checkout cardholder remove_payment_method --params '{"payment_method_id":""}' + kernel vaults items invoke checkout link-wallet link_balance_setup --params '{"desired_balance_amount":10000,"desired_transaction_limit":5000}' --open kernel vaults items invoke checkout wallet-1 update_access_token --spec-file ./link-access-token.json kernel vaults items invoke user-vault login register_passkey --browser-id --field passkey kernel vaults items invoke user-vault login arm_passkey --browser-id --field passkey @@ -404,7 +420,7 @@ JSON } if cmd.Flags().Changed("spec-file") { if !vaultOperationTakesParams(args[2]) { - return fmt.Errorf("--spec-file is only supported for fill, webmcp_invoke, prepare_checkout, confirm_transaction, remove_payment_method, update_access_token, and 1Password operations with parameters; passkey operations use --browser-id and optional --field") + return fmt.Errorf("--spec-file is only supported for fill, webmcp_invoke, prepare_checkout, confirm_transaction, remove_payment_method, link_balance_setup, update_access_token, and 1Password operations with parameters; passkey operations use --browser-id and optional --field") } data, err := readVaultJSONFile(cmd, "spec-file") if err != nil { @@ -435,7 +451,7 @@ JSON } return getVaultsHandler(cmd).Invoke(cmd.Context(), args[0], args[1], args[2], params, vaultOutput(cmd), open) }} - invoke.Flags().String("params", "", "operation parameters json for fill, webmcp_invoke, prepare_checkout, confirm_transaction, remove_payment_method, or 1pw_* (maximum 128 KiB); omit type and credential values; token update operations require --spec-file") + invoke.Flags().String("params", "", "operation parameters json for fill, webmcp_invoke, prepare_checkout, confirm_transaction, remove_payment_method, link_balance_setup, or 1pw_* (maximum 128 KiB); omit type and credential values; token update operations require --spec-file") invoke.Flags().String("spec-file", "", "operation parameters json file (use '-' for stdin; maximum 128 KiB)") invoke.MarkFlagsMutuallyExclusive("params", "spec-file") invoke.Flags().Bool("open", false, "open a returned https action url; cardholder links are human-only, agents must share privately") @@ -489,7 +505,7 @@ JSON walletCreate.Flags().Bool("open", false, "open a returned https connection/enrollment url; cardholder use only, agents must share privately") addVaultJSONOutputFlag(walletCreate) methods := &cobra.Command{Use: "payment-methods ", Short: "fetch advertised live wallet payment methods", Args: cobra.ExactArgs(2), PreRunE: vaultPreRun, - Long: "fetch payment_methods through the item's GET expansion. the wallet must advertise this expansion.\ndisplays selectable ids and advisory capabilities; never automatically chooses a funding method.\njson returns the item with expanded.payment_methods, like items get --expand payment_methods.", + Long: "fetch payment_methods through the item's GET expansion. the wallet must advertise this expansion.\ndisplays selectable ids and advisory capabilities; never automatically chooses a funding method. for stored-value methods such as a Link balance, the available amount is read live from the provider, never stored by Kernel, and shown in the currency's smallest unit with a lowercase ISO 4217 currency code; an absent amount means the provider did not report it.\njson returns the item with expanded.payment_methods, like items get --expand payment_methods.", RunE: func(cmd *cobra.Command, args []string) error { project, _ := cmd.Flags().GetString("project") return getVaultsHandler(cmd).GetItem(cmd.Context(), args[0], args[1], 0, []string{"payment_methods"}, resolveProjectSelection(project), vaultOutput(cmd), false) diff --git a/cmd/vaults_operation_params.go b/cmd/vaults_operation_params.go index cb67ffa7..95e28ea4 100644 --- a/cmd/vaults_operation_params.go +++ b/cmd/vaults_operation_params.go @@ -23,6 +23,7 @@ type vaultOperationParams struct { Passkey *kernel.VaultItemPerformOperationParams OnePassword *kernel.VaultItemPerformOperationParams PaymentMethod *kernel.VaultItemPerformOperationParams + LinkBalanceSetup *kernel.VaultItemPerformOperationParams UpdateAccessToken *kernel.VaultItemPerformOperationParams } @@ -32,7 +33,7 @@ func isOnePasswordOperation(operation string) bool { // vaultOperationTakesParams reports whether an operation accepts --params or --spec-file. func vaultOperationTakesParams(operation string) bool { - return operation == "fill" || operation == "webmcp_invoke" || operation == "prepare_checkout" || operation == "confirm_transaction" || operation == "remove_payment_method" || operation == "update_access_token" || (isOnePasswordOperation(operation) && operation != "1pw_recover" && operation != "1pw_disconnect") + return operation == "fill" || operation == "webmcp_invoke" || operation == "prepare_checkout" || operation == "confirm_transaction" || operation == "remove_payment_method" || operation == "link_balance_setup" || operation == "update_access_token" || (isOnePasswordOperation(operation) && operation != "1pw_recover" && operation != "1pw_disconnect") } func applyVaultAddPaymentMethodEnrollment(operation string, params *vaultOperationParams, enrollment string, set bool) error { @@ -113,8 +114,8 @@ func parseVaultOperationParams(operation, raw string, paramsSet, openSet bool) ( if strings.TrimSpace(operation) == "" { return nil, fmt.Errorf("operation must not be empty") } - if openSet && operation != "authorize" && operation != "collect" && operation != "prepare_checkout" && operation != "1pw_recover" && operation != "restart_verification" { - return nil, fmt.Errorf("--open is only supported for authorize, collect, prepare_checkout, 1pw_recover, and restart_verification") + if openSet && operation != "authorize" && operation != "collect" && operation != "prepare_checkout" && operation != "link_balance_setup" && operation != "1pw_recover" && operation != "restart_verification" { + return nil, fmt.Errorf("--open is only supported for authorize, collect, prepare_checkout, link_balance_setup, 1pw_recover, and restart_verification") } if len(raw) > 128*1024 { return nil, fmt.Errorf("operation parameters exceed 128 KiB") @@ -192,6 +193,35 @@ func parseVaultOperationParams(operation, raw string, paramsSet, openSet bool) ( }, }}, nil } + if operation == "link_balance_setup" { + if !paramsSet { + raw = "{}" + } + object, err := vaultParamsObject(raw, "desired_balance_amount desired_transaction_limit") + if err != nil { + return nil, err + } + request := kernel.LinkBalanceSetupVaultItemOperationRequestParam{ + Type: kernel.LinkBalanceSetupVaultItemOperationRequestTypeLinkBalanceSetup, + } + if value, ok := object["desired_balance_amount"]; ok { + var amount *int64 + if json.Unmarshal(value, &amount) != nil || amount == nil || *amount < 100 || *amount%100 != 0 { + return nil, fmt.Errorf("desired_balance_amount must be an integer of at least 100 cents in whole-dollar increments") + } + request.DesiredBalanceAmount = kernel.Opt(*amount) + } + if value, ok := object["desired_transaction_limit"]; ok { + var limit *int64 + if json.Unmarshal(value, &limit) != nil || limit == nil || *limit < 100 || *limit > 50000 || *limit%100 != 0 { + return nil, fmt.Errorf("desired_transaction_limit must be an integer from 100 to 50000 cents in whole-dollar increments") + } + request.DesiredTransactionLimit = kernel.Opt(*limit) + } + return &vaultOperationParams{LinkBalanceSetup: &kernel.VaultItemPerformOperationParams{ + OfLinkBalanceSetup: &request, + }}, nil + } if operation == "confirm_transaction" { if !paramsSet { return nil, fmt.Errorf("confirm_transaction requires --params or --spec-file") @@ -224,7 +254,7 @@ func parseVaultOperationParams(operation, raw string, paramsSet, openSet bool) ( } if operation != "fill" { if paramsSet { - return nil, fmt.Errorf("--params is only supported for fill, webmcp_invoke, prepare_checkout, confirm_transaction, remove_payment_method, update_access_token, and 1Password operations; authorize takes --browser-id and --page-url, passkey operations take --browser-id and optional --field, add_payment_method takes --enrollment, and restart_verification takes no parameters") + return nil, fmt.Errorf("--params is only supported for fill, webmcp_invoke, prepare_checkout, confirm_transaction, remove_payment_method, link_balance_setup, update_access_token, and 1Password operations; authorize takes --browser-id and --page-url, passkey operations take --browser-id and optional --field, add_payment_method takes --enrollment, and restart_verification takes no parameters") } return nil, nil } diff --git a/cmd/vaults_output.go b/cmd/vaults_output.go index 0944468b..1e77a85f 100644 --- a/cmd/vaults_output.go +++ b/cmd/vaults_output.go @@ -35,6 +35,7 @@ var vaultMethodFields = vaultOutputFields{ "id": nil, "provider": nil, "type": nil, "is_default": nil, "status": nil, "status_reason": nil, "expires_at": nil, "issuer_reference": nil, "valid_until": nil, "action": vaultFieldsOf("name url"), + "balance": {"available": vaultFieldsOf("amount currency")}, "display": vaultFieldsOf("label brand last4"), "capabilities": {"single_use_card": vaultFieldsOf("eligible reasons")}, } @@ -826,17 +827,53 @@ func printVaultPaymentMethodOperationResult(response *kernel.VaultItemOperationR return nil } +func printVaultLinkBalanceSetupResult(response *kernel.VaultItemOperationResponseUnion, output string) (string, error) { + const operation = "link_balance_setup" + if response == nil || response.Type != operation { + return "", fmt.Errorf("unexpected %s response; inspect the wallet before retrying", operation) + } + result := response.AsLinkBalanceSetupVaultItemOperationResult() + setupURL, err := url.Parse(result.URL) + if err != nil || setupURL.Scheme != "https" || setupURL.Hostname() == "" || setupURL.User != nil { + return "", fmt.Errorf("invalid %s URL; inspect the wallet before retrying", operation) + } + // The setup URL is an intended user-facing capability and may contain a + // one-time-looking query key such as "code". Build the safe response from the + // typed fields instead of applying the generic vault URL redaction policy. + raw, err := json.Marshal(struct { + Type string `json:"type"` + URL string `json:"url"` + }{Type: operation, URL: result.URL}) + if err != nil { + return "", fmt.Errorf("invalid %s response; inspect the wallet before retrying", operation) + } + if output == "json" { + if err := printVaultJSON(json.RawMessage(raw)); err != nil { + return "", err + } + return result.URL, nil + } + pterm.Success.Println("Created Link balance setup page") + pterm.Printf("Link balance setup URL:\n%s\n", result.URL) + pterm.Info.Println("only the Link user can complete this page. the URL does not expire and is reused for setup, adding money, and changing the approval threshold. check wallets payment-methods for a balance method and its live available amount instead of assuming the user finished.") + return result.URL, nil +} + func printVaultPaymentMethods(provider string, methods []kernel.VaultPaymentMethod) { if len(methods) == 0 { pterm.Info.Println("no payment methods returned") return } - showIssuerReference, showValidUntil := false, false + showIssuerReference, showValidUntil, showBalance := false, false, false for _, method := range methods { showIssuerReference = showIssuerReference || method.JSON.IssuerReference.Valid() showValidUntil = showValidUntil || method.JSON.ValidUntil.Valid() + showBalance = showBalance || method.JSON.Balance.Valid() } headers := []string{"payment method id", "provider", "type", "label", "brand", "last4", "default", "status", "single-use eligible", "reasons", "status reason", "expires at"} + if showBalance { + headers = append(headers, "available balance (minor units)", "balance currency") + } if showIssuerReference { headers = append(headers, "issuer reference") } @@ -855,6 +892,14 @@ func printVaultPaymentMethods(provider string, methods []kernel.VaultPaymentMeth expiresAt = util.FormatLocal(m.ExpiresAt) } row := []string{m.ID, m.Provider, m.Type, m.Display.Label, m.Display.Brand, m.Display.Last4, fmt.Sprint(m.IsDefault), string(m.Status), eligible, strings.Join(capability.Reasons, ", "), m.StatusReason, expiresAt} + if showBalance { + available, currency := "", "" + if m.Balance.JSON.Available.Valid() { + available = fmt.Sprint(m.Balance.Available.Amount) + currency = m.Balance.Available.Currency + } + row = append(row, available, currency) + } if showIssuerReference { row = append(row, m.IssuerReference) } diff --git a/cmd/vaults_payment_method_operations_test.go b/cmd/vaults_payment_method_operations_test.go index b2bc400d..b3efaa1e 100644 --- a/cmd/vaults_payment_method_operations_test.go +++ b/cmd/vaults_payment_method_operations_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "io" "net/http" "strings" @@ -21,6 +22,16 @@ const kernelWalletPaymentOperationsFixture = `{ "available_expansions":[{"type":"payment_methods","description":"List cards"}] }` +const linkBalanceSetupFixture = `{ + "id":"wallet-id","key":"link-wallet","type":"wallet", + "spec":{"provider":"link"}, + "state":{"provider":"link","status":"connected"}, + "available_operations":[ + {"type":"link_balance_setup","description":"Set up or change Link balance"} + ], + "available_expansions":[{"type":"payment_methods","description":"List payment methods and balance"}] +}` + func TestVaultAddPaymentMethodOperation(t *testing.T) { t.Setenv("KERNEL_PROJECT", "") posts := 0 @@ -132,6 +143,73 @@ func TestVaultRemovePaymentMethodOperation(t *testing.T) { assert.NotContains(t, out, "secret-provider") } +func TestVaultLinkBalanceSetupOperation(t *testing.T) { + t.Setenv("KERNEL_PROJECT", "") + posts := 0 + client := vaultTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodGet { + _, _ = io.WriteString(w, linkBalanceSetupFixture) + return + } + posts++ + body, err := io.ReadAll(r.Body) + require.NoError(t, err) + if posts == 1 { + assert.JSONEq(t, `{"type":"link_balance_setup","desired_balance_amount":10000,"desired_transaction_limit":5000}`, string(body)) + } else { + assert.JSONEq(t, `{"type":"link_balance_setup"}`, string(body)) + } + _, _ = io.WriteString(w, `{"type":"link_balance_setup","url":"https://link.example/balance/setup?code=setup-token","provider_secret":"secret-provider"}`) + }) + + out, text, err := executeVaultCommand(t, client, "vaults", "items", "invoke", "checkout", "link-wallet", "link_balance_setup", "--params", `{"desired_balance_amount":10000,"desired_transaction_limit":5000}`, "-o", "json") + require.NoError(t, err) + assert.Equal(t, 1, posts) + assert.Empty(t, text) + assert.Contains(t, out, `"type": "link_balance_setup"`) + assert.Contains(t, out, `"url": "https://link.example/balance/setup?code=setup-token"`) + assert.NotContains(t, out, "secret-provider") + + _, text, err = executeVaultCommand(t, client, "vaults", "items", "invoke", "checkout", "link-wallet", "link_balance_setup") + require.NoError(t, err) + assert.Equal(t, 2, posts) + for _, want := range []string{"Created Link balance setup page", "does not expire", "only the Link user", "wallets payment-methods", "live available amount"} { + assert.Contains(t, text, want) + } + + opened := "" + params, err := parseVaultOperationParams("link_balance_setup", "", false, true) + require.NoError(t, err) + err = (VaultsCmd{ + vaults: &client.Vaults, + openURL: func(address string) error { opened = address; return nil }, + }).Invoke(context.Background(), "checkout", "link-wallet", "link_balance_setup", params, "", true) + require.NoError(t, err) + assert.Equal(t, 3, posts) + assert.Equal(t, "https://link.example/balance/setup?code=setup-token", opened) +} + +func TestVaultLinkBalanceSetupValidation(t *testing.T) { + for _, tc := range []struct { + raw string + want string + }{ + {`{"desired_balance_amount":99}`, "at least 100"}, + {`{"desired_balance_amount":150}`, "whole-dollar"}, + {`{"desired_transaction_limit":50100}`, "100 to 50000"}, + {`{"desired_transaction_limit":150}`, "whole-dollar"}, + {`{"other":true}`, "only supported"}, + } { + _, err := parseVaultOperationParams("link_balance_setup", tc.raw, true, false) + require.ErrorContains(t, err, tc.want) + } + params, err := parseVaultOperationParams("link_balance_setup", `{"desired_balance_amount":25000}`, true, false) + require.NoError(t, err) + require.NotNil(t, params.LinkBalanceSetup) + assert.Equal(t, int64(25000), params.LinkBalanceSetup.OfLinkBalanceSetup.DesiredBalanceAmount.Value) +} + func TestVaultPaymentMethodOperationValidation(t *testing.T) { calls := 0 client := vaultTestClient(t, func(w http.ResponseWriter, r *http.Request) { calls++ }) @@ -200,16 +278,51 @@ func TestVaultPaymentMethodsExposeLifecycleWithoutCaptureToken(t *testing.T) { assert.NotContains(t, text, "secret-capture") } +func TestVaultPaymentMethodsExposeLiveBalance(t *testing.T) { + fixture := strings.TrimSuffix(linkBalanceSetupFixture, "}") + `, + "expanded":{"payment_methods":[{ + "id":"balance-1","provider":"link","type":"balance","is_default":true, + "status":"active","display":{"label":"Link balance"},"capabilities":{}, + "balance":{"available":{"amount":12345,"currency":"usd"}}, + "provider_secret":"secret-provider" + }]}}` + client := vaultTestClient(t, func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "payment_methods", r.URL.Query().Get("expand")) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, fixture) + }) + + out, _, err := executeVaultCommand(t, client, "vaults", "wallets", "payment-methods", "checkout", "link-wallet", "-o", "json") + require.NoError(t, err) + assert.Contains(t, out, `"balance"`) + assert.Contains(t, out, `"amount": 12345`) + assert.Contains(t, out, `"currency": "usd"`) + assert.NotContains(t, out, "secret-provider") + + _, text, err := executeVaultCommand(t, client, "vaults", "wallets", "payment-methods", "checkout", "link-wallet") + require.NoError(t, err) + for _, want := range []string{"available balance (minor units)", "balance currency", "12345", "usd"} { + assert.Contains(t, text, want) + } +} + func TestVaultPaymentMethodOperationHelp(t *testing.T) { invoke, _, err := newVaultsCommand().Find([]string{"items", "invoke"}) require.NoError(t, err) flat := strings.Join(strings.Fields(invoke.Long), " ") - for _, want := range []string{"add_payment_method is valid", "--enrollment hosted", "--enrollment server", "card_ingest", "5 minutes", "remove_payment_method requires", "payment_method_id", "separate pending enrollment", "without disconnecting the wallet", "removal_pending", "not proof that a payment did not occur", "vaults:write"} { + for _, want := range []string{"add_payment_method is valid", "--enrollment hosted", "--enrollment server", "card_ingest", "5 minutes", "remove_payment_method requires", "payment_method_id", "separate pending enrollment", "without disconnecting the wallet", "removal_pending", "not proof that a payment did not occur", "vaults:write", "link_balance_setup is valid", "eligible_for_balance", "desired_balance_amount", "target balance", "desired_transaction_limit", "always shows that step", "$150", "50000 cents", "does not expire", "wallets payment-methods"} { assert.Contains(t, flat, want) } assert.Contains(t, invoke.Example, "add_payment_method --enrollment server") assert.Contains(t, invoke.Example, "remove_payment_method") + assert.Contains(t, invoke.Example, "link_balance_setup") assert.Contains(t, invoke.Flags().Lookup("params").Usage, "remove_payment_method") + assert.Contains(t, invoke.Flags().Lookup("params").Usage, "link_balance_setup") assert.Contains(t, invoke.Flags().Lookup("enrollment").Usage, "hosted") assert.Contains(t, invoke.Flags().Lookup("enrollment").Usage, "server") + + methods, _, err := newVaultsCommand().Find([]string{"wallets", "payment-methods"}) + require.NoError(t, err) + assert.Contains(t, methods.Long, "never stored by Kernel") + assert.Contains(t, methods.Long, "lowercase ISO 4217") } diff --git a/cmd/workload_identity_issuers.go b/cmd/workload_identity_issuers.go index c7b958e7..c5f5914d 100644 --- a/cmd/workload_identity_issuers.go +++ b/cmd/workload_identity_issuers.go @@ -429,8 +429,8 @@ func buildWorkloadIdentityTokenValidation(in WorkloadIdentityTokenValidationInpu } result := kernel.WorkloadIdentityTokenValidationParam{} if in.MaxLifetimeSeconds.Set { - if in.MaxLifetimeSeconds.Value < 1 || in.MaxLifetimeSeconds.Value > 86400 { - return result, false, fmt.Errorf("--token-max-lifetime-seconds must be between 1 and 86400") + if in.MaxLifetimeSeconds.Value < 1 || in.MaxLifetimeSeconds.Value > 172800 { + return result, false, fmt.Errorf("--token-max-lifetime-seconds must be between 1 and 172800") } result.MaxLifetimeSeconds = kernel.Opt(in.MaxLifetimeSeconds.Value) } @@ -576,7 +576,7 @@ func addWorkloadIdentityIssuerMutationFlags(cmd *cobra.Command, update bool) { cmd.Flags().String("jwks-discovery-base-url", "", "Base URL used for OpenID Connect discovery (maximum 2048 characters)") cmd.Flags().String("jwks-ca-cert-pem", "", "Optional PEM public CA certificates trusted instead of system roots (maximum 65536 characters)") cmd.Flags().String("jwks-keys", "", "Inline JWK set as a JSON array of 1-16 public JWK objects") - cmd.Flags().Int64("token-max-lifetime-seconds", 0, "Maximum incoming exp minus iat, from 1 to 86400 seconds") + cmd.Flags().Int64("token-max-lifetime-seconds", 0, "Maximum incoming exp minus iat, from 1 to 172800 seconds (48 hours; covers Azure managed identity tokens that live slightly over 24 hours)") cmd.Flags().String("token-replay-protection", "", "Incoming token reuse policy: single_use or allow_reuse") if update { cmd.Flags().Int64("expected-version", 0, "Current security_version used for optimistic concurrency (required)") diff --git a/cmd/workload_identity_test.go b/cmd/workload_identity_test.go index 3527650b..cbc4873e 100644 --- a/cmd/workload_identity_test.go +++ b/cmd/workload_identity_test.go @@ -208,11 +208,19 @@ func TestWorkloadIdentityValidationMatchesSpecBounds(t *testing.T) { require.Error(t, err) assert.Contains(t, err.Error(), "not null") + validation, set, err := buildWorkloadIdentityTokenValidation(WorkloadIdentityTokenValidationInput{ + Set: true, MaxLifetimeSeconds: Int64Flag{Set: true, Value: 172800}, + }) + require.NoError(t, err) + assert.True(t, set) + assert.Equal(t, int64(172800), validation.MaxLifetimeSeconds.Value) + _, _, err = buildWorkloadIdentityTokenValidation(WorkloadIdentityTokenValidationInput{ - Set: true, MaxLifetimeSeconds: Int64Flag{Set: true, Value: 86401}, + Set: true, MaxLifetimeSeconds: Int64Flag{Set: true, Value: 172801}, }) require.Error(t, err) - assert.Contains(t, err.Error(), "86400") + assert.Contains(t, err.Error(), "172800") + assert.Contains(t, workloadIdentityIssuersCreateCmd.Flags().Lookup("token-max-lifetime-seconds").Usage, "48 hours") _, _, err = buildWorkloadIdentityAuthorization(WorkloadIdentityAuthorizationInput{ Set: true, ProjectID: "proj_123", Policy: `{"statements":[{"action":"browsers:use","resource":"projects/proj_123/browsers/*"}]}`, diff --git a/go.mod b/go.mod index 71da086e..8007bcf0 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/charmbracelet/lipgloss/v2 v2.0.0-beta.1 github.com/golang-jwt/jwt/v5 v5.2.2 github.com/joho/godotenv v1.5.1 - github.com/kernel/kernel-go-sdk v0.153.0 + github.com/kernel/kernel-go-sdk v0.154.0 github.com/klauspost/compress v1.18.5 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c github.com/pterm/pterm v0.12.80 diff --git a/go.sum b/go.sum index 65b9e4ee..01207a70 100644 --- a/go.sum +++ b/go.sum @@ -68,8 +68,8 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2 github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= -github.com/kernel/kernel-go-sdk v0.153.0 h1:j9nXRESMbpKnhGr0RgGW6ZFw8xSV4+kaoS2ihFE2GAo= -github.com/kernel/kernel-go-sdk v0.153.0/go.mod h1:vAhfZUrC647uk9zju1S62zUqnKN+c3VMi3XJQ83ELsw= +github.com/kernel/kernel-go-sdk v0.154.0 h1:U5uTXBI92DMi/xXh6SYqDpizHfpK5xOcYyC3Tz0cjNI= +github.com/kernel/kernel-go-sdk v0.154.0/go.mod h1:vAhfZUrC647uk9zju1S62zUqnKN+c3VMi3XJQ83ELsw= github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE= github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= diff --git a/pkg/util/errors.go b/pkg/util/errors.go index cbb55efe..81670baa 100644 --- a/pkg/util/errors.go +++ b/pkg/util/errors.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "strings" "github.com/kernel/kernel-go-sdk" ) @@ -29,6 +30,17 @@ func (e CleanedUpSdkError) Error() string { return fmt.Sprintf("%s (invocation_id: %s): %s", code, invocationID, message) } } + if rawFields, ok := m["unsupported_fields"].([]interface{}); ok { + fields := make([]string, 0, len(rawFields)) + for _, rawField := range rawFields { + if field, ok := rawField.(string); ok && field != "" { + fields = append(fields, field) + } + } + if len(fields) > 0 { + return fmt.Sprintf("%s: %s (unsupported fields: %s)", code, message, strings.Join(fields, ", ")) + } + } return fmt.Sprintf("%s: %s", code, message) } else if kerror.Response != nil && kerror.Response.Body != nil { // try response body as text diff --git a/pkg/util/errors_test.go b/pkg/util/errors_test.go new file mode 100644 index 00000000..5d20c078 --- /dev/null +++ b/pkg/util/errors_test.go @@ -0,0 +1,31 @@ +package util + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + kernel "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/option" + "github.com/stretchr/testify/require" +) + +func TestCleanedUpSdkErrorIncludesUnsupportedFields(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = fmt.Fprint(w, `{"code":"unsupported_configuration","message":"The requested browser platform does not support this configuration.","unsupported_fields":["headless","memory","region"]}`) + })) + defer server.Close() + + client := kernel.NewClient( + option.WithBaseURL(server.URL), + option.WithAPIKey("test"), + option.WithMaxRetries(0), + ) + _, err := client.Browsers.New(context.Background(), kernel.BrowserNewParams{}) + require.Error(t, err) + require.EqualError(t, CleanedUpSdkError{Err: err}, "unsupported_configuration: The requested browser platform does not support this configuration. (unsupported fields: headless, memory, region)") +}