Skip to content

fix: correct data-loss, security and UI-thread bugs found in an audit - #52

Merged
MotherSphere merged 53 commits into
mainfrom
gitspace-audit-fixes
Nov 25, 2026
Merged

MotherSphere merged 53 commits into
mainfrom
gitspace-audit-fixes

Conversation

@MotherSphere

Copy link
Copy Markdown
Member

Fixes from a full audit of the iced interface, git layer and token storage. No new screens; the interface redesign follows in its own PR.

Git:

  • Pull fast-forwards only the checked-out branch and push sends it to its upstream name; both refuse when HEAD is another branch.
  • Checkout, pull and stash apply use libgit2's safe checkout and no longer overwrite uncommitted changes.
  • Stash drop and apply check the stash id, so a list changed elsewhere cannot drop the wrong stash.
  • Merge and rebase read git's output while it runs (no deadlock above 64 KB) and re-read the index before listing conflicts.
  • The token is offered only to https:// remotes; git+ssh:// and scp-style URLs count as SSH.
  • History counts real lines, filters before the page limit, and an empty git init repository opens.

Tokens and config:

  • A GitHub Enterprise token is no longer sent to api.github.com; tokens are saved under the host name lookups use; signing out removes the token everywhere; GitLab OAuth tokens refresh; secret files are created 0600.
  • A zero auto-fetch interval no longer stops the app at startup, and one wrong-typed value in config.json no longer resets the whole file.

Interface:

  • Git, keyring and network work runs in background tasks; Stage no longer stages a modified file as deleted when GitSpace is started from another folder; destructive actions ask for confirmation; a Commit button exists; every panel loads when a repository opens.
  • Unused code and 95 unused font files (223 MB) are removed.

Checked locally on Linux with Rust 1.100: fmt, clippy -D warnings, 104 tests. macOS and Windows rely on CI.

Snapshot of the iced rewrite as it stood locally: new views under src/ui,
the git, auth and .NET helper glue they need, and the Cargo changes. It
does not build or pass CI yet; it is pushed so the work is not only on one
machine.
Conflicts resolved as follows:
- auth and config come from main (GitHub device flow, https-only token
  hosts). Token validation stays async for the iced runtime.
- git modules keep the repository cache from this branch and use the
  git2 0.21 API from main.
- the UI keeps the iced rewrite. The built-in updater, removed on main,
  is also removed from the iced preferences, app and notifications.
- dependencies follow main's pinned versions; eframe, egui and
  poll-promise give way to iced 0.13.1, tokio and arboard. The vendored
  objc2 patch was only needed by eframe 0.27 and is dropped.
Ports the device flow from main: the panel shows the user code with copy, open and cancel actions while a background task polls GitHub. Built-in client IDs win over the ones typed in the panel, as on main.
…and line

Ports the terminal launcher from main to the iced overview panel, with its test.
The iced clone panel now streams progress from the clone thread, and a failed clone or search raises a notification with Retry and Copy log path, as the egui panel did. Copying uses iced's clipboard task: arboard dropped its clipboard right after writing, which loses the text on Linux, so the crate is removed.
Unused message variants are removed. Git helpers that are tested but not used by the iced UI yet keep an allow(dead_code) with that reason.
The repository tracked 96 JetBrains Mono Nerd Font files (223 MB) and the binary embedded 8 of them, but no widget asks for a weight, style or the Mono family. Only Regular and the OFL licence stay.
Pull received the upstream branch name and used it as the local branch:
on feature tracking origin/main it moved refs/heads/main, switched HEAD
to main and ran a forced checkout, which discarded uncommitted changes.

pull_branch now takes the local branch and the upstream branch
separately, refuses to run when HEAD is not the local branch, and
fast-forwards that branch with a safe checkout. A modified file that the
update would touch makes the pull fail and leaves the file and the ref
as they were.

push_branch takes the same pair and pushes
refs/heads/<local>:refs/heads/<upstream>. RemoteInfo gains push_url so
the overview resolves the push token from the URL the push goes to.
is_ssh_url only knew ssh:// and user@host:path. git+ssh://, ssh+git://
and host:path without a user slipped past the allow_ssh setting, and the
saved token could be offered to them as a password.

SSH detection now follows git: the three SSH schemes, or a colon before
any slash when there is no scheme, except a Windows drive letter. The
token is only handed out for https:// URLs.
validate_token chose the API with a substring test, so a GitHub
Enterprise host such as github.company.com, which contains github.com,
had its personal access token sent to https://api.github.com/user.

The host is now parsed from the normalized origin and compared exactly:
github.com and api.github.com use https://api.github.com, other hosts
starting with github. use {origin}/api/v3, and gitlab.com or hosts
starting with gitlab. use {origin}/api/v4. Any other host is accepted
without a request, as before. The trimmed token is the one sent.
A manual token was saved under the host exactly as typed, while lookups
go through extract_host, which returns the lowercase host name without
scheme or port. Tokens typed for https://gitlab.example.com,
GitLab.example.com or gitlab.example.com:8443 were saved but never found.

extract_host now also handles host:port, which Url::parse reads as a
URL with a scheme and no host, and always lowercases. Manual and OAuth
tokens are saved, read and cleared under that key. clear_token also
removes an entry saved under the host as typed by an older release.
Branch checkout and stash apply both used a forced checkout. Checkout
replaced modified files with the target branch's version, and stash
apply reset unstaged edits in files the stash does not touch. Both now
use libgit2's safe checkout and report an error when a modified file is
in the way.

Stash apply and drop went by index only, so a stash list that changed
since the panel was refreshed could apply or drop another stash.
StashEntry now carries the stash commit id, and apply_stash and
drop_stash refuse to act when the stash at that index has a different
id.

Stashes are now signed with the repository's configured identity. The
GitSpace placeholder is kept for repositories without one.
With the encrypted fallback off, clear_token left tokens.enc as it was,
so turning the fallback back on brought a signed-out token back. A
failed keyring delete was only logged while the host still left the
host list, which hid a token that remained in use.

clear_token now removes the host from tokens.enc whenever the file
decrypts, whatever the fallback setting. A keyring error is returned and
the host stays listed. clear_oauth_token returns the error of either
entry instead of ignoring the one for the refresh token.
The local key and salt files were written with the default mode and
chmod 0600 afterwards, so they were briefly readable by other users. A
key file of the wrong size, for example after a truncated write, was
regenerated and overwritten, which made tokens.enc unreadable for good.
A salt file of the wrong size was overwritten the same way.

Secret files are now written through write_private, a variant of
write_atomic that creates the temporary file with mode 0600 on Unix
before renaming it into place. tokens.enc and token-hosts.json use it
too, so a file left 0644 by an older release becomes 0600 on its next
write. A key or salt file of the wrong size is treated like an
unreadable one: an error is logged, a secret for this session only is
used and the file is left as it is.
detect_conflicts runs on the thread-local cached repository, whose index
object is loaded once. After `git merge` wrote a conflicted index, it
still saw the old one and reported no conflicts. It now calls
index.read(false) first. Status and diff already refresh the index, and
refs and HEAD are read from disk on each lookup.

The cache kept a RwLock inside the thread-local RefCell, so a closure
that called with_cached_repo again deadlocked on the lock. The cache is
now a map of Rc<Repository> borrowed only during lookup. RepoCache,
RepoHandle and their helpers were only used by the module's own tests,
and invalidate_cached had no caller; they are removed, along with the
module-wide allow(dead_code).
When the keyring was locked at startup, tokens.enc was written with the
local key. On the next start with the keyring unlocked, the keyring key
was used and the file could no longer be decrypted.

When the keyring key fails to decrypt tokens.enc, the local key file is
now tried as well, without creating it. After a successful fallback
decrypt the tokens are written again under the keyring key, and the
configuration guide says so. The doc comment of the local key now states
that GITSPACE_TOKEN_MASTER_PASSWORD only applies to that key, as the
guide already did.
stdout and stderr were piped but only read after the process exited.
Once git wrote more than a pipe buffer (64 KiB on Linux), it blocked on
the write and the wait loop ran until the 5-minute timeout. Both pipes
are now read on their own threads while the loop polls, and the
timeout still kills the process.
GitLab access tokens expire after about two hours. The refresh token was
saved but never used, so a GitLab OAuth sign-in stopped working after
that time.

OAuthToken now also saves the client ID and token endpoint it was issued
with. When resolve_for_host finds an expired OAuth token that has a
refresh token, it exchanges the refresh token through the blocking oauth2
client, saves the new token and returns its access token. A response
without a new refresh token keeps the current one. If the refresh fails,
including for tokens saved by older releases without a client ID, the
error is logged and no token is returned.
The callback server handled error= before it checked the state, and a
state mismatch ended the wait. Any request to
127.0.0.1:9876/callback, from any web page, could therefore end the
sign-in. The provider's error and error_description were put into the
answer page without HTML escaping. Accepted sockets inherit
non-blocking mode on macOS and Windows, so read() could fail with
WouldBlock and the real callback was dropped.

parse_callback now checks the state first. A request on another path or
without the expected state gets a 400 answer and the wait goes on. Query
values are percent-decoded, and the error page escapes the error text.
The accepted socket is switched back to blocking mode before it is read.
Only the setters clamped these values. An auto_fetch_interval_minutes of
0 in config.json or in an imported file reached iced::time::every with a
zero duration, which panics in tokio. With panic = "abort" in release
builds, GitSpace then closed on every launch.

The getters now clamp as well: the auto-fetch interval to 1 to 1440
minutes, so the conversion to seconds cannot overflow, and the log
retention to MIN_LOG_RETENTION_FILES to MAX_LOG_RETENTION_FILES.
Importing any JSON object yielded the default preferences, which were
then saved: the full config.json, whose fields sit under
"preferences", or {} reset every preference. Export wrote "{}" when
serialization failed and wrote the file in place.

Import now reads the "preferences" object of a whole config.json, and
refuses a file that has none of the known preference fields. Export goes
through write_atomic and returns serialization errors.
Diff:
- Commit summaries reported file sizes in bytes as additions and
  deletions. They now come from each delta's patch line stats.
- Patch text started header lines with libgit2's origin codes (F, H, B,
  =, >, <). Only added, removed and context lines get a prefix now.
- Single-file diffs treated the path as a glob, so `[draft].md` matched
  `d.md` instead of itself. Pathspec matching is now disabled for them.
- Non-UTF-8 paths no longer all map to one "(unknown)" entry.

Log:
- Filters ran after revwalk.take(limit), so the limit counted walked
  commits and a match older than the first `limit` commits was missed.
  The walk now stops once `limit` commits matched.
- The branch filter only looked in refs/heads; names such as origin/x
  are now resolved too.
- A repository with no commit yet returns an empty log instead of an
  error.

Status: an unborn HEAD now reports its branch name instead of failing.
- list_branches uses Branch::is_head instead of comparing names with
  HEAD's shorthand.
- merge.rs: the EmptyStringExt trait served one call and is inlined.
- compare.rs: include_untracked has no effect on a tree-to-tree diff.
- find_repo_root opened the discovered repository a second time through
  the cache and ignored it.
The repository cache was its only user and no longer needs a lock.
Nothing in the tree used these items:

- AuthManager::set_token
- the keybindings preference and the Keybinding type
- the branch_box_height preference and MIN_BRANCH_BOX_HEIGHT
- the AppError::Auth variant and the AppError constructor helpers, which
  only their own test called

The module-wide allow(dead_code) in error.rs is gone so the compiler
reports unused items again. The git2 conversion test now converts a real
git2::Error. Old config.json and exported files that still have the
removed fields load as before: unknown fields are ignored.
Removing a token returned an error when no Secret Service, Keychain or Credential Manager is running, so the account could never leave the list. That case now counts as nothing to remove; a locked keyring is still an error.
The Latte, Frappe, Macchiato and Mocha constructors repeated the same typography and spacing. Theme::from_mode now passes the palette to one private constructor.
Control height, motion intensity, reduced motion and performance mode were only read by animation.rs, which nothing used. They are removed from the panel, from Preferences and with animation.rs. Old config files that still hold these keys load as before; serde ignores them.

A theme change now applies the last applied preferences with the new theme, instead of every unsaved edit in the panel. Closing the panel restores the last applied values. Reset asks for confirmation first. Import and export errors are shown in red under the buttons, and a cancelled file dialog no longer reports an error.

The five button style closures share one helper.
Staging, unstaging, stash, restore and the status refresh ran on the UI thread, and every refresh built the patch of every changed file. They now run on the blocking pool. Results carry the repository path and are dropped after a switch. The refresh lists files only; the patch of the selected file loads when it is picked. Action buttons are disabled while one runs, and view() no longer reads the repository for the restore dialog.

stage_path checked Path::exists against the process working directory, so launched from $HOME a modified README.md was staged as deleted. It now checks the file under the repository workdir.

Errors show above the controls instead of replacing them, and clear on the next action. Dropping a stash asks for confirmation, and the stash list is read again after any stash error.

git::commit::commit_index commits the index on HEAD, or as a root commit on an unborn branch, with the identity from the Git config. It refuses an empty message, an index equal to HEAD and a merge or rebase in progress. The Commit button uses it and clears the message on success. The sign-off line comes from the same identity instead of a placeholder address.

StagePanel::load resets the panel and loads a repository in the background. refresh_if_needed still loads synchronously until app.rs calls load.
animation.rs and perf.rs had no callers outside their own files. The Dev Gallery tab only showed in debug builds and described hover effects the widgets do not have. The GITSPACE_PROFILE_UI variable read by perf.rs goes with it, and the docs no longer list these files.
Clicking x or an action button only marked the toast, which then stayed on screen until the next one-second tick. It is now removed in the same update. Toasts carry an id so a click cannot close a neighbour after an expired toast is dropped. The module-wide allow(dead_code) is gone with what it hid: the unread log_path field, progress(), with_detail(), with_duration(), and the Success and Info kinds that only tests used.
The empty Open tab called dirs and Path::exists for four folders on every frame. The list is now built when the panel is created. The folder picker moves into pick_folder() so the Clone tab can use the same code.
…them

Every keystroke, Search press and provider switch bumps a search version. SearchResult carries the version it answers and older results are dropped, so a slower earlier query or a result for the previous provider no longer replaces newer results. Pressing Search during the debounce no longer starts the same search twice. Search and DebouncedSearch share start_search().

GitLab search sent an OAuth token as PRIVATE-TOKEN, which GitLab rejects with 401. Both providers now get Authorization: Bearer, which also works for personal access tokens.

GitHub search kept going after a failed request with an empty list, so a 403 rate limit showed "0 résultat(s)", and a failure on the private repositories call threw away the public results. The results that did arrive are now kept, and the first error is shown only when every request failed. The account name is percent-encoded in the API paths.

Tokens for search and clone are looked up inside the background task, through resolve_for_url, instead of on the UI thread. The results pick list borrows the results instead of cloning them twice per frame.
The Auth tab called known_hosts() and has_oauth() for every host on every frame: a file read and decryption, then a keyring lookup per host. The list is now cached in the panel and reloaded by a background task at startup, after a token is stored, validated or removed, and when the token storage settings change.

Saving an OAuth token and disconnecting an account also run in background tasks. A failed disconnect is shown under the account list; it used to be dropped. GitHub and GitLab share the code that turns an OAuth result into a status line.
Recent, Favorites and Local Repos all opened the Open tab and were all highlighted together. Favorites had no feature behind it. Only Recent remains. Sidebar entries now send TabSelected, so the separate SidebarNav message, handled the same way, is gone.
Pinning a branch saved the new list in the config but not in the Preferences panel, which kept its own copy. Applying any preference afterwards wrote that old copy back and unpinned the branch. The panel now gets the updated preferences after every pin change.
RepoContext::from_path filled current_branch, is_dirty and upstream_remote, and nothing read them. is_dirty ran a full statuses() scan, untracked files included, on every load. The context now holds the path and name, and opening the repository is enough to validate the path.
…ive ones

Every branch operation ran on the UI thread, including merge and rebase, which run git for up to 300 seconds, and a refresh that reads the last commit of each branch. They now run on the blocking pool, with the repository path in each result. Action buttons are disabled while one runs. Errors show above the controls and clear on the next action.

Delete, merge and rebase ask for confirmation. The delete prompt says when the branch has commits that the current branch does not contain. A checkout that git refuses shows its error.

The rebase button said "Rebase onto current" and the doc comment described the reverse of what runs. The action is git rebase <selected>, which rebases the current branch onto the selected one. The button, the message name and the comment now say that.

BranchPanel::load resets the panel, keeping pinned branches, and loads a repository in the background.
…asks

At startup the last repository was opened synchronously and the overview
was never filled, so it showed "(detached)" and "No remotes" until another
repository was picked. The app now starts with no repository and loads
the most recent one with load_repo_context_async.

RepoContextLoaded applied any result it got. The latest requested path is
now kept, and a result for another path is dropped. When a path cannot be
opened, an error toast says so and the current repository and the recent
list stay as they were.

Repo Overview read the status and remotes, and ran fetch, pull and push,
on the UI thread, so the window froze for the whole network operation.
Each of these is now a task that reports back with StateLoaded or
ActionFinished. Fetch, Pull and Push are disabled while one runs, and a
result for a repository that is no longer open is dropped. Tokens are
looked up inside the task, since a keyring read can block and an expired
GitLab OAuth token is refreshed over HTTP. The fallback that looked up a
whole remote URL as a host name is removed.

Auto-fetch goes through the same task. The first fetch now happens one
interval after the repository loads instead of two, a repository without
a remote is skipped without a toast every interval, and a result is no
longer applied to a repository opened after it started. The unused tick
payload and auto_fetch_last are removed.

The sidebar button and the overview button open the folder with the same
open_folder() helper, and both report a failure.
The commit log, the file list of a commit and each file patch were read on the UI thread. They now run on the blocking pool. Each log read carries a request number, so a slow reply to an older search is dropped. A load error shows under the filters instead of hiding them, and clears on the next search.

The local branch list was loaded and never shown. It now fills a pick list next to the branch filter. pending_refresh was written and never read; a branch filter set without an open repository is now kept for the next load. The CommitFilter built twice by copy-paste comes from one helper, and Load more reuses the filter of the last search instead of whatever is typed in the fields.

The git log counts matching commits against the limit, so a full page means more may match. Load more reads the first N + 50 matches and replaces the list.

HistoryPanel::load resets the panel and loads a repository. show_branch returns the task for a branch filter; set_branch_filter still reads synchronously until app.rs calls show_branch.
Opening a repository now loads Stage, Branches and History in background tasks next to Repo Overview; before, Branches and History stayed empty or showed the previous repository. A commit, checkout, merge or rebase reloads the other panels. The blocking refresh_if_needed and set_branch_filter wrappers are removed.
Worktree and submodule listing, upstream set/unset, tracking branch listing, prune, the whole-commit and working-tree diffs, the grouped working-tree status and the HTTPS policy helper had tests but no caller outside them. They are removed with their tests, along with fields nothing read (branch upstream, commit parents and time, FileDiff.path) and the allow(dead_code) attributes that hid them.
The egui shell had these shortcuts (Cmd on macOS) and the iced port lost them.
The architecture, UI stack and layout pages still described the egui shell, poll_promise threads, the removed motion settings and helpers, and the tab dragging the iced port does not have. They now describe the iced tasks, safe checkouts, the push and pull rules, the token storage changes and the commit action.
…e checkout

push_branch now refuses when HEAD is not the branch it was asked to push, like pull_branch. Checkout on a cached repository handle reloads the index first, so libgit2 does not write back an index that predates a git add made elsewhere.
A failed OAuth refresh returned no token at all; it now returns the saved access token. Refreshes for a host run one at a time and re-read the token under the lock, since a provider may refuse a refresh token used twice. Saving a personal access token removes the host's OAuth entry, whose refresh would overwrite it.
A wrong-typed value anywhere in config.json reset the whole file, recent repositories and token settings included. Loading now takes the valid values one key at a time and uses the default only for the ones that fail.
… reload

After a checkout, merge or commit the overview kept the old branch, so Push could target it. It now rereads its state, a successful pull reloads the other panels, and a fetch, pull or push that finishes after a repository switch shows a notification. Reloading the Stage panel for the same repository keeps the commit and stash messages.
The Windows runner checks files out with CRLF (core.autocrlf), so the pull test failed on content that was otherwise correct.
@MotherSphere
MotherSphere merged commit fd0099d into main Nov 25, 2026
10 checks passed
@MotherSphere
MotherSphere deleted the gitspace-audit-fixes branch November 25, 2026 10:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant