diff --git a/README.md b/README.md index f1dc06b..b7e2679 100644 --- a/README.md +++ b/README.md @@ -387,12 +387,6 @@ banner exchange: Connection to port : Software caused connection abor Example configuration for `Git Bash` on Windows, using a Cygwin-compatible listener: ```toml -[history] -# Add a setting only to override its default: -# enabled = false -# path = "/path/to/history.sqlite" -# remember_selection = false - [agent] # Replace USERNAME with your Windows user name: upstream = 'C:\Users\USERNAME\.ssh\ssh-upstream-agent.sock' @@ -412,6 +406,12 @@ allow_unbound_signing_on_bind_failure = false file = "" level = "off" +[history] +# Add a setting only to override its default: +# enabled = false +# path = "/path/to/history.sqlite" +# remember_selection = false + [gui] theme = "light" # "light" or "dark" ``` @@ -431,6 +431,8 @@ The window title combines the action, application name, and local display time. When `history.remember_selection` is enabled and the request includes a verified target host key, the GUI remembers the selected key for that host and preselects it the next time the same host key is seen. The picker still opens and requires you to confirm a selection. Requests without a verified target host key start with the first key. +When `history.enabled` is enabled and the request includes a verified target host key, the picker displays a `First selection` badge if no earlier selection matches the same Target Host and Forwarded path. It applies to the request context, not an individual key, and does not indicate whether a prior key authenticated successfully. The badge is omitted when the target host or forwarded path cannot be verified, or history cannot be read. + When `history.enabled` is enabled, choose `File > History…` or press Ctrl+Shift+H (Cmd+Shift+H on macOS) to review request time, target host and forwarded hops, selected key, selection time, and whether the picker completed, was canceled, or timed out. Right-click a row to copy its displayed information or delete it. Use `Export CSV` to save the full history and host paths. The result describes the picker interaction; it does not indicate whether the SSH server accepted authentication. Right-click a key row and choose `Copy`, or press Ctrl+C, to copy its Comment, Type, Size, and Fingerprint as tab-separated text. diff --git a/cmd/ssh-keyselect-gui/gui_history.go b/cmd/ssh-keyselect-gui/gui_history.go index d858858..9fda63f 100644 --- a/cmd/ssh-keyselect-gui/gui_history.go +++ b/cmd/ssh-keyselect-gui/gui_history.go @@ -98,9 +98,10 @@ func (a *guiApp) openHistory() { if a.historyError != "" { state.loadError = "Could not open history: " + a.historyError } + // Fit all history columns at the default window width. window := mygo.NewWindow(mygo.WindowOptions{ Title: "History - SSH KeySelect", Parent: a.window, - Width: 1000, Height: 430, MinWidth: 820, MinHeight: 350, + Width: 1470, Height: 450, MinWidth: 820, MinHeight: 350, Content: ui.View(state.view), }) state.window = window diff --git a/docs/dev.md b/docs/dev.md index 3fa8c63..7649979 100644 --- a/docs/dev.md +++ b/docs/dev.md @@ -121,6 +121,8 @@ The proxy opens a temporary upstream session for each bound operation and replay #### GUI selection history +When event recording is enabled, the GUI picker reads selected outcomes for the final verified target-host fingerprint and compares the ordered fingerprints of forwarded hops. It shows `First selection` when no prior selection event matches that Target Host and Forwarded path. This context-level marker records a picker selection only, not SSH authentication success. Missing target context, incomplete forwarded fingerprints, disabled event recording, or a history read error suppresses the marker; preference-only mode does not provide this history. + `internal/selectionhistory` stores GUI selection events, verified host hops, and the last selected key for each verified target host in `history.sqlite` under the per-user application-data directory by default. `[history].path` selects another file when set; it is omitted from saved configuration when empty, and relative paths resolve from the application-data directory. GUI Settings leaves the field empty and shows the resolved default path as its placeholder. `[history].enabled` and `[history].remember_selection` both default to true, are saved only when false, and are independent: the first controls event recording and the History window, while the second controls per-host preference reads and writes. The application opens the database only when at least one switch is enabled; when both are disabled, startup and configuration apply skip database path resolution and SQLite open/create. If both features are enabled, the event and preference update share one transaction. History-only recording does not update preferences; preference-only recording does not create events. Preferences use the final non-forwarding host-key fingerprint and selected public-key fingerprint; they only set the picker's initial row. Requests without a verified target host key do not read or update a preference. When history is enabled, the proxy captures `requested_at` when it receives `RequestIdentities`, before listing upstream identities. The GUI records when the picker opens, when the user selects or cancels, and the outcome. Host hops preserve binding order, forwarding flags, fingerprints, and `known_hosts` display hints. The compact history table pages 50 rows ordered by request time, shows target host names separately from the host key, and shows selected-key comment, public-key data, and fingerprint in separate columns. It copies its displayed row fields and deletes events with their host-hop rows. Forwarding paths use ` -> ` between hops and comma-separated known-host hints followed by the key in brackets. CSV export starts with the table's columns in display order, then adds event and connection metadata, the complete host path as JSON, and the selected key algorithm and blob in Base64. When key remembrance is enabled, deleting the latest event for a host restores the prior surviving key preference. The result is the picker outcome, not SSH authentication acceptance, which the agent protocol does not expose. diff --git a/internal/config/config.go b/internal/config/config.go index b6bbdd1..e4971bc 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -62,9 +62,9 @@ type GUIConfig struct { } type saveConfig struct { - History *saveHistoryConfig `toml:"history,omitempty"` Agent saveAgentConfig `toml:"agent"` Log LogConfig `toml:"log"` + History *saveHistoryConfig `toml:"history,omitempty"` GUI GUIConfig `toml:"gui"` } diff --git a/internal/selectionhistory/store.go b/internal/selectionhistory/store.go index 7ff4c8b..6cbecca 100644 --- a/internal/selectionhistory/store.go +++ b/internal/selectionhistory/store.go @@ -289,6 +289,71 @@ func (s *Store) PreferredSelection(ctx context.Context, targetHostFingerprint st return fingerprint, true, nil } +// HasSelectionContext reports whether a picker selection exists for a target and forwarded path. +func (s *Store) HasSelectionContext(ctx context.Context, targetHostFingerprint string, forwardedFingerprints []string) (bool, error) { + if s == nil || s.db == nil || targetHostFingerprint == "" { + return false, nil + } + release, err := s.Retain() + if err != nil { + return false, err + } + defer release() + rows, err := s.db.QueryContext(ctx, ` + SELECT e.id, h.host_key_fingerprint, h.is_forwarding + FROM selection_events AS e + LEFT JOIN selection_host_hops AS h ON h.event_id = e.id + WHERE e.target_host_fingerprint = ? AND e.outcome = ? AND e.selected_key_fingerprint != '' + ORDER BY e.id DESC, h.ordinal`, + targetHostFingerprint, string(OutcomeSelected), + ) + if err != nil { + return false, fmt.Errorf("read selection context from history: %w", err) + } + defer rows.Close() + forwardingPathMatches := func(path []string) bool { + if len(path) != len(forwardedFingerprints) { + return false + } + for index := range path { + if path[index] != forwardedFingerprints[index] { + return false + } + } + return true + } + var eventID int64 + var forwardingPath []string + haveEvent := false + for rows.Next() { + var rowEventID int64 + var fingerprint sql.NullString + var isForwarding sql.NullInt64 + if err := rows.Scan(&rowEventID, &fingerprint, &isForwarding); err != nil { + return false, fmt.Errorf("read selection context row: %w", err) + } + if haveEvent && rowEventID != eventID { + if forwardingPathMatches(forwardingPath) { + return true, nil + } + forwardingPath = nil + } + if !haveEvent || rowEventID != eventID { + eventID, haveEvent = rowEventID, true + } + if isForwarding.Valid && isForwarding.Int64 != 0 && fingerprint.Valid { + forwardingPath = append(forwardingPath, fingerprint.String) + } + } + if haveEvent && forwardingPathMatches(forwardingPath) { + return true, nil + } + if err := rows.Err(); err != nil { + return false, fmt.Errorf("read selection contexts from history: %w", err) + } + return false, nil +} + // RememberSelection stores a selected key without creating a history event. func (s *Store) RememberSelection(ctx context.Context, targetHostFingerprint, selectedKeyFingerprint string, selectedAt time.Time) error { if s == nil || s.db == nil { diff --git a/internal/selector/gui.go b/internal/selector/gui.go index e5449a6..8bf9d42 100644 --- a/internal/selector/gui.go +++ b/internal/selector/gui.go @@ -204,6 +204,7 @@ func (s *GUISelector) Select(ctx context.Context, identities []identity.Identity defer releasePickerReturnWindow(returnWindow) shownAt := time.Now() offered := append([]identity.Identity(nil), identities...) + hasPriorContextSelection, selectionHistoryKnown := guiHasSelectionHistory(ctx, history, recordHistory, requestContext) selectedIndex := 0 if rememberSelection { selectedIndex = guiPreferredSelectionIndex(ctx, history, requestContext, offered) @@ -213,6 +214,7 @@ func (s *GUISelector) Select(ctx context.Context, identities []identity.Identity offered: offered, requestContext: requestContext, detailsText: guiSelectionDetailsText(requestContext, shownAt), shownAt: shownAt, refresh: refresh, + hasPriorContextSelection: hasPriorContextSelection, selectionHistoryKnown: selectionHistoryKnown, selected: selectedIndex, focusFilter: true, // The current target is the final entry in a multi-host path. detailsScroll: ui.ScrollState{Y: math.MaxFloat32}, @@ -396,6 +398,40 @@ func guiPreferredSelectionIndex(ctx context.Context, history *selectionhistory.S return 0 } +func guiHasSelectionHistory(ctx context.Context, history *selectionhistory.Store, recordHistory bool, requestContext SelectionContext) (bool, bool) { + target, forwarded, ok := selectionContextHistoryKey(requestContext) + if !recordHistory || history == nil || !ok { + return false, false + } + hasSelection, err := history.HasSelectionContext(ctx, target, forwarded) + if err != nil { + slog.Warn("could not read GUI selection-context history", "error", err) + return false, false + } + return hasSelection, true +} + +func selectionContextHistoryKey(requestContext SelectionContext) (string, []string, bool) { + if len(requestContext.HostBindings) == 0 { + return "", nil, false + } + target := requestContext.HostBindings[len(requestContext.HostBindings)-1] + if target.IsForwarding || target.Fingerprint == "" { + return "", nil, false + } + forwarded := make([]string, 0, len(requestContext.HostBindings)) + for _, binding := range requestContext.HostBindings { + if !binding.IsForwarding { + continue + } + if binding.Fingerprint == "" { + return "", nil, false + } + forwarded = append(forwarded, binding.Fingerprint) + } + return target.Fingerprint, forwarded, true +} + func (s *GUISelector) init() { s.initOnce.Do(func() { if s.queue == nil { @@ -417,33 +453,35 @@ type guiSelectionResult struct { } type guiPickerState struct { - ctx context.Context - identities []identity.Identity - offered []identity.Identity - requestContext SelectionContext - detailsText string - shownAt time.Time - refresh func(context.Context) ([]identity.Identity, error) - selected int - query string - lastQuery string - err string - refreshing bool - expired bool - hasSelection bool - chosen identity.Identity - focusTime uint32 - closePending bool - searchOptions []identityOption - optionsValid bool - matchesCache []identityMatch - matchesQuery string - matchesValid bool - tableRows []guitable.IdentityRow - detailsScroll ui.ScrollState - tableState ui.ListState - window *mygo.Window - focusFilter bool + ctx context.Context + identities []identity.Identity + offered []identity.Identity + requestContext SelectionContext + detailsText string + shownAt time.Time + refresh func(context.Context) ([]identity.Identity, error) + selected int + query string + lastQuery string + err string + refreshing bool + expired bool + hasSelection bool + chosen identity.Identity + focusTime uint32 + closePending bool + searchOptions []identityOption + hasPriorContextSelection bool + selectionHistoryKnown bool + optionsValid bool + matchesCache []identityMatch + matchesQuery string + matchesValid bool + tableRows []guitable.IdentityRow + detailsScroll ui.ScrollState + tableState ui.ListState + window *mygo.Window + focusFilter bool } func (p *guiPickerState) view(c *ui.Context) { @@ -512,6 +550,12 @@ func (p *guiPickerState) view(c *ui.Context) { ui.Text(c, "Keys").FontSize(theme.Rem(0.9)).TextColor(keyBadgeText). Background(keyBadgeFill).Padding(theme.Space(0.5), theme.Space(1.5)).Radius(theme.Space(1.5)) ui.Text(c, fmt.Sprintf("%d/%d", len(matches), len(p.identities))).FontSize(theme.Rem(0.9)).TextColor(theme.TextMuted) + if p.selectionHistoryKnown && !p.hasPriorContextSelection { + badgeFill, badgeText := guitable.WarningBadgeColors(theme) + ui.Text(c, "First selection").SingleLine().Shrink(0).FontSize(theme.Rem(0.75)). + TextColor(badgeText).Background(badgeFill).Padding(theme.Space(0.25), theme.Space(1)). + Radius(theme.Space(1)).Tooltip("No prior key selection for this Target Host and forwarded path.") + } if p.err != "" { ui.Text(c, p.err).SingleLine().TextColor(theme.Danger).Grow(1) } else {