Configure profile-aware Git authentication and diagnose Nix setup failures

This commit is contained in:
Ziad Arafat committed 2026-11-15 11:49:52 -07:00
1 parent df7ffa82ed
commit da2f8bb2e3
10 files changed
+738 -18

No files matched your search

+16 -1
View File
@@ -47,7 +47,7 @@ Then, once per machine (`bw` already points at `https://vault.etvamerica.com`; o
```bash
bw login && export BW_SESSION=$(bw unlock --raw)
dot secrets pull # ~/.ssh/id_ed25519, secrets.env, Claude/pi MCP config, ~/.git-credentials
dot secrets pull # ~/.ssh/id_ed25519, secrets.env, Claude/pi MCP config
dot secrets pull --wireguard # also import WireGuard connections into NetworkManager (sudo)
dot boxes # distrobox: general (Fedora), etv (AlmaLinux 10)
dot doctor
@@ -57,6 +57,14 @@ Manual sign-ins that can't be automated: Edge (work account), Chrome and Firefox
## Desktop profiles
Git uses your personal GitHub email (`anonymous0programmer@gmail.com`) for `full`
and `headless`, and `ziad.arafat@etvamerica.com` for `full-work`. Both desktop
profiles install **SourceGit**, with browser OAuth and encrypted keyring storage
for GitHub and the appropriate Gitea origin. Headless uses terminal token prompts
and an in-memory cache. All profiles can read matching Git credentials from an
explicitly unlocked Bitwarden vault. See [Git authentication](docs/git-auth.md)
for first login, vault selection and migration from plaintext credentials.
`full` is the personal desktop and includes Codex alongside Claude. Codex is managed by Nix and updated by `dot switch` after updating flake inputs. Sign in with `codex` on first use; credentials stay outside this repository.
### Agent environments
@@ -110,6 +118,13 @@ For a fresh installation, set `DOTFILES_PROFILE=full-work`. `headless` remains t
| `dot sounds` | build the Portal 2 sound theme from your Steam install |
| `dot doctor` | what's installed or missing |
`dot doctor` checks Nix startup, store/database access, broken profile links,
daemon versus single-user setup, `nix-command` and flakes, and the checkout's
flake files. This catches interrupted installers and feature overrides before
`dot switch` fails. Probes are bounded and read-only; a failed daemon connection
gets a different repair hint from a single-user store problem. Doctor also
checks the profile's Git credential tools and desktop SourceGit/OAuth helper.
Apps that write their own settings (Claude Code, pi, Vesktop, Konsole profiles, VSCodium, Zed, `~/.ssh/config`) are linked **out of the Nix store** into this checkout. Changes made in the app show up in `git diff`, so commit them.
## What's in it
+12 -10
View File
@@ -463,14 +463,8 @@ secrets_render() {
chmod 600 "$HOME/.pi/agent/mcp.json"
ok "pi MCP servers"
# HTTPS git auth for the forges (credential.helper=store).
(umask 077; {
[ -n "${GITEA_DOGE_TOKEN:-}" ] && echo "https://ziadarafat:$GITEA_DOGE_TOKEN@gitea.godemperordoge.org"
[ -n "${ETV_GITEA_TOKEN:-}" ] && echo "https://ziadarafat:$ETV_GITEA_TOKEN@gitea.etvamerica.com"
[ -n "${GITHUB_ACCESS_TOKEN:-}" ] && echo "https://RustyRaptor:$GITHUB_ACCESS_TOKEN@github.com"
} >"$HOME/.git-credentials")
chmod 600 "$HOME/.git-credentials"
ok "git credentials"
# Git now uses the profile's credential manager and optional unlocked vault.
# Do not write a plaintext ~/.git-credentials or modify an existing one.
}
cmd_secrets() {
@@ -646,7 +640,10 @@ cmd_doctor() {
local p; p="$(profile)"
printf 'os=%s profile=%s container=%s systemd=%s\n' "$(os_id)" "$p" "$(in_container && echo yes || echo no)" "$(has_systemd && echo yes || echo no)"
chk() { if eval "$2" >/dev/null 2>&1; then ok "$1"; else warn "$1 — $3"; fi; }
chk "nix" "source_nix" "dot nix"
# Diagnose interrupted installs and disabled features independently, without
# network access or automatically changing the installation.
source "$DOTFILES_DIR/scripts/doctor-nix.sh"
doctor_nix
chk "home-manager" "have home-manager" "dot switch"
chk "zsh + oh-my-zsh" "have zsh && [ -d \"\$(dirname \"\$(readlink -f ~/.zshrc)\")\" ]" "dot switch"
chk "mise" "have mise" "dot switch"
@@ -654,6 +651,11 @@ cmd_doctor() {
chk "pi" "have pi || mise which pi" "dot apps"
chk "pokemon-go-colorscripts" "have pokemon-go-colorscripts || mise which pokemon-go-colorscripts" "dot apps"
[ "$p" != full ] || chk "codex" "have codex" "dot switch"
chk "Git credential manager" "have git-credential-dotfiles && have git-credential-manager" "dot switch"
if is_desktop; then
chk "SourceGit" "have sourcegit" "dot switch"
chk "Git browser OAuth helper" "have git-credential-oauth" "dot switch"
fi
chk "claude" "[ -x ~/.local/bin/claude ]" "dot apps"
if ! in_container; then
chk "podman" "have podman" "dot system"
@@ -696,7 +698,7 @@ cmd_bootstrap() {
cat <<EOF
${c_grn}Done.${c_off} Next, once per machine:
bw login && export BW_SESSION=\$(bw unlock --raw) && dot secrets pull # SSH keys, MCP tokens, git creds
bw login && export BW_SESSION=\$(bw unlock --raw) && dot secrets pull # SSH keys and MCP tokens
dot boxes # create the general/etv distroboxes
dot doctor # see what's left
Then sign in: Edge (work), Chrome + Firefox (personal), XPipe git sync token, Bitwarden.
+116
View File
@@ -0,0 +1,116 @@
# Git identity and authentication
| Profile | Commit email | SourceGit | HTTPS credential storage | Sign-in |
|---|---|---|---|---|
| full | anonymous0programmer@gmail.com (owner-confirmed GitHub email) | Installed | Desktop Secret Service/keyring | Browser OAuth or unlocked Bitwarden |
| full-work | ziad.arafat@etvamerica.com | Installed | Desktop Secret Service/keyring | Browser OAuth or unlocked Bitwarden |
| headless / headless-aarch64 | Personal email | Omitted | One-hour memory cache | Terminal personal-access token or unlocked Bitwarden |
Commit identity follows the selected dotfiles profile. A repository-local
`user.email` still overrides the default using normal Git precedence. HTTPS
credentials are selected independently by the remote's host; a work token is not
sent to a personal host. SSH remotes continue using SSH keys and do not invoke
HTTPS credential helpers.
## Desktop use
After `dot switch`, open SourceGit from the application launcher or run
`sourcegit`. It uses the configured Git credential helper. On the first private
HTTPS fetch/push, the browser opens for GitHub or the matching Gitea instance:
- Work: https://gitea.etvamerica.com
- Personal: https://gitea.godemperordoge.org
- GitHub: https://github.com
Sign in normally, including SSO/MFA, and approve the Git OAuth application. Public
repository reads may succeed without a login, which is normal. Stock Gitea
instances provide the OAuth application used by git-credential-oauth; instances
where that application has been disabled need it enabled by their administrator.
This dotfiles change does not modify either server.
The helper checks an explicitly unlocked Bitwarden context, then the desktop
credential manager's saved entry, then starts OAuth if needed. Successful OAuth
credentials are saved through Git Credential Manager's Secret Service backend.
The desktop profile provides the GNOME Keyring secrets user service; an existing
Secret Service provider can also be used. The keyring must be unlocked in the
desktop session (it may prompt for its own password).
Vault lookup does not automatically insert OAuth credentials into Bitwarden.
## Headless use
The helper uses terminal prompts, with GCM GUI prompts disabled. Enter the
appropriate GitHub/Gitea username and a personal access token when requested;
tokens need repository permissions appropriate to your operation. Headless does
not launch OAuth browser callbacks or a GUI. Accepted credentials are cached in
memory for one hour and are lost at cache expiry or reboot.
For unattended use, unlock the appropriate Bitwarden context in the process
environment or provide an explicit automation credential helper. The interactive
prompt is not a replacement for a CI credential source. No token is committed.
## Optional Bitwarden credentials
`git-vault` wraps the existing Bitwarden CLI with isolated per-vault app-data
directories. It configures only that context's expected server, and refuses to
switch it while logged into a different server. It does not change the general
`bw` CLI or `dot secrets` account.
| Remote | Vault context / server | Environment containing its unlocked session |
|---|---|---|
| gitea.etvamerica.com | work / https://vault.etvamerica.com | BW_SESSION_WORK |
| gitea.godemperordoge.org | personal / https://vault.godemperordoge.org | BW_SESSION_PERSONAL |
| github.com | work for full-work, personal otherwise | Corresponding variable above |
Log in once to the selected context and capture the unlock session without
printing it. For example, for the personal SSO vault:
```sh
git-vault personal login --sso
export BW_SESSION_PERSONAL="$(git-vault personal unlock --raw)"
git-vault personal sync
```
For the work vault, use `git-vault work login` with your normal login method and
`export BW_SESSION_WORK="$(git-vault work unlock --raw)"`. On headless systems,
`git-vault personal login --apikey` is an option where supported by your vault;
enter the client credentials at its prompts rather than in command arguments.
Existing SSO/vault enrollment and master-password requirements still apply.
Create a **Login** item named exactly `Git: <host>` (for example,
`Git: github.com`) with:
- URI `https://<host>`
- Your Git username
- A repository-scoped personal access token in the password field
The helper uses only that named item and an exact HTTPS hostname match, not your
ordinary website-password item. Username hints must also match. Deleted or
ambiguous matching items are ignored, and credentials from the wrong vault server
are never returned. Vault sessions are inherited from the calling process; start
`sourcegit` from the unlocked terminal if you want it to use that session. The
normal desktop browser/keyring flow works without these session variables.
The helper reads unlocked vault entries but does not modify them. If a stored PAT
has been revoked, update/remove that item in Bitwarden before retrying. Use
`unset BW_SESSION_PERSONAL BW_SESSION_WORK` when finished with the shell session.
Do not run credential lookup with tracing or print its protocol output: it
contains a password/token intended only for Git.
## Migration and checks
`dot secrets render` no longer writes `~/.git-credentials`, and Git no longer
configures `credential.helper=store`. An existing file is left untouched and is
not read by the new helper; remove/archive it yourself after checking whether
other tooling still needs it. Existing machine-local repository overrides can
still replace the generated helper.
Apply with `git pull` and `dot switch` on the target machine. Check the selected
email with `git config user.email`. Run `bash tests/profiles.sh` to evaluate the
profile boundaries. The Go helper has offline fixture tests for host/vault
isolation, locked/wrong vaults, ambiguous entries, desktop OAuth fallback,
headless browser avoidance and credential persistence routing.
References:
- https://github.com/hickford/git-credential-oauth
- https://github.com/git-ecosystem/git-credential-manager/blob/main/docs/credstores.md
- https://bitwarden.com/help/cli/
+43 -4
View File
@@ -1,15 +1,54 @@
{ ... }:
{ config, lib, pkgs, ... }:
let
gui = config.dotfiles.gui;
vault = if config.dotfiles.work then "work" else "personal";
mode = if gui then "desktop" else "headless";
credentialHelper = pkgs.buildGoModule {
pname = "git-credential-dotfiles";
version = "1.0.0";
src = ../tools/git-credential-dotfiles;
vendorHash = null;
nativeBuildInputs = [ pkgs.makeWrapper ];
postInstall = ''
wrapProgram $out/bin/git-credential-dotfiles \
--prefix PATH : ${lib.makeBinPath ([ pkgs.git-credential-manager pkgs.bitwarden-cli ] ++ lib.optional gui pkgs.git-credential-oauth)}
'';
};
vaultCLI = pkgs.writeShellScriptBin "git-vault" ''
exec ${credentialHelper}/bin/git-credential-dotfiles vault "$@"
'';
in
{
# Provide a Secret Service on desktops without relying on distro-specific
# keyring packages. It is a user service and does not alter system PAM/SSH.
services.gnome-keyring = lib.mkIf gui {
enable = true;
components = [ "secrets" ];
};
home.packages = [ credentialHelper vaultCLI pkgs.git-credential-manager ]
++ lib.optionals gui [ pkgs.sourcegit pkgs.git-credential-oauth pkgs.libsecret ];
programs.git = {
enable = true;
settings = {
user = {
name = "Ziad Arafat";
email = "anonymous0programmer@gmail.com";
email = if config.dotfiles.work then "ziad.arafat@etvamerica.com"
else "anonymous0programmer@gmail.com";
};
init.defaultBranch = "main";
# Tokens for HTTPS remotes land in ~/.git-credentials via `dot secrets pull`.
credential.helper = "store";
credential = {
# Empty helper clears inherited system helpers, including plaintext storage.
helper = [ "" "${credentialHelper}/bin/git-credential-dotfiles --mode=${mode} --vault=${vault}" ];
credentialStore = if gui then "secretservice" else "cache";
cacheOptions = "--timeout=3600";
guiPrompt = gui;
"https://github.com" = {
provider = if gui then "generic" else "github";
gitHubAuthModes = if gui then "browser" else "pat";
};
"https://gitea.godemperordoge.org".provider = "generic";
"https://gitea.etvamerica.com".provider = "generic";
};
http = {
lowSpeedLimit = 1000;
lowSpeedTime = 60;
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env bash
# Read-only local probes. No installer, package downloads, sudo, or repairs.
doctor_nix_root() { printf '%s\n' /nix; }
doctor_nix_home() { printf '%s\n' "$HOME"; }
doctor_timeout() { if have timeout; then timeout 10 "$@"; else "$@"; fi; }
doctor_nix() {
local root home daemon=0 cli=0 flakes="" version=""
root="$(doctor_nix_root)"; home="$(doctor_nix_home)"
if ! source_nix; then
if [ -d "$root" ] || [ -L "$home/.nix-profile" ]; then
warn "Nix installation incomplete or missing from PATH — inspect $root/receipt.json and the profile scripts; finish/repair the existing installer before dot switch"
else
warn "Nix not installed — run dot nix"
fi
return 0
fi
if ! version="$(doctor_timeout nix --version 2>/dev/null)"; then
warn "Nix executable cannot start — check for a broken executable/link or interrupted installation; repair the existing Nix installation"
return 0
fi
ok "Nix executable starts"
if [ -d "$root/store" ] && [ -r "$root/store" ] && [ -x "$root/store" ]; then
ok "Nix store directory accessible"
else
warn "Nix store directory missing/inaccessible — finish the installer and check the $root mount (SteamOS offload/bind mount included)"
fi
if [ -L "$home/.nix-profile" ] && [ ! -e "$home/.nix-profile" ]; then
warn "Nix user profile link is broken — inspect its target; restore the Nix/profile installation before dot switch"
fi
if [ -L "$root/var/nix/profiles/default" ] && [ ! -e "$root/var/nix/profiles/default" ]; then
warn "Nix default profile link is broken — installation may have stopped partway; repair the existing installation"
fi
if [[ "${NIX_REMOTE:-}" == daemon* ]] || [ -S "$root/var/nix/daemon-socket/socket" ]; then daemon=1; fi
if has_systemd && systemctl cat nix-daemon.service >/dev/null 2>&1; then daemon=1; fi
# Force only this read-only store probe so disabled nix-command does not hide
# a separate daemon/database failure. Actual feature checks below are unforced.
if doctor_timeout nix --extra-experimental-features nix-command store ping --json >/dev/null 2>&1; then
ok "Nix store/database connection"
elif [ "$daemon" = 1 ]; then
warn "Nix daemon/store connection failed — inspect nix-daemon.socket and nix-daemon.service; finish/repair the installer (do not chown a daemon-managed store)"
else
warn "Nix local store/database connection failed — check the mount and single-user ownership; finish/repair the installation before dot switch"
fi
if [ "$daemon" = 0 ] && [ -d "$root/store" ] && [ ! -w "$root/store" ]; then
warn "Single-user Nix store is not writable — confirm this is really a single-user install and repair its ownership/mount; never chown a daemon-managed store"
fi
if doctor_timeout nix eval --expr 1 >/dev/null 2>&1; then
cli=1; ok "Nix nix-command feature enabled"
else
warn "Nix nix-command feature disabled or CLI configuration invalid — enable experimental-features = nix-command flakes in ~/.config/nix/nix.conf; check NIX_CONFIG overrides"
fi
if have nix-instantiate; then
flakes="$(doctor_timeout nix-instantiate --eval --expr 'builtins ? getFlake' 2>/dev/null)" || flakes=""
elif [ "$cli" = 1 ]; then
flakes="$(doctor_timeout nix eval --expr 'builtins ? getFlake' 2>/dev/null)" || flakes=""
fi
if [ "$flakes" = true ]; then
ok "Nix flakes feature enabled"
else
warn "Nix flakes feature disabled or unavailable — run dot nix to enable nix-command + flakes; if overridden, fix NIX_CONFIG/system config and retry dot doctor"
fi
if [ -f "$DOTFILES_DIR/flake.nix" ] && [ -s "$DOTFILES_DIR/flake.lock" ]; then
if have jq && ! jq empty "$DOTFILES_DIR/flake.lock" >/dev/null 2>&1; then
warn "Dotfiles flake.lock is invalid JSON — resolve checkout/merge damage before dot switch"
else
ok "Dotfiles flake files present"
fi
else
warn "Dotfiles flake.nix or flake.lock missing — restore a complete dotfiles checkout before dot switch"
fi
return 0
}
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
source scripts/doctor-nix.sh
fixture="$(mktemp -d)"
trap 'rm -rf "$fixture"' EXIT
mkdir -p "$fixture/nix/store" "$fixture/home" "$fixture/repo"
printf '{}\n' >"$fixture/repo/flake.lock"
touch "$fixture/repo/flake.nix"
DOTFILES_DIR="$fixture/repo"
doctor_nix_root() { echo "$fixture/nix"; }
doctor_nix_home() { echo "$fixture/home"; }
doctor_timeout() { "$@"; }
ok() { printf 'OK %s\n' "$*"; }
warn() { printf 'WARN %s\n' "$*"; }
have() { [ "$1" = nix-instantiate ] || command -v "$1" >/dev/null; }
source_nix() { [ "${missing:-0}" = 0 ]; }
has_systemd() { [ "${fixture_daemon:-0}" = 1 ]; }
systemctl() { return 0; }
nix() {
case "$*" in
--version) [ "${broken:-0}" = 0 ] && echo 'nix (Nix) 2.35.3';;
'--extra-experimental-features nix-command store ping --json') [ "${store_broken:-0}" = 0 ];;
'eval --expr 1') [ "${cli_disabled:-0}" = 0 ];;
*) return 1;;
esac
}
nix-instantiate() { if [ "${flakes_disabled:-0}" = 1 ]; then echo false; else echo true; fi; }
result="$(doctor_nix)"
! grep -q WARN <<<"$result"
grep -q 'Nix store/database connection' <<<"$result"
missing=1 result="$(doctor_nix)"
grep -q 'installation incomplete' <<<"$result"
unset missing
broken=1 result="$(doctor_nix)"
grep -q 'executable cannot start' <<<"$result"
unset broken
store_broken=1 fixture_daemon=1 result="$(doctor_nix)"
grep -q 'daemon/store connection failed' <<<"$result"
unset store_broken fixture_daemon
cli_disabled=1 flakes_disabled=1 result="$(doctor_nix)"
grep -q 'nix-command feature disabled' <<<"$result"
grep -q 'flakes feature disabled' <<<"$result"
unset cli_disabled flakes_disabled
ln -s "$fixture/absent-generation" "$fixture/home/.nix-profile"
result="$(doctor_nix)"
grep -q 'user profile link is broken' <<<"$result"
printf 'not json\n' >"$fixture/repo/flake.lock"
result="$(doctor_nix)"
grep -q 'flake.lock is invalid JSON' <<<"$result"
echo 'Nix doctor fixture checks passed'
+12 -3
View File
@@ -10,14 +10,21 @@ for profile in full full-work headless; do
vesktop = builtins.hasAttr ".var/app/dev.vencord.Vesktop/config/vesktop/settings.json" c.home.file;
claudeSettings = builtins.hasAttr ".claude/settings.json" c.home.file;
claudeInstructions = builtins.hasAttr ".claude/CLAUDE.md" c.home.file;
gitEmail = c.programs.git.settings.user.email;
credentialStore = c.programs.git.settings.credential.credentialStore;
githubAuth = c.programs.git.settings.credential."https://github.com".gitHubAuthModes;
guiPrompt = c.programs.git.settings.credential.guiPrompt;
}' | jq -e --arg p "$profile" '
if $p == "full" then
(.packages | index("codex") != null and index("defguard-client") != null and index("build-sound-theme") != null) and
(.activities.activities | keys == ["Personal", "Work"]) and .theme == "portal2" and .vesktop and .claudeSettings and .claudeInstructions
(.activities.activities | keys == ["Personal", "Work"]) and .theme == "portal2" and .vesktop and .claudeSettings and .claudeInstructions and
(.packages | index("sourcegit") != null) and .gitEmail == "anonymous0programmer@gmail.com" and .credentialStore == "secretservice" and .guiPrompt and .githubAuth == "browser"
elif $p == "full-work" then
(.packages | index("codex") == null and index("defguard-client") == null and index("build-sound-theme") == null and index("notification-sounds") != null) and
(.activities.activities | keys == ["Work"]) and .activities.workOnly and .theme == "ocean" and (.vesktop | not) and (.claudeSettings | not) and (.claudeInstructions | not)
else (.packages | index("codex") == null) and .activities == null and .claudeSettings and .claudeInstructions end
(.activities.activities | keys == ["Work"]) and .activities.workOnly and .theme == "ocean" and (.vesktop | not) and (.claudeSettings | not) and (.claudeInstructions | not) and
(.packages | index("sourcegit") != null) and .gitEmail == "ziad.arafat@etvamerica.com" and .credentialStore == "secretservice" and .guiPrompt
else (.packages | index("codex") == null and index("sourcegit") == null) and .activities == null and .claudeSettings and .claudeInstructions and
.credentialStore == "cache" and (.guiPrompt | not) and .githubAuth == "pat" end
'
done
# Exercise the same manifest selector used by apps and doctor in an isolated HOME.
@@ -32,10 +39,12 @@ rg -q '^com.microsoft.Edge$' <<<"$work_apps"
# Work rendering must neither overwrite an existing Claude configuration nor
# create one on a fresh machine; other rendered agent configuration still works.
printf 'GITHUB_ACCESS_TOKEN=fixture-not-a-real-token\n' >"$SECRETS_ENV"
printf 'fixture: keep existing private data\n' >"$HOME/.git-credentials"
printf '{"fixture":"preserve"}\n' >"$HOME/.claude.json"
secrets_render
jq -e '.fixture == "preserve" and (has("mcpServers") | not)' "$HOME/.claude.json"
[ -s "$HOME/.pi/agent/mcp.json" ]
grep -qx 'fixture: keep existing private data' "$HOME/.git-credentials"
mv "$HOME/.claude.json" "$HOME/.claude.json.saved"
secrets_render
[ ! -e "$HOME/.claude.json" ]
+3
View File
@@ -0,0 +1,3 @@
module dotfiles/git-credential-dotfiles
go 1.25
+279
View File
@@ -0,0 +1,279 @@
// Git's credential protocol is the only output path that can carry a credential.
// Backend output stays in memory; Bitwarden is queried only with an unlocked,
// host-selected session. No credentials are written to dotfiles or command args.
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
type fields map[string]string
type runner func(string, []string, []byte, []string, bool) ([]byte, error)
func run(name string, args []string, input []byte, env []string, interactive bool) ([]byte, error) {
ctx := context.Background()
cancel := func() {}
if !interactive {
ctx, cancel = context.WithTimeout(ctx, 20*time.Second)
}
defer cancel()
cmd := exec.CommandContext(ctx, name, args...)
cmd.Stdin = bytes.NewReader(input)
cmd.Env = env
if interactive {
cmd.Stderr = os.Stderr
}
return cmd.Output()
}
func parse(b []byte) fields {
f := fields{}
scan := bufio.NewScanner(bytes.NewReader(b))
for scan.Scan() {
line := scan.Text()
if line == "" {
break
}
k, v, ok := strings.Cut(line, "=")
if ok {
f[k] = v
}
}
return f
}
func encode(f fields) []byte {
var b strings.Builder
for _, k := range []string{"protocol", "host", "path", "username", "password", "password_expiry_utc", "oauth_refresh_token"} {
if v := f[k]; v != "" && !strings.ContainsAny(v, "\r\n") {
fmt.Fprintf(&b, "%s=%s\n", k, v)
}
}
b.WriteByte('\n')
return []byte(b.String())
}
func complete(f fields) bool { return f["username"] != "" && f["password"] != "" }
func originHost(f fields) string {
if f["protocol"] != "https" {
return ""
}
u, e := url.Parse("https://" + f["host"])
if e != nil || u.User != nil || u.Path != "" || u.Port() != "" && u.Port() != "443" {
return ""
}
return strings.ToLower(u.Hostname())
}
func selectVault(host, profile string) string {
switch host {
case "gitea.etvamerica.com":
return "work"
case "gitea.godemperordoge.org":
return "personal"
case "github.com":
return profile
}
return ""
}
func vaultURL(v string) string {
if v == "work" {
return "https://vault.etvamerica.com"
}
return "https://vault.godemperordoge.org"
}
func appData(v string) string {
base := os.Getenv("XDG_CONFIG_HOME")
if base == "" {
base = filepath.Join(os.Getenv("HOME"), ".config")
}
return filepath.Join(base, "dotfiles", "bitwarden-git", v)
}
func envWith(extra map[string]string) []string {
env := []string{}
for _, v := range os.Environ() {
k, _, _ := strings.Cut(v, "=")
if _, ok := extra[k]; !ok {
env = append(env, v)
}
}
for k, v := range extra {
env = append(env, k+"="+v)
}
return env
}
type vaultItem struct {
Name string `json:"name"`
Type int `json:"type"`
Deleted string `json:"deletedDate"`
Login struct {
Username, Password string
URIs []struct {
URI string `json:"uri"`
} `json:"uris"`
} `json:"login"`
}
func itemCredential(data []byte, host, user string) fields {
var items []vaultItem
if json.Unmarshal(data, &items) != nil {
return nil
}
var found fields
for _, item := range items {
if item.Type != 1 || item.Deleted != "" || item.Name != "Git: "+host || item.Login.Username == "" || item.Login.Password == "" || strings.ContainsAny(item.Login.Username+item.Login.Password, "\r\n") {
continue
}
if user != "" && user != item.Login.Username {
continue
}
match := false
for _, uri := range item.Login.URIs {
u, e := url.Parse(uri.URI)
if e == nil && u.Scheme == "https" && strings.EqualFold(u.Host, host) && u.User == nil {
match = true
}
}
if match {
if found != nil {
return nil
}
found = fields{"username": item.Login.Username, "password": item.Login.Password}
}
}
return found
}
func fromVault(f fields, profile string, exec runner) fields {
host := originHost(f)
v := selectVault(host, profile)
if v == "" {
return nil
}
session := os.Getenv("BW_SESSION_" + strings.ToUpper(v))
if session == "" {
return nil
}
env := envWith(map[string]string{"BITWARDENCLI_APPDATA_DIR": appData(v), "BW_SESSION": session})
status, e := exec("bw", []string{"status"}, nil, env, false)
if e != nil {
return nil
}
var s struct {
Status string
ServerURL string `json:"serverUrl"`
}
if json.Unmarshal(status, &s) != nil || s.Status != "unlocked" || strings.TrimRight(s.ServerURL, "/") != vaultURL(v) {
return nil
}
data, e := exec("bw", []string{"list", "items", "--url", "https://" + host, "--search", "Git: " + host}, nil, env, false)
if e != nil {
return nil
}
return itemCredential(data, host, f["username"])
}
func handle(mode, profile, op string, input []byte, exec runner) []byte {
if op != "get" && op != "store" && op != "erase" {
return nil
}
f := parse(input)
// Do not send credentials to cleartext URLs or run OAuth discovery for unknown hosts.
host := originHost(f)
if selectVault(host, profile) == "" {
return nil
}
if op == "get" {
if v := fromVault(f, profile, exec); complete(v) {
return encode(v)
}
if mode == "desktop" {
b, _ := exec("git-credential-manager", []string{"get"}, input, envWith(map[string]string{"GCM_INTERACTIVE": "false"}), false)
if complete(parse(b)) {
return b
}
b, e := exec("git-credential-oauth", []string{"get"}, input, os.Environ(), true)
if e == nil && complete(parse(b)) {
return b
}
return nil
}
b, e := exec("git-credential-manager", []string{"get"}, input, envWith(map[string]string{"GCM_GUI_PROMPT": "false"}), true)
if e == nil && complete(parse(b)) {
return b
}
return nil
}
// Git calls approve/store after successful authentication. Persist via GCM's
// Secret Service backend on desktops or memory-only cache on headless hosts.
if _, err := exec("git-credential-manager", []string{op}, input, os.Environ(), false); err != nil {
// Never echo backend errors, which may contain credential protocol data.
fmt.Fprintln(os.Stderr, "Git credential manager could not "+op+" the credential; check the keyring/cache configuration.")
}
return nil
}
func vaultCLI(args []string) {
if len(args) < 2 || (args[0] != "personal" && args[0] != "work") {
fmt.Fprintln(os.Stderr, "Usage: git-vault personal|work <bw command> [args...]")
os.Exit(2)
}
v := args[0]
env := envWith(map[string]string{"BITWARDENCLI_APPDATA_DIR": appData(v), "BW_SESSION": os.Getenv("BW_SESSION_" + strings.ToUpper(v))})
status, e := run("bw", []string{"status"}, nil, env, false)
if e != nil {
fmt.Fprintln(os.Stderr, "Unable to read Bitwarden login state")
os.Exit(1)
}
var s struct {
Status string
ServerURL string `json:"serverUrl"`
}
if json.Unmarshal(status, &s) != nil {
os.Exit(1)
}
if strings.TrimRight(s.ServerURL, "/") != vaultURL(v) {
if s.Status != "unauthenticated" {
fmt.Fprintln(os.Stderr, "This isolated vault is logged into another server; log out of that context first.")
os.Exit(1)
}
if _, e := run("bw", []string{"config", "server", vaultURL(v)}, nil, env, false); e != nil {
fmt.Fprintln(os.Stderr, "Unable to configure the selected vault server")
os.Exit(1)
}
}
cmd := exec.Command("bw", args[1:]...)
cmd.Env = env
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if e := cmd.Run(); e != nil {
if e, ok := e.(*exec.ExitError); ok {
os.Exit(e.ExitCode())
}
os.Exit(1)
}
}
func main() {
if len(os.Args) > 1 && os.Args[1] == "vault" {
vaultCLI(os.Args[2:])
return
}
mode := flag.String("mode", "headless", "desktop or headless")
profile := flag.String("vault", "personal", "personal or work GitHub vault")
flag.Parse()
if flag.NArg() != 1 || (*mode != "desktop" && *mode != "headless") || (*profile != "personal" && *profile != "work") {
os.Exit(2)
}
input, e := io.ReadAll(io.LimitReader(os.Stdin, 1<<20))
if e != nil {
os.Exit(1)
}
os.Stdout.Write(handle(*mode, *profile, flag.Arg(0), input, run))
}
+133
View File
@@ -0,0 +1,133 @@
package main
import (
"bytes"
"encoding/json"
"errors"
"strings"
"testing"
)
func TestVaultIsolationAndExactURI(t *testing.T) {
cases := []struct{ host, profile, want string }{{"github.com", "work", "work"}, {"github.com", "personal", "personal"}, {"gitea.etvamerica.com", "personal", "work"}, {"gitea.godemperordoge.org", "work", "personal"}, {"github.com.evil.invalid", "work", ""}}
for _, c := range cases {
if got := selectVault(c.host, c.profile); got != c.want {
t.Fatalf("vault for %s: %s", c.host, got)
}
}
for _, bad := range []string{"http", "ssh"} {
if originHost(fields{"protocol": bad, "host": "github.com"}) != "" {
t.Fatal("non-HTTPS origin accepted")
}
}
for _, host := range []string{"person@github.com", "github.com/path", "github.com:8080"} {
if originHost(fields{"protocol": "https", "host": host}) != "" {
t.Fatal("unsafe origin accepted")
}
}
item := func(uri string) map[string]any {
return map[string]any{"type": 1, "name": "Git: github.com", "login": map[string]any{"username": "fixture-user", "password": "fixture-token", "uris": []map[string]string{{"uri": uri}}}}
}
data, _ := json.Marshal([]any{item("https://github.com.evil.invalid")})
if complete(itemCredential(data, "github.com", "")) {
t.Fatal("credential crossed origin")
}
data, _ = json.Marshal([]any{item("https://github.com")})
if !complete(itemCredential(data, "github.com", "fixture-user")) {
t.Fatal("exact matching item rejected")
}
if complete(itemCredential(data, "github.com", "different-user")) {
t.Fatal("username mismatch accepted")
}
data, _ = json.Marshal([]any{item("https://github.com"), item("https://github.com")})
if complete(itemCredential(data, "github.com", "")) {
t.Fatal("ambiguous items accepted")
}
}
func TestHeadlessNeverStartsOAuth(t *testing.T) {
t.Setenv("BW_SESSION_PERSONAL", "")
t.Setenv("BW_SESSION_WORK", "")
called := []string{}
fake := func(name string, args []string, in []byte, env []string, interactive bool) ([]byte, error) {
called = append(called, name)
if name != "git-credential-manager" {
t.Fatal("headless started browser backend")
}
if !strings.Contains(strings.Join(env, "\n"), "GCM_GUI_PROMPT=false") {
t.Fatal("GUI not disabled")
}
return []byte("username=fixture\npassword=fixture-token\n\n"), nil
}
got := handle("headless", "personal", "get", []byte("protocol=https\nhost=github.com\n\n"), fake)
if !complete(parse(got)) || len(called) != 1 {
t.Fatal("headless manager did not return credential")
}
}
func TestDesktopCacheMissFallsBackToBrowserOAuth(t *testing.T) {
t.Setenv("BW_SESSION_PERSONAL", "")
calls := []string{}
fake := func(name string, args []string, in []byte, env []string, interactive bool) ([]byte, error) {
calls = append(calls, name)
if name == "git-credential-manager" {
if interactive {
t.Fatal("store lookup would prompt")
}
return nil, errors.New("cache miss")
}
return []byte("username=fixture\npassword=fixture-oauth\n\n"), nil
}
out := handle("desktop", "personal", "get", []byte("protocol=https\nhost=gitea.godemperordoge.org\n\n"), fake)
if !complete(parse(out)) || strings.Join(calls, ",") != "git-credential-manager,git-credential-oauth" {
t.Fatal("desktop fallback order incorrect")
}
}
func TestUnlockedVaultUsesSessionOnlyInEnvironment(t *testing.T) {
t.Setenv("BW_SESSION_WORK", "fixture-session")
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
fake := func(name string, args []string, in []byte, env []string, interactive bool) ([]byte, error) {
if name != "bw" || interactive {
t.Fatal("unexpected vault backend")
}
if strings.Contains(strings.Join(args, " "), "fixture-session") {
t.Fatal("session in process arguments")
}
if !strings.Contains(strings.Join(env, "\n"), "BW_SESSION=fixture-session") {
t.Fatal("session missing from child environment")
}
if args[0] == "status" {
return []byte(`{"status":"unlocked","serverUrl":"https://vault.etvamerica.com"}`), nil
}
return []byte(`[{"type":1,"name":"Git: gitea.etvamerica.com","login":{"username":"fixture","password":"fixture-token","uris":[{"uri":"https://gitea.etvamerica.com"}]}}]`), nil
}
got := handle("desktop", "personal", "get", []byte("protocol=https\nhost=gitea.etvamerica.com\n\n"), fake)
if !complete(parse(got)) {
t.Fatal("unlocked work vault was not used")
}
wrong := func(name string, args []string, in []byte, env []string, interactive bool) ([]byte, error) {
return []byte(`{"status":"unlocked","serverUrl":"https://vault.godemperordoge.org"}`), nil
}
if complete(fromVault(fields{"protocol": "https", "host": "gitea.etvamerica.com"}, "personal", wrong)) {
t.Fatal("wrong vault server accepted")
}
}
func TestStoreAndEraseNeverWriteToVault(t *testing.T) {
for _, op := range []string{"store", "erase"} {
calls := 0
fake := func(name string, args []string, in []byte, env []string, interactive bool) ([]byte, error) {
calls++
if name != "git-credential-manager" || args[0] != op {
t.Fatal("unexpected persistence target")
}
return nil, nil
}
if len(handle("headless", "personal", op, []byte("protocol=https\nhost=github.com\n\n"), fake)) != 0 || calls != 1 {
t.Fatal("unexpected persistence response")
}
}
}
func TestNoCredentialProtocolLineInjection(t *testing.T) {
out := encode(fields{"username": "fixture", "password": "fixture\npassword=injected"})
if bytes.Contains(out, []byte("password=")) {
t.Fatal("multiline password escaped into protocol")
}
}