Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

Sanitize Git remote errors before credential redaction (#36205)

Jinjing0ded87821d5b
diff --git a/src/renderer/src/lib/source-control-remote-error.test.ts b/src/renderer/src/lib/source-control-remote-error.test.ts
index d363ef3697f..82ff4c9820f 100644
--- a/src/renderer/src/lib/source-control-remote-error.test.ts
+++ b/src/renderer/src/lib/source-control-remote-error.test.ts
@@ -2,7 +2,10 @@ import { afterEach, describe, expect, it } from 'vitest'
import { i18n } from '@/i18n/i18n'
import es from '@/i18n/locales/es.json'
-import { resolveRemoteOperationErrorMessage } from './source-control-remote-error'
+import {
+ isNonFastForwardRemoteError,
+ resolveRemoteOperationErrorMessage
+} from './source-control-remote-error'
const originalLanguage = i18n.language
@@ -11,6 +14,17 @@ afterEach(async () => {
})
describe('source-control remote error formatting', () => {
+ it('recognizes split colored stale lease markers from remote hosts', () => {
+ const error = new Error(
+ " ! [rejected] main -> main (stale\x1b[31m info\x1b[m)\nerror: failed to push some refs to 'origin'"
+ )
+
+ expect(resolveRemoteOperationErrorMessage(error, { isForcePush: true })).toBe(
+ 'Force push rejected — remote changed since last fetch. Fetch first, then try again.'
+ )
+ expect(isNonFastForwardRemoteError(error)).toBe(true)
+ })
+
it('prefers fatal detail over an earlier remote detail for publish failures', () => {
const error = new Error('remote: protected branch\r\nfatal: Authentication failed\r\n')
@@ -19,6 +33,58 @@ describe('source-control remote error formatting', () => {
)
})
+ it.each(['fatal', 'remote'])(
+ 'redacts ANSI-bearing credentials in %s details from older remote hosts',
+ (prefix) => {
+ const error = new Error(
+ `git.push failed:\n${prefix}: Access denied to https://user:sec\x1b[1 [email protected]/repo.git`
+ )
+
+ expect(resolveRemoteOperationErrorMessage(error, { isPush: true })).toBe(
+ 'Push failed. Access denied to https://example.com/repo.git. Check your remote access and try again.'
+ )
+ }
+ )
+
+ it.each([
+ [{ isFetch: true }, 'Fetch failed. '],
+ [{ isFastForward: true }, 'Fast-forward failed. '],
+ [{ isRebase: true }, 'Rebase failed. '],
+ [{}, '']
+ ])('redacts ANSI-bearing credentials in fallback details for %j', (options, prefix) => {
+ const error = new Error('Access denied to https://user:sec\x1b[1 [email protected]/repo.git')
+
+ expect(resolveRemoteOperationErrorMessage(error, options)).toBe(
+ `${prefix}Access denied to https://example.com/repo.git`
+ )
+ expect(error.message).toContain('user:sec\x1b[1 qret@')
+ })
+
+ it.each([
+ [{ publish: true }, 'Publish Branch'],
+ [{ isSync: true }, 'Sync'],
+ [{ isForcePush: true }, 'Force Push'],
+ [{ isPush: true }, 'Push']
+ ])('sanitizes and classifies older-host submodule errors for %j', (options, operation) => {
+ const error = new Error(
+ "Unable to push sub\x1b[1 qmodule 'https://user:sec\x1b[1 [email protected]/repo.git'\n" +
+ ' ! [rejected] main -> main (fetch\x1b[1 q first)'
+ )
+
+ expect(resolveRemoteOperationErrorMessage(error, options)).toBe(
+ `${operation} failed. Submodule 'https://example.com/repo.git' has remote changes. Pull inside the submodule, then try again.`
+ )
+ expect(isNonFastForwardRemoteError(error)).toBe(true)
+ expect(
+ resolveRemoteOperationErrorMessage(
+ new Error("Unable to push submodule 'https://user:sec\x1b[1 [email protected]/repo.git'"),
+ options
+ )
+ ).toBe(
+ `${operation} failed. Submodule 'https://example.com/repo.git' could not be pushed. Resolve the submodule push error, then try again.`
+ )
+ })
+
it('maps pre-push hook failures to a hook-specific message instead of remote access guidance', () => {
const error = new Error(
"git push failed: Command failed: git push origin main\nerror: failed to push some refs to 'origin'\nhusky - pre-push hook exited with code 1\neslint found 2 errors"
diff --git a/src/renderer/src/lib/source-control-remote-error.ts b/src/renderer/src/lib/source-control-remote-error.ts
index 7f75daa2f8d..781a3e956ec 100644
--- a/src/renderer/src/lib/source-control-remote-error.ts
+++ b/src/renderer/src/lib/source-control-remote-error.ts
@@ -1,4 +1,5 @@
import { translate } from '@/i18n/i18n'
+import { stripAnsiEscapeSequences } from '../../../shared/ansi-escape-sequences'
import {
GIT_AUTHENTICATION_FAILED_MESSAGE,
formatSubmodulePushFailureDetail,
@@ -36,7 +37,7 @@ function truncateDetail(detail: string): string {
function extractPublishFailureDetail(message: string): string | null {
let remoteDetail: string | null = null
- for (const rawLine of iterateRemoteErrorLines(message)) {
+ for (const rawLine of iterateRemoteErrorLines(stripAnsiEscapeSequences(message))) {
const line = rawLine.trim()
if (!line) {
continue
@@ -87,8 +88,9 @@ function isNonFastForwardRemoteError(error: unknown): boolean {
if (!(error instanceof Error)) {
return false
}
+ const message = stripAnsiEscapeSequences(error.message)
return (
- /non-fast-forward|fetch first|updates were rejected|stale info/i.test(error.message) ||
+ /non-fast-forward|fetch first|updates were rejected|stale info/i.test(message) ||
formatSubmodulePushFailureDetail(error.message)?.includes('has remote changes') === true
)
}
@@ -151,6 +153,8 @@ export function resolveRemoteOperationErrorMessage(
return translate('sourceControl.remoteError.operationFailed', 'Remote operation failed')
}
+ const message = stripCredentialsFromMessage(stripAnsiEscapeSequences(error.message))
+
const pullLikeOperation: PullLikeOperation = options?.isRebase
? 'rebase'
: options?.isSync
@@ -159,37 +163,37 @@ export function resolveRemoteOperationErrorMessage(
? 'fastForward'
: 'pull'
- if (UNCONCLUDED_MERGE_ERROR_PATTERN.test(error.message)) {
+ if (UNCONCLUDED_MERGE_ERROR_PATTERN.test(message)) {
return unconcludedMergeMessage(pullLikeOperation)
}
- if (FRESH_MERGE_CONFLICT_ERROR_PATTERN.test(error.message)) {
+ if (FRESH_MERGE_CONFLICT_ERROR_PATTERN.test(message)) {
return mergeConflictsMessage(pullLikeOperation)
}
if (options?.publish) {
- const submoduleMessage = resolveSubmodulePushFailureMessage(error.message, 'publish')
+ const submoduleMessage = resolveSubmodulePushFailureMessage(message, 'publish')
if (submoduleMessage) {
return submoduleMessage
}
}
if (options?.isSync) {
- const submoduleMessage = resolveSubmodulePushFailureMessage(error.message, 'sync')
+ const submoduleMessage = resolveSubmodulePushFailureMessage(message, 'sync')
if (submoduleMessage) {
return submoduleMessage
}
}
if (options?.isForcePush) {
- const submoduleMessage = resolveSubmodulePushFailureMessage(error.message, 'forcePush')
+ const submoduleMessage = resolveSubmodulePushFailureMessage(message, 'forcePush')
if (submoduleMessage) {
return submoduleMessage
}
}
if (options?.isPush) {
- const submoduleMessage = resolveSubmodulePushFailureMessage(error.message, 'push')
+ const submoduleMessage = resolveSubmodulePushFailureMessage(message, 'push')
if (submoduleMessage) {
return submoduleMessage
}
@@ -197,7 +201,7 @@ export function resolveRemoteOperationErrorMessage(
const isPushLikeOperation =
options?.isPush || options?.isForcePush || options?.publish || options?.isSyncPushStage
- if (isPushLikeOperation && isPushHookFailure(error.message)) {
+ if (isPushLikeOperation && isPushHookFailure(message)) {
const operation: PushLikeOperation = options?.publish
? 'publish'
: options?.isSyncPushStage
@@ -205,14 +209,11 @@ export function resolveRemoteOperationErrorMessage(
: options?.isForcePush
? 'forcePush'
: 'push'
- return pushHookBlockedMessage(operation, summarizePushFailure(error.message))
+ return pushHookBlockedMessage(operation, summarizePushFailure(message))
}
// Sync already pulled; NFF means the remote raced before its inner push. Choose sync wording before the shared push path, never misleading Pull first advice.
- if (
- options?.isSync &&
- /non-fast-forward|fetch first|updates were rejected/i.test(error.message)
- ) {
+ if (options?.isSync && /non-fast-forward|fetch first|updates were rejected/i.test(message)) {
return translate(
'sourceControl.remoteError.syncRemoteMoved',
'Sync failed — remote moved while syncing. Try again.'
@@ -222,7 +223,7 @@ export function resolveRemoteOperationErrorMessage(
// Lease rejection means remote changed since our snapshot; Pull first could reintroduce commits the explicit force-push meant to replace.
if (
options?.isForcePush &&
- /non-fast-forward|fetch first|updates were rejected|stale info/i.test(error.message)
+ /non-fast-forward|fetch first|updates were rejected|stale info/i.test(message)
) {
return translate(
'sourceControl.remoteError.forcePushRejected',
@@ -231,7 +232,7 @@ export function resolveRemoteOperationErrorMessage(
}
// Share rejected/NFF handling across publish and push for consistent actions.
- if (/non-fast-forward|fetch first|updates were rejected/i.test(error.message)) {
+ if (/non-fast-forward|fetch first|updates were rejected/i.test(message)) {
return translate(
'sourceControl.remoteError.pushRejected',
'Push rejected — remote has changes. Pull first, then try again.'
@@ -240,23 +241,21 @@ export function resolveRemoteOperationErrorMessage(
// Collapse overwritten-worktree refusal to one line instead of listing every affected path in the toast.
if (
- /local changes.*would be overwritten|Please commit your changes or stash them/i.test(
- error.message
- )
+ /local changes.*would be overwritten|Please commit your changes or stash them/i.test(message)
) {
return localChangesBlockedMessage(pullLikeOperation)
}
- if (/Pull would overwrite local changes/i.test(error.message)) {
+ if (/Pull would overwrite local changes/i.test(message)) {
return localChangesBlockedMessage(pullLikeOperation)
}
- if (/Pull would overwrite untracked files/i.test(error.message)) {
+ if (/Pull would overwrite untracked files/i.test(message)) {
return untrackedFilesBlockedMessage(pullLikeOperation)
}
// Why: the normalized auth message has no `fatal:` line and usually arrives IPC/RPC-wrapped.
- if (error.message.includes(GIT_AUTHENTICATION_FAILED_MESSAGE)) {
+ if (message.includes(GIT_AUTHENTICATION_FAILED_MESSAGE)) {
const operation: RemoteOperation = options?.publish
? 'publish'
: options?.isSync
@@ -283,21 +282,21 @@ export function resolveRemoteOperationErrorMessage(
if (options?.publish) {
// Unwrap publish git/IPC errors while preserving actionable fatal reasons.
- return remoteAccessFailedMessage('publish', extractPublishFailureDetail(error.message))
+ return remoteAccessFailedMessage('publish', extractPublishFailureDetail(message))
}
if (options?.isSync) {
// Sync reports its own failure, retaining push detail extraction for auth/protected-branch guidance.
- return remoteAccessFailedMessage('sync', extractPublishFailureDetail(error.message))
+ return remoteAccessFailedMessage('sync', extractPublishFailureDetail(message))
}
if (options?.isForcePush) {
- return remoteAccessFailedMessage('forcePush', extractPublishFailureDetail(error.message))
+ return remoteAccessFailedMessage('forcePush', extractPublishFailureDetail(message))
}
if (options?.isPush) {
// Prefer git fatal/remote detail over generic connection messages for auth/protected-branch failures.
- return remoteAccessFailedMessage('push', extractPublishFailureDetail(error.message))
+ return remoteAccessFailedMessage('push', extractPublishFailureDetail(message))
}
const verbatimOperation: RemoteOperation | null = options?.isFetch
@@ -308,13 +307,11 @@ export function resolveRemoteOperationErrorMessage(
? 'rebase'
: null
if (verbatimOperation) {
- const detail =
- extractPublishFailureDetail(error.message) ??
- truncateDetail(stripCredentialsFromMessage(error.message))
+ const detail = extractPublishFailureDetail(message) ?? truncateDetail(message)
return operationFailedWithDetail(verbatimOperation, detail)
}
- return error.message
+ return message
}
export { isNonFastForwardRemoteError }
diff --git a/src/shared/git-remote-error.test.ts b/src/shared/git-remote-error.test.ts
index 380cd05ae2c..dee968ccb41 100644
--- a/src/shared/git-remote-error.test.ts
+++ b/src/shared/git-remote-error.test.ts
@@ -5,14 +5,55 @@ import {
isNoUpstreamError,
normalizeGitErrorMessage,
pullArgsSpecifyReconciliation,
- runPullWithDivergenceFallback
+ runPullWithDivergenceFallback,
+ stripCredentialsFromMessage
} from './git-remote-error'
afterEach(() => {
vi.restoreAllMocks()
})
+describe('stripCredentialsFromMessage', () => {
+ it.each([
+ ['https://user:secret@host/repo', 'https://host/repo'],
+ ['custom+git.1://user:sec:ret@host/repo', 'custom+git.1://host/repo'],
+ ['SSH://git:secret@host/repo', 'SSH://host/repo'],
+ ['HTTPS://token@host/repo', 'HTTPS://host/repo'],
+ ['http://token@host/repo', 'http://host/repo'],
+ ['ssh://git@host/repo', 'ssh://git@host/repo'],
+ ['git@host:repo', 'git@host:repo'],
+ ['123://user:secret@host', '123://user:secret@host'],
+ ['123git+1://user:secret@host', '123git+1://host'],
+ ['https://user:secret/path@host', 'https://user:secret/path@host'],
+ ['https://user:secret\u00a0tail@host', 'https://user:secret\u00a0tail@host'],
+ ['https://user:secret@token@host', 'https://host'],
+ ['https://user:pa@ss:word@host/repo', 'https://host/repo'],
+ ['ssh://user:pa@ss:word@host/repo', 'ssh://host/repo'],
+ ['https://user:pa@ss:word@host?query=@other', 'https://host?query=@other'],
+ ['https://user:pa@ss:word@host#fragment=@other', 'https://host#fragment=@other'],
+ ['https://user:pa@ss:word@host/path@other', 'https://host/path@other'],
+ ['https://user:secret?query=@host', 'https://user:secret?query=@host'],
+ ['https://user:secret#fragment=@host', 'https://user:secret#fragment=@host'],
+ [
+ '界 https://user:secret@host/😀 ssh://git@host https://token@other',
+ '界 https://host/😀 ssh://git@host https://other'
+ ]
+ ])('preserves URL structure when redacting %s', (input, expected) => {
+ expect(stripCredentialsFromMessage(input)).toBe(expected)
+ })
+})
+
describe('normalizeGitErrorMessage', () => {
+ it('bounds redaction time when ANSI stripping joins a long scheme-like word', () => {
+ const error = new Error(
+ `remote: ${'\x1b[31ma\x1b[0m'.repeat(65_536)}\nfatal: denied https://user:secret@host/repo`
+ )
+ const start = performance.now()
+
+ expect(normalizeGitErrorMessage(error, 'push')).toBe('fatal: denied https://host/repo')
+ expect(performance.now() - start).toBeLessThan(2_000)
+ })
+
it.each([
' ! [rejected] main -> main (stale info)',
'\t!\t[rejected] main -> main (stale info)\t',
@@ -27,11 +68,37 @@ describe('normalizeGitErrorMessage', () => {
].join(newline)
expect(normalizeGitErrorMessage(new Error(output), 'push')).toBe(
- output.replace('user:secret@', '').replace('token@', '')
+ output
+ .replace('user:secret@', '')
+ .replace('token@', '')
+ .replaceAll('\x1b[31m', '')
+ .replaceAll('\x1b[m', '')
+ .replaceAll('\x1b[0m', '')
)
}
})
+ it.each([
+ 'https://user:sec\x1b[1 [email protected]/repo.git',
+ 'https://sec\x1b]8;;https://example.org\x07ret\x1b]8;;\[email protected]/repo.git'
+ ])('redacts ANSI-bearing URL userinfo in stale lease diagnostics: %s', (url) => {
+ const error = new Error(
+ [
+ `Command failed: git push ${url}`,
+ ' ! [rejected] main -> main (stale\x1b[31m info\x1b[m)',
+ "error: failed to push some refs to 'origin'"
+ ].join('\n')
+ )
+
+ expect(normalizeGitErrorMessage(error, 'push')).toBe(
+ [
+ 'Command failed: git push https://example.com/repo.git',
+ ' ! [rejected] main -> main (stale info)',
+ "error: failed to push some refs to 'origin'"
+ ].join('\n')
+ )
+ })
+
it('does not classify a rejection marker on a separate line as a stale lease rejection', () => {
const tail = "error: failed to push some refs to 'origin'"
const error = new Error(`Command failed: git push\n !\n [rejected] main (stale info)\n${tail}`)
@@ -153,6 +220,15 @@ describe('normalizeGitErrorMessage', () => {
})
describe('formatSubmodulePushFailureDetail', () => {
+ it.each([
+ "Unable to push sub\x1b[1 qmodule 'https://user:sec\x1b[1 [email protected]/repo.git'\n(fetch\x1b[1 q first)",
+ "Submodule 'https://user:sec\x1b[1 [email protected]/repo.git' has remote changes. Pull inside the submodule, then try again."
+ ])('sanitizes raw and normalized submodule details before classification: %s', (message) => {
+ expect(formatSubmodulePushFailureDetail(message)).toBe(
+ "Submodule 'https://example.com/repo.git' has remote changes. Pull inside the submodule, then try again."
+ )
+ })
+
it('keeps normalized guidance when transport layers prefix the error', () => {
expect(
formatSubmodulePushFailureDetail(
diff --git a/src/shared/git-remote-error.ts b/src/shared/git-remote-error.ts
index d95a6002223..580980abd5e 100644
--- a/src/shared/git-remote-error.ts
+++ b/src/shared/git-remote-error.ts
@@ -2,8 +2,8 @@ import { stripAnsiEscapeSequences } from './ansi-escape-sequences'
import { isPushHookFailure } from './source-control-push-failure'
// Why: strip `user:password@` on any scheme, but a lone `user@` only on HTTP(S) — SSH's git@host user-info is required, so stripping breaks the URL.
-const USERPASS_URL_PATTERN = /([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi
-const HTTPS_TOKEN_URL_PATTERN = /(https?:\/\/)[^\s/@:]+@/gi
+const URL_USERPASS_PATTERN = /[^\s/@:?#]+:[^\s/?#]+@/y
+const HTTPS_TOKEN_URL_PATTERN = /(https?:\/\/)[^\s/@:?#]+@/gi
const SUBMODULE_PUSH_FAILURE_PATTERN = /Unable to push submodule ['"](.+?)['"]/i
const SUBMODULE_PUSH_FAILURE_SENTINEL_PATTERN =
/failed to push all needed submodules|Unable to push submodule/i
@@ -21,7 +21,41 @@ const RECONCILIATION_PULL_ARG_PATTERN =
export const MERGE_RECONCILIATION_PULL_ARGS = ['--no-rebase']
export function stripCredentialsFromMessage(message: string): string {
- return message.replace(USERPASS_URL_PATTERN, '$1').replace(HTTPS_TOKEN_URL_PATTERN, '$1')
+ const spans: string[] = []
+ let retainedStart = 0
+ // Search fixed delimiters first so long scheme-like words cannot cause quadratic retries.
+ for (
+ let separator = message.indexOf('://');
+ separator !== -1;
+ separator = message.indexOf('://', separator + 3)
+ ) {
+ if (!hasUrlSchemeBefore(message, separator)) {
+ continue
+ }
+ const authorityStart = separator + 3
+ URL_USERPASS_PATTERN.lastIndex = authorityStart
+ const credentials = URL_USERPASS_PATTERN.exec(message)
+ if (credentials) {
+ spans.push(message.slice(retainedStart, authorityStart))
+ retainedStart = authorityStart + credentials[0].length
+ }
+ }
+ const withoutPasswords =
+ retainedStart === 0 ? message : spans.join('') + message.slice(retainedStart)
+ return withoutPasswords.replace(HTTPS_TOKEN_URL_PATTERN, '$1')
+}
+
+function hasUrlSchemeBefore(message: string, separator: number): boolean {
+ for (let index = separator - 1; index >= 0; index--) {
+ const code = message.charCodeAt(index)
+ if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) {
+ return true
+ }
+ if ((code < 48 || code > 57) && code !== 43 && code !== 45 && code !== 46) {
+ return false
+ }
+ }
+ return false
}
export type SubmodulePushFailure = {
@@ -32,7 +66,7 @@ export type SubmodulePushFailure = {
// Why: the renderer rebuilds this classification as translated copy; detail stays English for main/CLI.
export function classifySubmodulePushFailure(message: string): SubmodulePushFailure | null {
- const raw = stripCredentialsFromMessage(message)
+ const raw = stripCredentialsFromMessage(stripAnsiEscapeSequences(message))
const trimmed = raw.trim()
const normalizedMatch = trimmed.match(NORMALIZED_SUBMODULE_PUSH_FAILURE_PATTERN)
if (normalizedMatch) {
@@ -152,7 +186,7 @@ export function normalizeGitErrorMessage(error: unknown, operation?: GitRemoteOp
}
// Why: scrub credentials up-front so every downstream branch operates on already-redacted text.
- const raw = stripCredentialsFromMessage(error.message)
+ const raw = stripCredentialsFromMessage(stripAnsiEscapeSequences(error.message))
const submodulePushFailureDetail = formatSubmodulePushFailureDetail(raw)
if ((operation === 'push' || operation === undefined) && submodulePushFailureDetail) {
@@ -167,10 +201,7 @@ export function normalizeGitErrorMessage(error: unknown, operation?: GitRemoteOp
return 'Push rejected: remote has newer commits (non-fast-forward). Please pull or sync first.'
}
- if (
- operation === 'push' &&
- (STALE_LEASE_REJECTION_PATTERN.test(stripAnsiEscapeSequences(raw)) || isPushHookFailure(raw))
- ) {
+ if (operation === 'push' && (STALE_LEASE_REJECTION_PATTERN.test(raw) || isPushHookFailure(raw))) {
// Lease rejection and pre-push hook details precede Git's generic "failed to push some refs" tail line.
return raw.trim()
}