From 5db491b9163d88d50077e78e5f90e510aab2425c Mon Sep 17 00:00:00 2001 From: David Gasperoni Date: Sat, 7 Nov 2026 18:40:42 +0100 Subject: [PATCH 1/5] Use Git credential helpers for HTTPS authentication libgit2 has no notion of Git's "credential.helper" configuration, so GitUp could only authenticate HTTPS remotes from a Keychain item in the format used by "osxkeychain", or by prompting. Anyone using a different helper (gh, Git Credential Manager, ...) had to create a token by hand and store it in the Keychain. GCRepository now exposes -fillCredentialsForURL:..., -approveCredentials... and -rejectCredentials..., which shell out to "git credential fill", "approve" and "reject" with the user's login-shell PATH, so Git itself resolves the configured helpers (including URL-scoped and reset entries). Terminal prompts are disabled and the command is bounded by a timeout. The app asks the helpers first, then the Keychain, then shows the login dialog, for interactive transfers and for the background remote check. Credentials obtained from a helper are approved after a successful transfer and rejected when the remote asks again, instead of being duplicated in the Keychain. Co-Authored-By: Claude Fable 5.1 --- .../AuthenticationWindowController.m | 49 ++++++- GitUp/Application/Document.m | 3 + GitUpKit/Core/GCRepository-Tests.m | 55 ++++++++ GitUpKit/Core/GCRepository.h | 5 + GitUpKit/Core/GCRepository.m | 124 +++++++++++++++++- 5 files changed, 231 insertions(+), 5 deletions(-) diff --git a/GitUp/Application/AuthenticationWindowController.m b/GitUp/Application/AuthenticationWindowController.m index 0ceeeef9b..e2d9f8e84 100644 --- a/GitUp/Application/AuthenticationWindowController.m +++ b/GitUp/Application/AuthenticationWindowController.m @@ -11,7 +11,9 @@ #import "KeychainAccessor.h" @interface AuthenticationWindowControllerModel : NSObject +@property(nonatomic, assign) BOOL useCredentialHelper; @property(nonatomic, assign) BOOL useKeychain; +@property(nonatomic, assign) BOOL credentialsFromHelper; // Current credentials were provided by a Git credential helper @property(nonatomic, copy) NSURL* url; @property(nonatomic, copy) NSString* name; @property(nonatomic, copy) NSString* password; @@ -23,11 +25,16 @@ @implementation AuthenticationWindowControllerModel - (BOOL)isValid { return self.url && self.name && self.password; } +- (void)unsetUseCredentialHelper { + self.useCredentialHelper = NO; +} - (void)unsetUseKeychain { self.useKeychain = NO; } - (void)willStartTransfer { + self.useCredentialHelper = YES; self.useKeychain = YES; + self.credentialsFromHelper = NO; self.url = nil; self.name = nil; self.password = nil; @@ -37,6 +44,7 @@ - (void)didFinishTransferWithURL:(NSURL*)url success:(BOOL)success onResult:(voi BOOL shouldPassModel = success && self.isValid; onResult(shouldPassModel ? self : nil); } + self.credentialsFromHelper = NO; self.url = nil; self.name = nil; self.password = nil; @@ -105,6 +113,36 @@ - (void)repository:(GCRepository*)repository willStartTransferWithURL:(NSURL*)ur } - (BOOL)repository:(GCRepository*)repository requiresPlainTextAuthenticationForURL:(NSURL*)url user:(NSString*)user username:(NSString**)username password:(NSString**)password { + // Being asked again after a helper provided credentials means the remote rejected them: let the helpers know and fall through to the other sources + if (self.model.credentialsFromHelper && self.model.isValid) { + NSError* error; + if (![repository rejectCredentialsForURL:self.model.url username:self.model.name password:self.model.password error:&error]) { + XLOG_WARNING(@"Failed rejecting credentials with Git credential helpers: %@", error.localizedDescription); + } + self.model.credentialsFromHelper = NO; + self.model.url = nil; + self.model.name = nil; + self.model.password = nil; + } + + // Try the credential helpers configured in Git first (e.g. "gh auth git-credential", "osxkeychain" or Git Credential Manager) + if (self.model.useCredentialHelper) { + [self.model unsetUseCredentialHelper]; + NSString* helperUsername = nil; + NSString* helperPassword = nil; + NSError* error; + if ([repository fillCredentialsForURL:url user:user username:&helperUsername password:&helperPassword error:&error]) { + self.model.url = url; + self.model.name = helperUsername; + self.model.password = helperPassword; + self.model.credentialsFromHelper = YES; + *username = helperUsername; + *password = helperPassword; + return YES; + } + XLOG_VERBOSE(@"Git credential helpers did not provide credentials for \"%@\": %@", url, error.localizedDescription); + } + if (self.model.useKeychain) { [self.model unsetUseKeychain]; if ([KeychainAccessor loadPlainTextAuthenticationFormKeychainForURL:url user:user username:username password:password allowInteraction:YES]) { @@ -142,7 +180,16 @@ - (void)repository:(GCRepository*)repository didFinishTransferWithURL:(NSURL*)ur [self.model didFinishTransferWithURL:url success:success onResult:^(AuthenticationWindowControllerModel* model) { - if (model) { + if (!model) { + return; + } + if (model.credentialsFromHelper) { + // Let the helpers cache the credentials, like Git itself does, instead of duplicating them in the Keychain + NSError* error; + if (![repository approveCredentialsForURL:model.url username:model.name password:model.password error:&error]) { + XLOG_WARNING(@"Failed approving credentials with Git credential helpers: %@", error.localizedDescription); + } + } else { [KeychainAccessor savePlainTextAuthenticationToKeychainForURL:url username:model.name password:model.password]; } }]; diff --git a/GitUp/Application/Document.m b/GitUp/Application/Document.m index f3131a315..d447e7852 100644 --- a/GitUp/Application/Document.m +++ b/GitUp/Application/Document.m @@ -1913,6 +1913,9 @@ - (IBAction)selectNextCommit:(id)sender { } + (BOOL)repository:(GCRepository*)repository requiresPlainTextAuthenticationForURL:(NSURL*)url user:(NSString*)user username:(NSString**)username password:(NSString**)password { + if ([repository fillCredentialsForURL:url user:user username:username password:password error:NULL]) { // Non-interactive thanks to GIT_TERMINAL_PROMPT=0 + return YES; + } return [KeychainAccessor loadPlainTextAuthenticationFormKeychainForURL:url user:user username:username password:password allowInteraction:NO]; } diff --git a/GitUpKit/Core/GCRepository-Tests.m b/GitUpKit/Core/GCRepository-Tests.m index b96a0aff6..8911dabb1 100644 --- a/GitUpKit/Core/GCRepository-Tests.m +++ b/GitUpKit/Core/GCRepository-Tests.m @@ -105,6 +105,61 @@ - (void)testInitialization { XCTAssertFalse([[GCRepository alloc] initWithNewLocalRepository:self.repository.workingDirectoryPath bare:NO error:NULL]); } +- (void)testCredentialHelpers { + NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; + GCRepository* repository = [self createLocalRepositoryAtPath:path bare:NO]; + + // Create a fake credential helper that logs every invocation and answers "get" requests + NSString* helperDirectory = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; + XCTAssertTrue([[NSFileManager defaultManager] createDirectoryAtPath:helperDirectory withIntermediateDirectories:YES attributes:nil error:NULL]); + NSString* logPath = [helperDirectory stringByAppendingPathComponent:@"log"]; + NSString* helperPath = [helperDirectory stringByAppendingPathComponent:@"helper"]; + NSString* helperScript = [NSString stringWithFormat:@"#!/bin/sh\n" + "echo \"[$1]\" >> \"%@\"\n" + "cat >> \"%@\"\n" + "if [ \"$1\" = \"get\" ]; then\n" + " printf 'username=bot\\npassword=s3cret\\n'\n" + "fi\n", + logPath, logPath]; + XCTAssertTrue([helperScript writeToFile:helperPath atomically:YES encoding:NSUTF8StringEncoding error:NULL]); + XCTAssertTrue([[NSFileManager defaultManager] setAttributes:@{NSFilePosixPermissions : @(0755)} ofItemAtPath:helperPath error:NULL]); + + // No helper configured (reset inherited ones): no credentials + // Note: git only runs helpers as "git credential-" unless given an absolute path or a "!" command + XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"--add", @"credential.helper", @"", nil])); // Commas must be shielded from the macro + NSURL* url = [NSURL URLWithString:@"https://example.invalid/some/repo.git"]; + NSString* username = nil; + NSString* password = nil; + NSError* error = nil; + XCTAssertFalse([repository fillCredentialsForURL:url user:nil username:&username password:&password error:&error]); + XCTAssertNotNil(error); + XCTAssertNil(username); + XCTAssertNil(password); + + // Fake helper configured: fill, approve and reject + XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"--add", @"credential.helper", helperPath, nil])); + XCTAssertTrue([repository fillCredentialsForURL:url user:@"hint" username:&username password:&password error:&error]); + XCTAssertEqualObjects(username, @"bot"); + XCTAssertEqualObjects(password, @"s3cret"); + XCTAssertTrue([repository approveCredentialsForURL:url username:username password:password error:&error]); + XCTAssertTrue([repository rejectCredentialsForURL:url username:username password:password error:&error]); + + NSString* log = [NSString stringWithContentsOfFile:logPath encoding:NSUTF8StringEncoding error:NULL]; + XCTAssertNotNil(log); + NSArray* expectedEntries = @[ + @"[get]\nprotocol=https\nhost=example.invalid\nusername=hint\n", + @"[store]\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n", + @"[erase]\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n" + ]; + for (NSString* entry in expectedEntries) { + XCTAssertTrue([log containsString:entry], @"Missing \"%@\" in helper log:\n%@", entry, log); + } + XCTAssertFalse([log containsString:@"path="]); // Stripped by git unless credential.useHttpPath is set + + XCTAssertTrue([[NSFileManager defaultManager] removeItemAtPath:helperDirectory error:NULL]); + [self destroyLocalRepository:repository]; +} + - (void)testPathForHookWithName { NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; diff --git a/GitUpKit/Core/GCRepository.h b/GitUpKit/Core/GCRepository.h index cf7240f0d..933ecc828 100644 --- a/GitUpKit/Core/GCRepository.h +++ b/GitUpKit/Core/GCRepository.h @@ -82,5 +82,10 @@ typedef NS_ENUM(NSUInteger, GCFileMode) { #if !TARGET_OS_IPHONE - (NSString*)pathForHookWithName:(NSString*)name; // Returns nil if hook doesn't exist - (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardInput:(NSString*)standardInput error:(NSError**)error; // Silently ignores non-existing hooks + +// Git credential helpers as configured through "credential.helper" - See git-credential(1) +- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user username:(NSString**)username password:(NSString**)password error:(NSError**)error; // "git credential fill" - Returns NO if no helper provided credentials +- (BOOL)approveCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error; // "git credential approve" +- (BOOL)rejectCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error; // "git credential reject" #endif @end diff --git a/GitUpKit/Core/GCRepository.m b/GitUpKit/Core/GCRepository.m index 8ee279425..d6e6dd03a 100644 --- a/GitUpKit/Core/GCRepository.m +++ b/GitUpKit/Core/GCRepository.m @@ -376,14 +376,22 @@ - (NSString*)getPATHUsingShell:(NSString*)shell error:(NSError**)error { return [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; } -- (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardInput:(NSString*)standardInput error:(NSError**)error { - NSString* path = [self pathForHookWithName:name]; - if (path) { - static NSString* cachedPATH = nil; +// Resolve the user's PATH through their login shell (once per process) so that tools installed outside /usr/bin are found +- (NSString*)_userPATH:(NSError**)error { + static NSString* cachedPATH = nil; + @synchronized([GCRepository class]) { if (cachedPATH == nil) { cachedPATH = [self getPATHUsingShell:NSProcessInfo.processInfo.environment[@"SHELL"] error:error] ?: [self getPATHUsingShell:@"/bin/sh" error:error]; XLOG_DEBUG_CHECK(cachedPATH); } + return cachedPATH; + } +} + +- (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardInput:(NSString*)standardInput error:(NSError**)error { + NSString* path = [self pathForHookWithName:name]; + if (path) { + NSString* cachedPATH = [self _userPATH:error]; CFAbsoluteTime time = CFAbsoluteTimeGetCurrent(); GCTask* task = [[GCTask alloc] initWithExecutablePath:path]; @@ -414,6 +422,114 @@ - (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardIn return YES; } +#pragma mark - Credential Helpers + +// Serialize a credential description in the format expected by "git credential" - See git-credential(1) "INPUT/OUTPUT FORMAT" +static BOOL _AppendCredentialAttribute(NSMutableString* string, NSString* key, NSString* value) { + if (!value.length) { + return YES; // Nothing to add + } + if ([value rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"\n\0"]].location != NSNotFound) { + return NO; // Attribute values can't contain newlines or NULs + } + [string appendFormat:@"%@=%@\n", key, value]; + return YES; +} + +static NSData* _CredentialDescriptionData(NSURL* url, NSString* username, NSString* password) { + NSURLComponents* components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO]; + components.user = nil; // Passed separately as "username" below + components.password = nil; + components.query = nil; + components.fragment = nil; + NSString* urlString = components.URL.absoluteString; + if (!urlString.length) { + return nil; + } + NSMutableString* string = [[NSMutableString alloc] init]; + if (!_AppendCredentialAttribute(string, @"url", urlString) || !_AppendCredentialAttribute(string, @"username", username) || !_AppendCredentialAttribute(string, @"password", password)) { + return nil; + } + [string appendString:@"\n"]; // Blank line terminates the description + return [string dataUsingEncoding:NSUTF8StringEncoding]; +} + +- (BOOL)_runCredentialCommand:(NSString*)command url:(NSURL*)url username:(NSString*)username password:(NSString*)password output:(NSData**)output error:(NSError**)error { + NSData* input = _CredentialDescriptionData(url, username, password); + if (input == nil) { + GC_SET_GENERIC_ERROR(@"Unable to describe credentials for \"%@\"", url); + return NO; + } + NSString* path = [self _userPATH:NULL] ?: NSProcessInfo.processInfo.environment[@"PATH"]; + if (!path.length) { + path = @"/usr/bin:/bin:/usr/sbin:/sbin"; + } + + CFAbsoluteTime time = CFAbsoluteTimeGetCurrent(); + GCTask* task = [[GCTask alloc] initWithExecutablePath:@"/usr/bin/env"]; // Use the user's "git" rather than hardcoding /usr/bin/git + task.currentDirectoryPath = self.workingDirectoryPath ?: self.repositoryPath; // So that repository-local configuration applies + task.additionalEnvironment = @{ + @"PATH" : path, + @"GIT_TERMINAL_PROMPT" : @"0" // Never block waiting on a terminal that doesn't exist + }; + task.executionTimeOut = 120.0; // Helpers may legitimately prompt the user (e.g. Git Credential Manager), but never hang forever + int status; + NSData* stdoutData; + NSData* stderrData; + if (![task runWithArguments:@[ @"git", @"credential", command ] stdin:input stdout:&stdoutData stderr:&stderrData exitStatus:&status error:error]) { + return NO; + } + XLOG_VERBOSE(@"Executed 'git credential %@' in %.3f seconds", command, CFAbsoluteTimeGetCurrent() - time); + if (status != 0) { + NSString* string = [[[NSString alloc] initWithData:(stderrData.length ? stderrData : stdoutData) encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + GC_SET_GENERIC_ERROR(@"'git credential %@' exited with non-zero status (%i)%@%@", command, status, string.length ? @": " : @"", string ?: @""); + return NO; + } + if (output) { + *output = stdoutData; + } + return YES; +} + +- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user username:(NSString**)username password:(NSString**)password error:(NSError**)error { + NSData* output; + if (![self _runCredentialCommand:@"fill" url:url username:(url.user.length ? url.user : user) password:nil output:&output error:error]) { + return NO; + } + NSString* string = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding]; + NSString* outUsername = nil; + NSString* outPassword = nil; + for (NSString* line in [string componentsSeparatedByString:@"\n"]) { + NSRange range = [line rangeOfString:@"="]; + if (range.location == NSNotFound) { + continue; + } + NSString* key = [line substringToIndex:range.location]; + NSString* value = [line substringFromIndex:(range.location + 1)]; + if ([key isEqualToString:@"username"]) { + outUsername = value; + } else if ([key isEqualToString:@"password"]) { + outPassword = value; + } + } + if (!outUsername.length || !outPassword.length) { + GC_SET_GENERIC_ERROR(@"No credential helper provided credentials for \"%@\"", url); + return NO; + } + XLOG_VERBOSE(@"Obtained credentials for \"%@\" from Git credential helper", url); + *username = outUsername; + *password = outPassword; + return YES; +} + +- (BOOL)approveCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error { + return [self _runCredentialCommand:@"approve" url:url username:username password:password output:NULL error:error]; +} + +- (BOOL)rejectCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error { + return [self _runCredentialCommand:@"reject" url:url username:username password:password output:NULL error:error]; +} + #endif #if DEBUG From acab700ef8a7092fab75d9836562824197768d16 Mon Sep 17 00:00:00 2001 From: David Gasperoni Date: Sat, 7 Nov 2026 20:26:19 +0100 Subject: [PATCH 2/5] Run credential helpers off the main thread and never prompt during automatic checks Address review feedback on the credential helper support: - Move the helper lookup from the application's authentication delegate into GCRepository's libgit2 credentials callback, which runs on the transfer thread. The UI (progress indicator, window) stays responsive while a helper works, and only the actual login dialog still goes to the main thread. Helper-provided credentials are approved when the transfer succeeds and rejected if libgit2 asks again; this is now encapsulated in GCRepository instead of being tracked by the window controller. - Add GCCredentialHelperMode (disabled by default so other GitUpKit clients are unaffected). Document enables the interactive mode for user-initiated transfers and the non-interactive mode for the automatic remote checks: that mode also sets GIT_ASKPASS to a failing program, GCM_INTERACTIVE=never and credential.interactive=false so helpers with their own UI cannot pop up during a background check, and uses a shorter timeout. GCLiveRepository propagates the mode to the per-operation repositories it creates. - Treat present-but-empty username/password values as valid, as Git's credential format does, and preserve them when describing credentials to approve/reject. - Isolate the unit test from the developer's global configuration by turning off credential.useHttpPath in the temporary repository, and assert that the non-interactive environment reaches the helper. Co-Authored-By: Claude Fable 5.1 --- .../AuthenticationWindowController.m | 49 +---------- GitUp/Application/Document.m | 5 +- GitUpKit/Core/GCLiveRepository.m | 1 + GitUpKit/Core/GCRepository-Tests.m | 23 +++-- GitUpKit/Core/GCRepository.h | 9 +- GitUpKit/Core/GCRepository.m | 87 ++++++++++++++++--- 6 files changed, 101 insertions(+), 73 deletions(-) diff --git a/GitUp/Application/AuthenticationWindowController.m b/GitUp/Application/AuthenticationWindowController.m index e2d9f8e84..0ceeeef9b 100644 --- a/GitUp/Application/AuthenticationWindowController.m +++ b/GitUp/Application/AuthenticationWindowController.m @@ -11,9 +11,7 @@ #import "KeychainAccessor.h" @interface AuthenticationWindowControllerModel : NSObject -@property(nonatomic, assign) BOOL useCredentialHelper; @property(nonatomic, assign) BOOL useKeychain; -@property(nonatomic, assign) BOOL credentialsFromHelper; // Current credentials were provided by a Git credential helper @property(nonatomic, copy) NSURL* url; @property(nonatomic, copy) NSString* name; @property(nonatomic, copy) NSString* password; @@ -25,16 +23,11 @@ @implementation AuthenticationWindowControllerModel - (BOOL)isValid { return self.url && self.name && self.password; } -- (void)unsetUseCredentialHelper { - self.useCredentialHelper = NO; -} - (void)unsetUseKeychain { self.useKeychain = NO; } - (void)willStartTransfer { - self.useCredentialHelper = YES; self.useKeychain = YES; - self.credentialsFromHelper = NO; self.url = nil; self.name = nil; self.password = nil; @@ -44,7 +37,6 @@ - (void)didFinishTransferWithURL:(NSURL*)url success:(BOOL)success onResult:(voi BOOL shouldPassModel = success && self.isValid; onResult(shouldPassModel ? self : nil); } - self.credentialsFromHelper = NO; self.url = nil; self.name = nil; self.password = nil; @@ -113,36 +105,6 @@ - (void)repository:(GCRepository*)repository willStartTransferWithURL:(NSURL*)ur } - (BOOL)repository:(GCRepository*)repository requiresPlainTextAuthenticationForURL:(NSURL*)url user:(NSString*)user username:(NSString**)username password:(NSString**)password { - // Being asked again after a helper provided credentials means the remote rejected them: let the helpers know and fall through to the other sources - if (self.model.credentialsFromHelper && self.model.isValid) { - NSError* error; - if (![repository rejectCredentialsForURL:self.model.url username:self.model.name password:self.model.password error:&error]) { - XLOG_WARNING(@"Failed rejecting credentials with Git credential helpers: %@", error.localizedDescription); - } - self.model.credentialsFromHelper = NO; - self.model.url = nil; - self.model.name = nil; - self.model.password = nil; - } - - // Try the credential helpers configured in Git first (e.g. "gh auth git-credential", "osxkeychain" or Git Credential Manager) - if (self.model.useCredentialHelper) { - [self.model unsetUseCredentialHelper]; - NSString* helperUsername = nil; - NSString* helperPassword = nil; - NSError* error; - if ([repository fillCredentialsForURL:url user:user username:&helperUsername password:&helperPassword error:&error]) { - self.model.url = url; - self.model.name = helperUsername; - self.model.password = helperPassword; - self.model.credentialsFromHelper = YES; - *username = helperUsername; - *password = helperPassword; - return YES; - } - XLOG_VERBOSE(@"Git credential helpers did not provide credentials for \"%@\": %@", url, error.localizedDescription); - } - if (self.model.useKeychain) { [self.model unsetUseKeychain]; if ([KeychainAccessor loadPlainTextAuthenticationFormKeychainForURL:url user:user username:username password:password allowInteraction:YES]) { @@ -180,16 +142,7 @@ - (void)repository:(GCRepository*)repository didFinishTransferWithURL:(NSURL*)ur [self.model didFinishTransferWithURL:url success:success onResult:^(AuthenticationWindowControllerModel* model) { - if (!model) { - return; - } - if (model.credentialsFromHelper) { - // Let the helpers cache the credentials, like Git itself does, instead of duplicating them in the Keychain - NSError* error; - if (![repository approveCredentialsForURL:model.url username:model.name password:model.password error:&error]) { - XLOG_WARNING(@"Failed approving credentials with Git credential helpers: %@", error.localizedDescription); - } - } else { + if (model) { [KeychainAccessor savePlainTextAuthenticationToKeychainForURL:url username:model.name password:model.password]; } }]; diff --git a/GitUp/Application/Document.m b/GitUp/Application/Document.m index d447e7852..de3ed4285 100644 --- a/GitUp/Application/Document.m +++ b/GitUp/Application/Document.m @@ -231,6 +231,7 @@ - (BOOL)readFromURL:(NSURL*)url ofType:(NSString*)typeName error:(NSError**)outE } #endif _repository.delegate = self; + _repository.credentialHelperMode = kGCCredentialHelperMode_Interactive; // Consult the Git credential helpers (e.g. gh, osxkeychain, Git Credential Manager) before the Keychain and the login dialog _repository.undoManager = self.undoManager; _repository.snapshotsEnabled = YES; if ([NSApp isActive]) { @@ -1913,9 +1914,6 @@ - (IBAction)selectNextCommit:(id)sender { } + (BOOL)repository:(GCRepository*)repository requiresPlainTextAuthenticationForURL:(NSURL*)url user:(NSString*)user username:(NSString**)username password:(NSString**)password { - if ([repository fillCredentialsForURL:url user:user username:username password:password error:NULL]) { // Non-interactive thanks to GIT_TERMINAL_PROMPT=0 - return YES; - } return [KeychainAccessor loadPlainTextAuthenticationFormKeychainForURL:url user:user username:username password:password allowInteraction:NO]; } @@ -1928,6 +1926,7 @@ - (IBAction)checkForChanges:(id)sender { NSMutableDictionary* updatedReferences = [[NSMutableDictionary alloc] init]; GCRepository* repository = [[GCRepository alloc] initWithExistingLocalRepository:path error:NULL]; repository.delegate = (id)self.class; // Don't use self as we don't want to show progress UI nor authentication prompts + repository.credentialHelperMode = kGCCredentialHelperMode_NonInteractive; // Same for Git credential helpers: they may not prompt during an automatic check for (GCRemote* remote in [repository listRemotes:NULL]) { @autoreleasepool { NSDictionary* added; diff --git a/GitUpKit/Core/GCLiveRepository.m b/GitUpKit/Core/GCLiveRepository.m index c3ebade77..f5e6282d1 100644 --- a/GitUpKit/Core/GCLiveRepository.m +++ b/GitUpKit/Core/GCLiveRepository.m @@ -842,6 +842,7 @@ - (void)performOperationInBackgroundWithReason:(NSString*)reason dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ GCRepository* repository = [[GCRepository alloc] initWithExistingLocalRepository:self.repositoryPath error:&error]; repository.delegate = self.delegate; + repository.credentialHelperMode = self.credentialHelperMode; __block BOOL success = repository && operationBlock(repository, &error); dispatch_async(dispatch_get_main_queue(), ^{ if (success) { diff --git a/GitUpKit/Core/GCRepository-Tests.m b/GitUpKit/Core/GCRepository-Tests.m index 8911dabb1..bbe57c8bd 100644 --- a/GitUpKit/Core/GCRepository-Tests.m +++ b/GitUpKit/Core/GCRepository-Tests.m @@ -115,7 +115,7 @@ - (void)testCredentialHelpers { NSString* logPath = [helperDirectory stringByAppendingPathComponent:@"log"]; NSString* helperPath = [helperDirectory stringByAppendingPathComponent:@"helper"]; NSString* helperScript = [NSString stringWithFormat:@"#!/bin/sh\n" - "echo \"[$1]\" >> \"%@\"\n" + "echo \"[$1] interactive=${GCM_INTERACTIVE:-default}\" >> \"%@\"\n" "cat >> \"%@\"\n" "if [ \"$1\" = \"get\" ]; then\n" " printf 'username=bot\\npassword=s3cret\\n'\n" @@ -124,21 +124,27 @@ - (void)testCredentialHelpers { XCTAssertTrue([helperScript writeToFile:helperPath atomically:YES encoding:NSUTF8StringEncoding error:NULL]); XCTAssertTrue([[NSFileManager defaultManager] setAttributes:@{NSFilePosixPermissions : @(0755)} ofItemAtPath:helperPath error:NULL]); - // No helper configured (reset inherited ones): no credentials + // Isolate from the developer's own configuration: reset inherited helpers and make sure "path=" isn't sent // Note: git only runs helpers as "git credential-" unless given an absolute path or a "!" command XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"--add", @"credential.helper", @"", nil])); // Commas must be shielded from the macro + XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"credential.useHttpPath", @"false", nil])); + + // No helper configured: no credentials NSURL* url = [NSURL URLWithString:@"https://example.invalid/some/repo.git"]; NSString* username = nil; NSString* password = nil; NSError* error = nil; - XCTAssertFalse([repository fillCredentialsForURL:url user:nil username:&username password:&password error:&error]); + XCTAssertFalse([repository fillCredentialsForURL:url user:nil allowInteraction:NO username:&username password:&password error:&error]); XCTAssertNotNil(error); XCTAssertNil(username); XCTAssertNil(password); // Fake helper configured: fill, approve and reject XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"--add", @"credential.helper", helperPath, nil])); - XCTAssertTrue([repository fillCredentialsForURL:url user:@"hint" username:&username password:&password error:&error]); + XCTAssertTrue([repository fillCredentialsForURL:url user:@"hint" allowInteraction:NO username:&username password:&password error:&error]); + XCTAssertEqualObjects(username, @"bot"); + XCTAssertEqualObjects(password, @"s3cret"); + XCTAssertTrue([repository fillCredentialsForURL:url user:@"hint" allowInteraction:YES username:&username password:&password error:&error]); XCTAssertEqualObjects(username, @"bot"); XCTAssertEqualObjects(password, @"s3cret"); XCTAssertTrue([repository approveCredentialsForURL:url username:username password:password error:&error]); @@ -147,14 +153,15 @@ - (void)testCredentialHelpers { NSString* log = [NSString stringWithContentsOfFile:logPath encoding:NSUTF8StringEncoding error:NULL]; XCTAssertNotNil(log); NSArray* expectedEntries = @[ - @"[get]\nprotocol=https\nhost=example.invalid\nusername=hint\n", - @"[store]\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n", - @"[erase]\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n" + @"[get] interactive=never\nprotocol=https\nhost=example.invalid\nusername=hint\n", // Non-interactive mode tells helpers not to prompt + @"[get] interactive=default\nprotocol=https\nhost=example.invalid\nusername=hint\n", + @"[store] interactive=never\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n", + @"[erase] interactive=never\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n" ]; for (NSString* entry in expectedEntries) { XCTAssertTrue([log containsString:entry], @"Missing \"%@\" in helper log:\n%@", entry, log); } - XCTAssertFalse([log containsString:@"path="]); // Stripped by git unless credential.useHttpPath is set + XCTAssertFalse([log containsString:@"path="]); // credential.useHttpPath is off XCTAssertTrue([[NSFileManager defaultManager] removeItemAtPath:helperDirectory error:NULL]); [self destroyLocalRepository:repository]; diff --git a/GitUpKit/Core/GCRepository.h b/GitUpKit/Core/GCRepository.h index 933ecc828..1c02eb6b4 100644 --- a/GitUpKit/Core/GCRepository.h +++ b/GitUpKit/Core/GCRepository.h @@ -40,6 +40,12 @@ typedef NS_ENUM(NSUInteger, GCFileMode) { #define GC_FILE_MODE_IS_FILE(m) (((m) == kGCFileMode_Blob) || ((m) == kGCFileMode_BlobExecutable) || ((m) == kGCFileMode_Link)) #define GC_FILE_MODE_IS_SUBMODULE(m) (((m) == kGCFileMode_Tree) || ((m) == kGCFileMode_Commit)) +typedef NS_ENUM(NSUInteger, GCCredentialHelperMode) { + kGCCredentialHelperMode_Disabled = 0, // Never run the Git credential helpers (default) + kGCCredentialHelperMode_NonInteractive, // Run the helpers but forbid them from prompting the user (e.g. for automatic remote checks) + kGCCredentialHelperMode_Interactive // Run the helpers and let them prompt the user if they need to (e.g. Git Credential Manager) +}; + @class GCRepository; @protocol GCRepositoryDelegate @@ -55,6 +61,7 @@ typedef NS_ENUM(NSUInteger, GCFileMode) { /// Walks up the file system to find the repository the given URL is contained in. Returns nil and sets the error if no repository is found. + (NSURL *)repositoryURLContainingURL:(NSURL *)url error:(NSError **)error; @property(nonatomic, weak) id delegate; +@property(nonatomic) GCCredentialHelperMode credentialHelperMode; // Whether HTTPS transfers consult the Git credential helpers configured through "credential.helper" before asking the delegate (macOS only) @property(nonatomic, readonly) NSString* repositoryPath; @property(nonatomic, readonly) NSString* workingDirectoryPath; // nil for a bare repository @property(nonatomic, readonly, getter=isReadOnly) BOOL readOnly; @@ -84,7 +91,7 @@ typedef NS_ENUM(NSUInteger, GCFileMode) { - (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardInput:(NSString*)standardInput error:(NSError**)error; // Silently ignores non-existing hooks // Git credential helpers as configured through "credential.helper" - See git-credential(1) -- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user username:(NSString**)username password:(NSString**)password error:(NSError**)error; // "git credential fill" - Returns NO if no helper provided credentials +- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction:(BOOL)allowInteraction username:(NSString**)username password:(NSString**)password error:(NSError**)error; // "git credential fill" - Returns NO if no helper provided credentials - (BOOL)approveCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error; // "git credential approve" - (BOOL)rejectCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error; // "git credential reject" #endif diff --git a/GitUpKit/Core/GCRepository.m b/GitUpKit/Core/GCRepository.m index d6e6dd03a..4fe752399 100644 --- a/GitUpKit/Core/GCRepository.m +++ b/GitUpKit/Core/GCRepository.m @@ -102,6 +102,10 @@ @implementation GCRepository { BOOL _didTrySSHAgent; NSMutableArray* _privateKeyList; NSUInteger _privateKeyIndex; + BOOL _didTryCredentialHelper; + NSURL* _helperCredentialsURL; // Set while credentials obtained from a Git credential helper are in use for the current transfer + NSString* _helperCredentialsUsername; + NSString* _helperCredentialsPassword; #endif BOOL _hasFetchProgressDelegate; @@ -426,8 +430,8 @@ - (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardIn // Serialize a credential description in the format expected by "git credential" - See git-credential(1) "INPUT/OUTPUT FORMAT" static BOOL _AppendCredentialAttribute(NSMutableString* string, NSString* key, NSString* value) { - if (!value.length) { - return YES; // Nothing to add + if (value == nil) { + return YES; // Nothing to add (an empty value is a legitimate attribute though) } if ([value rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"\n\0"]].location != NSNotFound) { return NO; // Attribute values can't contain newlines or NULs @@ -454,7 +458,13 @@ static BOOL _AppendCredentialAttribute(NSMutableString* string, NSString* key, N return [string dataUsingEncoding:NSUTF8StringEncoding]; } -- (BOOL)_runCredentialCommand:(NSString*)command url:(NSURL*)url username:(NSString*)username password:(NSString*)password output:(NSData**)output error:(NSError**)error { +- (void)_clearHelperCredentials { + _helperCredentialsURL = nil; + _helperCredentialsUsername = nil; + _helperCredentialsPassword = nil; +} + +- (BOOL)_runCredentialCommand:(NSString*)command url:(NSURL*)url username:(NSString*)username password:(NSString*)password allowInteraction:(BOOL)allowInteraction output:(NSData**)output error:(NSError**)error { NSData* input = _CredentialDescriptionData(url, username, password); if (input == nil) { GC_SET_GENERIC_ERROR(@"Unable to describe credentials for \"%@\"", url); @@ -468,11 +478,21 @@ - (BOOL)_runCredentialCommand:(NSString*)command url:(NSURL*)url username:(NSStr CFAbsoluteTime time = CFAbsoluteTimeGetCurrent(); GCTask* task = [[GCTask alloc] initWithExecutablePath:@"/usr/bin/env"]; // Use the user's "git" rather than hardcoding /usr/bin/git task.currentDirectoryPath = self.workingDirectoryPath ?: self.repositoryPath; // So that repository-local configuration applies - task.additionalEnvironment = @{ - @"PATH" : path, - @"GIT_TERMINAL_PROMPT" : @"0" // Never block waiting on a terminal that doesn't exist - }; - task.executionTimeOut = 120.0; // Helpers may legitimately prompt the user (e.g. Git Credential Manager), but never hang forever + NSMutableDictionary* environment = [[NSMutableDictionary alloc] init]; + environment[@"PATH"] = path; + environment[@"GIT_TERMINAL_PROMPT"] = @"0"; // Never block waiting on a terminal that doesn't exist + if (allowInteraction) { + task.executionTimeOut = 120.0; // Helpers may legitimately prompt the user (e.g. Git Credential Manager), but never hang forever + } else { + // GIT_TERMINAL_PROMPT only silences Git itself: also tell helpers with their own UI to stay quiet + environment[@"GIT_ASKPASS"] = @"/usr/bin/false"; // Takes precedence over SSH_ASKPASS and fails any prompt Git would make through an askpass program + environment[@"GCM_INTERACTIVE"] = @"never"; // Git Credential Manager + environment[@"GIT_CONFIG_COUNT"] = @"1"; // Equivalent of "-c credential.interactive=false", also seen by helpers that read Git configuration + environment[@"GIT_CONFIG_KEY_0"] = @"credential.interactive"; + environment[@"GIT_CONFIG_VALUE_0"] = @"false"; + task.executionTimeOut = 30.0; + } + task.additionalEnvironment = environment; int status; NSData* stdoutData; NSData* stderrData; @@ -491,9 +511,9 @@ - (BOOL)_runCredentialCommand:(NSString*)command url:(NSURL*)url username:(NSStr return YES; } -- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user username:(NSString**)username password:(NSString**)password error:(NSError**)error { +- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction:(BOOL)allowInteraction username:(NSString**)username password:(NSString**)password error:(NSError**)error { NSData* output; - if (![self _runCredentialCommand:@"fill" url:url username:(url.user.length ? url.user : user) password:nil output:&output error:error]) { + if (![self _runCredentialCommand:@"fill" url:url username:(url.user.length ? url.user : user) password:nil allowInteraction:allowInteraction output:&output error:error]) { return NO; } NSString* string = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding]; @@ -512,7 +532,7 @@ - (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user username:(NSStrin outPassword = value; } } - if (!outUsername.length || !outPassword.length) { + if ((outUsername == nil) || (outPassword == nil)) { // Empty values are legitimate (e.g. a token passed as the username with an empty password) GC_SET_GENERIC_ERROR(@"No credential helper provided credentials for \"%@\"", url); return NO; } @@ -523,11 +543,11 @@ - (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user username:(NSStrin } - (BOOL)approveCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error { - return [self _runCredentialCommand:@"approve" url:url username:username password:password output:NULL error:error]; + return [self _runCredentialCommand:@"approve" url:url username:username password:password allowInteraction:NO output:NULL error:error]; } - (BOOL)rejectCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error { - return [self _runCredentialCommand:@"reject" url:url username:username password:password output:NULL error:error]; + return [self _runCredentialCommand:@"reject" url:url username:username password:password allowInteraction:NO output:NULL error:error]; } #endif @@ -590,6 +610,17 @@ - (void)willStartRemoteTransferWithURL:(NSURL*)url { } - (void)didFinishRemoteTransferWithURL:(NSURL*)url success:(BOOL)success { +#if !TARGET_OS_IPHONE + if (_helperCredentialsPassword) { + if (success) { // Let the helpers cache the credentials like Git does - On failure Git only rejects credentials the server refused, which is handled when libgit2 asks for credentials again + NSError* error; + if (![self approveCredentialsForURL:_helperCredentialsURL username:_helperCredentialsUsername password:_helperCredentialsPassword error:&error]) { + XLOG_WARNING(@"Failed approving credentials with Git credential helpers: %@", error.localizedDescription); + } + } + [self _clearHelperCredentials]; + } +#endif if ([_delegate respondsToSelector:@selector(repository:didFinishTransferWithURL:success:)]) { if ([NSThread isMainThread]) { [_delegate repository:self didFinishTransferWithURL:url success:success]; @@ -672,6 +703,34 @@ static int _CredentialsCallback(git_cred** cred, const char* url, const char* us } } if (allowed_types & GIT_CREDTYPE_USERPASS_PLAINTEXT) { +#if !TARGET_OS_IPHONE + if (repository->_helperCredentialsPassword) { // Being asked again means the server refused what the helpers provided: tell them and move on to the delegate + NSError* error; + if (![repository rejectCredentialsForURL:repository->_helperCredentialsURL username:repository->_helperCredentialsUsername password:repository->_helperCredentialsPassword error:&error]) { + XLOG_WARNING(@"Failed rejecting credentials with Git credential helpers: %@", error.localizedDescription); + } + [repository _clearHelperCredentials]; + } + if ((repository.credentialHelperMode != kGCCredentialHelperMode_Disabled) && !repository->_didTryCredentialHelper) { // Runs on the transfer thread so the UI stays responsive while helpers work + repository->_didTryCredentialHelper = YES; + NSURL* helperURL = GCURLFromGitURL([NSString stringWithUTF8String:url]); + NSString* helperUsername = nil; + NSString* helperPassword = nil; + NSError* error; + if ([repository fillCredentialsForURL:helperURL + user:(user ? [NSString stringWithUTF8String:user] : nil) + allowInteraction:(repository.credentialHelperMode == kGCCredentialHelperMode_Interactive) + username:&helperUsername + password:&helperPassword + error:&error]) { + repository->_helperCredentialsURL = helperURL; + repository->_helperCredentialsUsername = helperUsername; + repository->_helperCredentialsPassword = helperPassword; + return git_cred_userpass_plaintext_new(cred, helperUsername.UTF8String, helperPassword.UTF8String); + } + XLOG_VERBOSE(@"Git credential helpers did not provide credentials for \"%s\": %@", url, error.localizedDescription); + } +#endif if ([repository.delegate respondsToSelector:@selector(repository:requiresPlainTextAuthenticationForURL:user:username:password:)]) { // Must use sync dispatch __block NSString* username = nil; __block NSString* password = nil; @@ -831,6 +890,8 @@ - (void)setRemoteCallbacks:(git_remote_callbacks*)callbacks { _didTrySSHAgent = NO; _privateKeyList = nil; _privateKeyIndex = 0; + _didTryCredentialHelper = NO; + [self _clearHelperCredentials]; #endif _hasFetchProgressDelegate = [_delegate respondsToSelector:@selector(repository:updateTransferProgress:transferredBytes:)]; From 36f5a34182e418e62cad005a6b3096e9f0405b93 Mon Sep 17 00:00:00 2001 From: David Gasperoni Date: Sat, 7 Nov 2026 21:09:52 +0100 Subject: [PATCH 3/5] Propagate the credential helper mode to submodule repositories Child GCRepository instances created for submodule transfers copied the parent's delegate but not its credentialHelperMode, so they stayed disabled and private submodules fell back to the Keychain and the login dialog even when Git had working credentials. Copy the mode wherever the delegate is copied: when adding a submodule, when initializing submodules recursively, and when fetching recursively. Co-Authored-By: Claude Opus 5.5 --- GitUpKit/Core/GCSubmodule.m | 2 ++ GitUpKit/Extensions/GCRepository+Utilities.m | 1 + 2 files changed, 3 insertions(+) diff --git a/GitUpKit/Core/GCSubmodule.m b/GitUpKit/Core/GCSubmodule.m index 6a5d144f1..c14bbb609 100644 --- a/GitUpKit/Core/GCSubmodule.m +++ b/GitUpKit/Core/GCSubmodule.m @@ -158,6 +158,7 @@ - (GCSubmodule*)addSubmoduleWithURL:(NSURL*)url atPath:(NSString*)path recursive goto cleanup; } repository.delegate = self.delegate; + repository.credentialHelperMode = self.credentialHelperMode; remote = [repository lookupRemoteWithName:@"origin" error:error]; if (remote == nil) { goto cleanup; @@ -196,6 +197,7 @@ - (BOOL)initializeSubmodule:(GCSubmodule*)submodule recursive:(BOOL)recursive er return NO; } repository.delegate = self.delegate; + repository.credentialHelperMode = self.credentialHelperMode; if (![repository initializeAllSubmodules:recursive error:error]) { return NO; } diff --git a/GitUpKit/Extensions/GCRepository+Utilities.m b/GitUpKit/Extensions/GCRepository+Utilities.m index 153ed7df7..a03591f23 100644 --- a/GitUpKit/Extensions/GCRepository+Utilities.m +++ b/GitUpKit/Extensions/GCRepository+Utilities.m @@ -63,6 +63,7 @@ - (BOOL)_fetchRepository:(GCRepository*)repository recursive:(BOOL)recursive err for (GCSubmodule* submodule in submodules) { GCRepository* subRepository = [[GCRepository alloc] initWithSubmodule:submodule error:error]; subRepository.delegate = self.delegate; + subRepository.credentialHelperMode = self.credentialHelperMode; if (subRepository == nil) { return NO; } From c2bdfc440b7a06ae40c19e2ff505a82f4fe9d506 Mon Sep 17 00:00:00 2001 From: David Gasperoni Date: Tue, 10 Nov 2026 00:41:35 +0100 Subject: [PATCH 4/5] Harden the credential helper support after review Correctness: - Hand Git's complete answer back to "git credential approve/reject" instead of only the username and password, so helpers also get the attributes they attached (password_expiry_utc, oauth_refresh_token, state[]...). The public API now carries an opaque description. - Only involve the helpers for HTTP(S) URLs, like Git does: they were also asked for password authentication over SSH. URLs that can't be parsed are skipped instead of raising in NSURLComponents. - Never let Git prompt by itself: GIT_ASKPASS is now overridden in both modes, so "core.askPass" can't pop a third-party dialog before the application's own. - Automatic (non-interactive) transfers ask the delegate first and the helpers second. A helper reading a Keychain item it didn't create, e.g. "osxkeychain" with a password saved by the application, makes macOS prompt the user, which can't be suppressed from here. - GCTask stops waiting for its pipes once it timed out. NSTask already terminates the whole process group, but a process that survives it (signals ignored, or moved to another group) kept the pipes open and the task waiting for as long as it lived. Output of approve/reject is no longer captured for the same reason. Structure: - Add -inheritRemoteSettingsFromRepository: and use it everywhere a repository is opened on behalf of another one, including the recursive branch of -initializeAllSubmodules: which copied neither the delegate nor the helper mode. - Share GCNewErrorFromTaskFailure() and -getUserPATH: between hooks, commit signing and credentials. Commit signing keeps resolving PATH once per operation on purpose. - Automatic transfers don't approve again credentials the helpers were already told about in this process, which saves starting Git and every helper after each check. Transfers initiated by the user still approve every time, like Git. Tests cover the wrappers (including askpass and attribute round trip), the credentials callback state machine driven the way libgit2 does, the settings inheritance and the task timeout. Co-Authored-By: Claude Fable 5.2 --- GitUpKit/Core/GCCommitSigning.m | 13 +- GitUpKit/Core/GCLiveRepository.m | 3 +- GitUpKit/Core/GCPrivate.h | 4 + GitUpKit/Core/GCPrivate.m | 14 +- GitUpKit/Core/GCRepository-Tests.m | 327 +++++++++++++++++-- GitUpKit/Core/GCRepository.h | 16 +- GitUpKit/Core/GCRepository.m | 257 ++++++++++----- GitUpKit/Core/GCSubmodule.m | 7 +- GitUpKit/Extensions/GCRepository+Utilities.m | 3 +- 9 files changed, 514 insertions(+), 130 deletions(-) diff --git a/GitUpKit/Core/GCCommitSigning.m b/GitUpKit/Core/GCCommitSigning.m index 76359c4ab..b9f4419c9 100644 --- a/GitUpKit/Core/GCCommitSigning.m +++ b/GitUpKit/Core/GCCommitSigning.m @@ -29,12 +29,6 @@ return repository.workingDirectoryPath ?: repository.repositoryPath; } -static NSError* _TaskFailureError(NSString* message, int status, NSData* stdoutData, NSData* stderrData) { - NSString* output = _StringFromTaskOutput(stderrData.length ? stderrData : stdoutData); - NSString* reason = output.length ? [NSString stringWithFormat:@": %@", output] : @""; - return GCNewError(kGCErrorCode_Generic, [NSString stringWithFormat:@"%@ exited with non-zero status (%i)%@", message, status, reason]); -} - static GCTask* _TaskWithPATH(GCRepository* repository, NSString* executablePath, NSString* path) { GCTask* task = [[GCTask alloc] initWithExecutablePath:executablePath]; task.currentDirectoryPath = _RepositoryTaskDirectoryPath(repository); @@ -87,8 +81,7 @@ static BOOL _ShouldSSHSignCommit(GCRepository* repository, BOOL* shouldSign, NSE } static NSString* _CommitSigningPATH(GCRepository* repository, NSError** error) { - NSString* shell = NSProcessInfo.processInfo.environment[@"SHELL"]; - NSString* path = [repository getPATHUsingShell:shell error:error] ?: [repository getPATHUsingShell:@"/bin/sh" error:error]; + NSString* path = [repository getUserPATH:error]; // Deliberately not cached: refreshed once per signing operation XLOG_DEBUG_CHECK(path); return path; } @@ -107,7 +100,7 @@ static BOOL _LooksLikeInlineSSHKey(NSString* key) { } if (status != 0) { if (error) { - *error = _TaskFailureError(@"SSH signing default key command", status, stdoutData, stderrData); + *error = GCNewErrorFromTaskFailure(@"SSH signing default key command", status, stdoutData, stderrData); } return nil; } @@ -204,7 +197,7 @@ static BOOL _LooksLikeInlineSSHKey(NSString* key) { } if (status != 0) { if (error) { - *error = _TaskFailureError(@"SSH commit signer", status, stdoutData, stderrData); + *error = GCNewErrorFromTaskFailure(@"SSH commit signer", status, stdoutData, stderrData); } return nil; } diff --git a/GitUpKit/Core/GCLiveRepository.m b/GitUpKit/Core/GCLiveRepository.m index f5e6282d1..61eec0584 100644 --- a/GitUpKit/Core/GCLiveRepository.m +++ b/GitUpKit/Core/GCLiveRepository.m @@ -841,8 +841,7 @@ - (void)performOperationInBackgroundWithReason:(NSString*)reason } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ GCRepository* repository = [[GCRepository alloc] initWithExistingLocalRepository:self.repositoryPath error:&error]; - repository.delegate = self.delegate; - repository.credentialHelperMode = self.credentialHelperMode; + [repository inheritRemoteSettingsFromRepository:self]; __block BOOL success = repository && operationBlock(repository, &error); dispatch_async(dispatch_get_main_queue(), ^{ if (success) { diff --git a/GitUpKit/Core/GCPrivate.h b/GitUpKit/Core/GCPrivate.h index b915102fc..232af7d41 100644 --- a/GitUpKit/Core/GCPrivate.h +++ b/GitUpKit/Core/GCPrivate.h @@ -139,6 +139,7 @@ extern int git_submodule_foreach_block(git_repository* repo, int (^block)(git_su @interface GCTask : NSObject @property(nonatomic, readonly) NSString* executablePath; @property(nonatomic) NSTimeInterval executionTimeOut; // Default is 0.0 i.e. no timeout +@property(nonatomic, readonly) BOOL timedOut; // Whether the last run was ended by the timeout @property(nonatomic, copy) NSDictionary* additionalEnvironment; @property(nonatomic, copy) NSString* currentDirectoryPath; @property(nonatomic) BOOL fallBackToDefaultInterpreter; @@ -146,6 +147,8 @@ extern int git_submodule_foreach_block(git_repository* repo, int (^block)(git_su - (BOOL)runWithArguments:(NSArray*)arguments stdin:(NSData*)stdin stdout:(NSData**)stdout stderr:(NSData**)stderr exitStatus:(int*)exitStatus error:(NSError**)error; // Returns NO if "exitStatus" is NULL and executable exits with a non-zero status @end +extern NSError* GCNewErrorFromTaskFailure(NSString* message, int status, NSData* stdoutData, NSData* stderrData); // "{message} exited with non-zero status ({status}): {stderr or stdout}" + #endif @interface GCObject () { @@ -266,6 +269,7 @@ extern int git_submodule_foreach_block(git_repository* repo, int (^block)(git_su - (BOOL)exportBlobWithOID:(const git_oid*)oid toPath:(NSString*)path error:(NSError**)error; #if !TARGET_OS_IPHONE - (NSString*)getPATHUsingShell:(NSString*)shell error:(NSError**)error; +- (NSString*)getUserPATH:(NSError**)error; // PATH from the user's login shell, falling back to /bin/sh - Not cached #endif @end diff --git a/GitUpKit/Core/GCPrivate.m b/GitUpKit/Core/GCPrivate.m index c0d527f2e..674c9cd03 100644 --- a/GitUpKit/Core/GCPrivate.m +++ b/GitUpKit/Core/GCPrivate.m @@ -21,6 +21,12 @@ #if !TARGET_OS_IPHONE +NSError* GCNewErrorFromTaskFailure(NSString* message, int status, NSData* stdoutData, NSData* stderrData) { + NSString* output = [[[NSString alloc] initWithData:(stderrData.length ? stderrData : stdoutData) encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + NSString* reason = output.length ? [NSString stringWithFormat:@": %@", output] : @""; + return GCNewError(kGCErrorCode_Generic, [NSString stringWithFormat:@"%@ exited with non-zero status (%i)%@", message, status, reason]); +} + @implementation GCTask { NSFileHandle* _outFileHandle; NSMutableData* _outData; @@ -36,7 +42,8 @@ - (instancetype)initWithExecutablePath:(NSString*)path { } - (void)_timer:(NSTimer*)timer { - [(NSTask*)timer.userInfo terminate]; + _timedOut = YES; + [(NSTask*)timer.userInfo terminate]; // This signals the whole process group i.e. also the processes started by the executable [(NSTask*)timer.userInfo interrupt]; } @@ -74,6 +81,7 @@ - (BOOL)_runWithDefaultInterpreter:(BOOL)useSH arguments:(NSArray*)arguments std NSPipe* errorPipe = nil; NSTimer* timer = nil; + _timedOut = NO; NSTask* task = [[NSTask alloc] init]; task.launchPath = useSH ? @"/bin/sh" : _executablePath; NSMutableDictionary* environment = [[NSMutableDictionary alloc] initWithDictionary:[[NSProcessInfo processInfo] environment]]; @@ -140,9 +148,11 @@ - (BOOL)_runWithDefaultInterpreter:(BOOL)useSH arguments:(NSArray*)arguments std *stderr = _errorData; } [task waitUntilExit]; - while (_outFileHandle || _errorFileHandle) { + while ((_outFileHandle || _errorFileHandle) && !_timedOut) { // After a timeout don't wait on the pipes: a process started by the executable that survived (signals ignored, or left the process group) may hold them open CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0, true); } + _outFileHandle = nil; + _errorFileHandle = nil; [[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleDataAvailableNotification object:nil]; [timer invalidate]; if (exitStatus) { diff --git a/GitUpKit/Core/GCRepository-Tests.m b/GitUpKit/Core/GCRepository-Tests.m index bbe57c8bd..c4983acea 100644 --- a/GitUpKit/Core/GCRepository-Tests.m +++ b/GitUpKit/Core/GCRepository-Tests.m @@ -19,6 +19,28 @@ #import "GCTestCase.h" +#import + +// Stands in for the application: counts the requests for credentials and answers with fixed ones, or declines +@interface GCCredentialsTestDelegate : NSObject +@property(nonatomic) BOOL providesCredentials; +@property(nonatomic) NSUInteger requestCount; +@end + +@implementation GCCredentialsTestDelegate + +- (BOOL)repository:(GCRepository*)repository requiresPlainTextAuthenticationForURL:(NSURL*)url user:(NSString*)user username:(NSString**)username password:(NSString**)password { + _requestCount += 1; + if (!_providesCredentials) { + return NO; + } + *username = @"delegate"; + *password = @"dialog"; + return YES; +} + +@end + @implementation GCTests (GCRepository) - (void)testPrecompose { @@ -105,68 +127,313 @@ - (void)testInitialization { XCTAssertFalse([[GCRepository alloc] initWithNewLocalRepository:self.repository.workingDirectoryPath bare:NO error:NULL]); } -- (void)testCredentialHelpers { - NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; - GCRepository* repository = [self createLocalRepositoryAtPath:path bare:NO]; - - // Create a fake credential helper that logs every invocation and answers "get" requests - NSString* helperDirectory = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; - XCTAssertTrue([[NSFileManager defaultManager] createDirectoryAtPath:helperDirectory withIntermediateDirectories:YES attributes:nil error:NULL]); - NSString* logPath = [helperDirectory stringByAppendingPathComponent:@"log"]; - NSString* helperPath = [helperDirectory stringByAppendingPathComponent:@"helper"]; +// Installs a fake credential helper that logs every request it gets and answers "get" ones - Returns the directory holding the helper and its "log" +- (NSString*)_installCredentialHelperInRepository:(GCRepository*)repository { + NSString* directory = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; + XCTAssertTrue([[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:NULL]); + NSString* logPath = [directory stringByAppendingPathComponent:@"log"]; + NSString* helperPath = [directory stringByAppendingPathComponent:@"helper"]; NSString* helperScript = [NSString stringWithFormat:@"#!/bin/sh\n" "echo \"[$1] interactive=${GCM_INTERACTIVE:-default}\" >> \"%@\"\n" "cat >> \"%@\"\n" "if [ \"$1\" = \"get\" ]; then\n" - " printf 'username=bot\\npassword=s3cret\\n'\n" + " printf 'username=bot\\npassword=s3cret\\npassword_expiry_utc=4102444800\\n'\n" "fi\n", logPath, logPath]; XCTAssertTrue([helperScript writeToFile:helperPath atomically:YES encoding:NSUTF8StringEncoding error:NULL]); XCTAssertTrue([[NSFileManager defaultManager] setAttributes:@{NSFilePosixPermissions : @(0755)} ofItemAtPath:helperPath error:NULL]); - // Isolate from the developer's own configuration: reset inherited helpers and make sure "path=" isn't sent + // Isolate from the developer's own configuration: reset inherited helpers, never send "path=" nor use an askpass program // Note: git only runs helpers as "git credential-" unless given an absolute path or a "!" command XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"--add", @"credential.helper", @"", nil])); // Commas must be shielded from the macro + XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"--add", @"credential.helper", helperPath, nil])); XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"credential.useHttpPath", @"false", nil])); + return directory; +} + +// Returns what the fake credential helper logged since the last call, or nil if it wasn't run +- (NSString*)_takeCredentialHelperLog:(NSString*)directory { + NSString* logPath = [directory stringByAppendingPathComponent:@"log"]; + NSString* log = [NSString stringWithContentsOfFile:logPath encoding:NSUTF8StringEncoding error:NULL]; + [[NSFileManager defaultManager] removeItemAtPath:logPath error:NULL]; + return log; +} + +static NSUInteger _CountOccurrences(NSString* string, NSString* substring) { + return string ? [string componentsSeparatedByString:substring].count - 1 : 0; +} + +- (void)testCredentialHelpers { + NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; + GCRepository* repository = [self createLocalRepositoryAtPath:path bare:NO]; // No helper configured: no credentials + XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"--add", @"credential.helper", @"", nil])); NSURL* url = [NSURL URLWithString:@"https://example.invalid/some/repo.git"]; NSString* username = nil; NSString* password = nil; + NSString* description = nil; NSError* error = nil; - XCTAssertFalse([repository fillCredentialsForURL:url user:nil allowInteraction:NO username:&username password:&password error:&error]); + XCTAssertFalse([repository fillCredentialsForURL:url user:nil allowInteraction:NO username:&username password:&password description:&description error:&error]); XCTAssertNotNil(error); XCTAssertNil(username); XCTAssertNil(password); - - // Fake helper configured: fill, approve and reject - XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"--add", @"credential.helper", helperPath, nil])); - XCTAssertTrue([repository fillCredentialsForURL:url user:@"hint" allowInteraction:NO username:&username password:&password error:&error]); + XCTAssertNil(description); + + // ...and Git must not fall back to asking by itself through an askpass program, even when the helpers are allowed to interact + NSString* askpassDirectory = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; + XCTAssertTrue([[NSFileManager defaultManager] createDirectoryAtPath:askpassDirectory withIntermediateDirectories:YES attributes:nil error:NULL]); + NSString* askpassPath = [askpassDirectory stringByAppendingPathComponent:@"askpass"]; + NSString* askpassMarkerPath = [askpassDirectory stringByAppendingPathComponent:@"asked"]; + NSString* askpassScript = [NSString stringWithFormat:@"#!/bin/sh\ntouch \"%@\"\necho answer\n", askpassMarkerPath]; + XCTAssertTrue([askpassScript writeToFile:askpassPath atomically:YES encoding:NSUTF8StringEncoding error:NULL]); + XCTAssertTrue([[NSFileManager defaultManager] setAttributes:@{NSFilePosixPermissions : @(0755)} ofItemAtPath:askpassPath error:NULL]); + XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"core.askPass", askpassPath, nil])); + XCTAssertFalse([repository fillCredentialsForURL:url user:nil allowInteraction:YES username:&username password:&password description:&description error:&error]); + XCTAssertFalse([repository fillCredentialsForURL:url user:nil allowInteraction:NO username:&username password:&password description:&description error:&error]); + XCTAssertFalse([[NSFileManager defaultManager] fileExistsAtPath:askpassMarkerPath]); + XCTAssertTrue([[NSFileManager defaultManager] removeItemAtPath:askpassDirectory error:NULL]); + + // URLs credentials can't be described for are refused instead of raising + NSURL* nilURL = nil; + XCTAssertFalse([repository fillCredentialsForURL:nilURL user:nil allowInteraction:NO username:&username password:&password description:&description error:&error]); + XCTAssertFalse([repository fillCredentialsForURL:[NSURL fileURLWithPath:@"/some/repo.git"] user:nil allowInteraction:NO username:&username password:&password description:&description error:&error]); + XCTAssertFalse([repository approveCredentialsWithDescription:@"" error:&error]); + + // Fake helper configured: fill in both modes + NSString* helperDirectory = [self _installCredentialHelperInRepository:repository]; + XCTAssertTrue([repository fillCredentialsForURL:url user:@"hint" allowInteraction:NO username:&username password:&password description:&description error:&error]); XCTAssertEqualObjects(username, @"bot"); XCTAssertEqualObjects(password, @"s3cret"); - XCTAssertTrue([repository fillCredentialsForURL:url user:@"hint" allowInteraction:YES username:&username password:&password error:&error]); + XCTAssertTrue([description containsString:@"host=example.invalid\n"]); + XCTAssertTrue([description containsString:@"password=s3cret\n"]); + NSString* log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertEqualObjects(log, @"[get] interactive=never\nprotocol=https\nhost=example.invalid\nusername=hint\n"); // Told not to prompt, and no "path=" as credential.useHttpPath is off + XCTAssertTrue([repository fillCredentialsForURL:url user:@"hint" allowInteraction:YES username:&username password:&password description:&description error:&error]); XCTAssertEqualObjects(username, @"bot"); XCTAssertEqualObjects(password, @"s3cret"); - XCTAssertTrue([repository approveCredentialsForURL:url username:username password:password error:&error]); - XCTAssertTrue([repository rejectCredentialsForURL:url username:username password:password error:&error]); + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertEqualObjects(log, @"[get] interactive=default\nprotocol=https\nhost=example.invalid\nusername=hint\n"); + + // Approve and reject hand the complete description back, including attributes other than the username and password + BOOL hasExpiry = [description containsString:@"password_expiry_utc=4102444800\n"]; // Only passed along by Git 2.40 and later + XCTAssertTrue([repository approveCredentialsWithDescription:description error:&error]); + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertTrue([log hasPrefix:@"[store] interactive=never\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n"], @"%@", log); + XCTAssertEqual([log containsString:@"password_expiry_utc=4102444800\n"], hasExpiry); + XCTAssertTrue([repository rejectCredentialsWithDescription:description error:&error]); + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertTrue([log hasPrefix:@"[erase] interactive=never\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n"], @"%@", log); + XCTAssertEqual([log containsString:@"password_expiry_utc=4102444800\n"], hasExpiry); - NSString* log = [NSString stringWithContentsOfFile:logPath encoding:NSUTF8StringEncoding error:NULL]; - XCTAssertNotNil(log); - NSArray* expectedEntries = @[ - @"[get] interactive=never\nprotocol=https\nhost=example.invalid\nusername=hint\n", // Non-interactive mode tells helpers not to prompt - @"[get] interactive=default\nprotocol=https\nhost=example.invalid\nusername=hint\n", - @"[store] interactive=never\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n", - @"[erase] interactive=never\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n" - ]; - for (NSString* entry in expectedEntries) { - XCTAssertTrue([log containsString:entry], @"Missing \"%@\" in helper log:\n%@", entry, log); + XCTAssertTrue([[NSFileManager defaultManager] removeItemAtPath:helperDirectory error:NULL]); + [self destroyLocalRepository:repository]; +} + +// Ask for credentials the way libgit2 does during a transfer +- (int)_requestCredentialsForURL:(NSString*)url withCallbacks:(git_remote_callbacks*)callbacks username:(NSString**)username password:(NSString**)password { + git_credential* credential = NULL; + int status = callbacks->credentials(&credential, url.UTF8String, NULL, GIT_CREDENTIAL_USERPASS_PLAINTEXT, callbacks->payload); + *username = nil; + *password = nil; + if (status == GIT_OK) { + git_credential_userpass_plaintext* plaintext = (git_credential_userpass_plaintext*)credential; + *username = [NSString stringWithUTF8String:plaintext->username]; + *password = [NSString stringWithUTF8String:plaintext->password]; + git_credential_free(credential); } - XCTAssertFalse([log containsString:@"path="]); // credential.useHttpPath is off + return status; +} + +- (void)testCredentialHelpersDuringTransfers { + NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; + GCRepository* repository = [self createLocalRepositoryAtPath:path bare:NO]; + NSString* helperDirectory = [self _installCredentialHelperInRepository:repository]; + GCCredentialsTestDelegate* delegate = [[GCCredentialsTestDelegate alloc] init]; + delegate.providesCredentials = YES; + repository.delegate = delegate; + // Unique hosts as the credentials approved so far are remembered for the lifetime of the process + NSString* unique = [[NSUUID UUID].UUIDString lowercaseString]; + NSString* url = [NSString stringWithFormat:@"https://%@.example.invalid/some/repo.git", unique]; + NSString* automaticURL = [NSString stringWithFormat:@"https://automatic-%@.example.invalid/some/repo.git", unique]; + git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT; + NSString* username; + NSString* password; + NSString* log; + + // Disabled, which is the default: only the delegate is asked + XCTAssertEqual(repository.credentialHelperMode, kGCCredentialHelperMode_Disabled); + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:url withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"delegate"); + XCTAssertEqualObjects(password, @"dialog"); + XCTAssertEqual(delegate.requestCount, 1); + [repository didFinishRemoteTransferWithURL:nil success:YES]; + XCTAssertNil([self _takeCredentialHelperLog:helperDirectory]); + + // Interactive: the helpers are asked first and their credentials approved once the transfer succeeds + repository.credentialHelperMode = kGCCredentialHelperMode_Interactive; + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:url withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"bot"); + XCTAssertEqualObjects(password, @"s3cret"); + XCTAssertEqual(delegate.requestCount, 1); + [repository didFinishRemoteTransferWithURL:nil success:YES]; + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertEqual(_CountOccurrences(log, @"[get] interactive=default\n"), 1); + XCTAssertEqual(_CountOccurrences(log, @"[store]"), 1); + XCTAssertEqual(_CountOccurrences(log, @"[erase]"), 0); + + // ...and approved again after each successful transfer, like Git does + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:url withCallbacks:&callbacks username:&username password:&password], GIT_OK); + [repository didFinishRemoteTransferWithURL:nil success:YES]; + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertEqual(_CountOccurrences(log, @"[store]"), 1); + + // Being asked again means the credentials were refused: the helpers are told, not asked a second time, and the delegate takes over + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:url withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"bot"); + XCTAssertEqual([self _requestCredentialsForURL:url withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"delegate"); + XCTAssertEqual(delegate.requestCount, 2); + delegate.providesCredentials = NO; + XCTAssertEqual([self _requestCredentialsForURL:url withCallbacks:&callbacks username:&username password:&password], GIT_EUSER); + XCTAssertEqual(delegate.requestCount, 3); + [repository didFinishRemoteTransferWithURL:nil success:YES]; // Whatever worked in the end didn't come from the helpers + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertEqual(_CountOccurrences(log, @"[get]"), 1); + XCTAssertEqual(_CountOccurrences(log, @"[erase]"), 1); + XCTAssertEqual(_CountOccurrences(log, @"[store]"), 0); + delegate.providesCredentials = YES; + + // A transfer failing for another reason neither approves nor rejects + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:url withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"bot"); + [repository didFinishRemoteTransferWithURL:nil success:NO]; + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertEqual(_CountOccurrences(log, @"[get]"), 1); + XCTAssertEqual(_CountOccurrences(log, @"[store]"), 0); + XCTAssertEqual(_CountOccurrences(log, @"[erase]"), 0); + + // Like Git, helpers aren't involved in password authentication over SSH + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:@"ssh://example.invalid/some/repo.git" withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"delegate"); + [repository didFinishRemoteTransferWithURL:nil success:YES]; + XCTAssertNil([self _takeCredentialHelperLog:helperDirectory]); + + // Non-interactive: the delegate is asked first and the helpers aren't run if it has credentials that work + repository.credentialHelperMode = kGCCredentialHelperMode_NonInteractive; + delegate.requestCount = 0; + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:automaticURL withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"delegate"); + [repository didFinishRemoteTransferWithURL:nil success:YES]; + XCTAssertNil([self _takeCredentialHelperLog:helperDirectory]); + + // ...the helpers come next if these are refused, and are told not to prompt + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:automaticURL withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"delegate"); + XCTAssertEqual([self _requestCredentialsForURL:automaticURL withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"bot"); + XCTAssertEqual(delegate.requestCount, 2); + [repository didFinishRemoteTransferWithURL:nil success:YES]; + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertEqual(_CountOccurrences(log, @"[get] interactive=never\n"), 1); + XCTAssertEqual(_CountOccurrences(log, @"[store] interactive=never\n"), 1); + + // ...or if the delegate has none - This time the same credentials aren't approved again + delegate.providesCredentials = NO; + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:automaticURL withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"bot"); + [repository didFinishRemoteTransferWithURL:nil success:YES]; + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertEqual(_CountOccurrences(log, @"[get]"), 1); + XCTAssertEqual(_CountOccurrences(log, @"[store]"), 0); + + // ...until they have been rejected in between + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:automaticURL withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqual([self _requestCredentialsForURL:automaticURL withCallbacks:&callbacks username:&username password:&password], GIT_EUSER); + [repository didFinishRemoteTransferWithURL:nil success:NO]; + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertEqual(_CountOccurrences(log, @"[erase]"), 1); + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:automaticURL withCallbacks:&callbacks username:&username password:&password], GIT_OK); + [repository didFinishRemoteTransferWithURL:nil success:YES]; + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertEqual(_CountOccurrences(log, @"[store]"), 1); + + // Without a delegate the helpers are all there is + repository.delegate = nil; + [repository setRemoteCallbacks:&callbacks]; + XCTAssertEqual([self _requestCredentialsForURL:automaticURL withCallbacks:&callbacks username:&username password:&password], GIT_OK); + XCTAssertEqualObjects(username, @"bot"); + XCTAssertEqual([self _requestCredentialsForURL:automaticURL withCallbacks:&callbacks username:&username password:&password], GIT_PASSTHROUGH); + [repository didFinishRemoteTransferWithURL:nil success:NO]; + [self _takeCredentialHelperLog:helperDirectory]; XCTAssertTrue([[NSFileManager defaultManager] removeItemAtPath:helperDirectory error:NULL]); [self destroyLocalRepository:repository]; } +- (void)testInheritRemoteSettings { + NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; + GCRepository* repository = [self createLocalRepositoryAtPath:path bare:NO]; + GCCredentialsTestDelegate* delegate = [[GCCredentialsTestDelegate alloc] init]; + repository.delegate = delegate; + repository.credentialHelperMode = kGCCredentialHelperMode_Interactive; + + GCRepository* other = [[GCRepository alloc] initWithExistingLocalRepository:path error:NULL]; + XCTAssertNotNil(other); + XCTAssertNil(other.delegate); + XCTAssertEqual(other.credentialHelperMode, kGCCredentialHelperMode_Disabled); + [other inheritRemoteSettingsFromRepository:repository]; + XCTAssertEqual(other.delegate, delegate); + XCTAssertEqual(other.credentialHelperMode, kGCCredentialHelperMode_Interactive); + + [self destroyLocalRepository:repository]; +} + +// A timed out task must not keep waiting on a process it started that survived and still holds its pipes (e.g. a credential helper started by git) +- (void)_testTaskTimeout { + GCTask* task = [[GCTask alloc] initWithExecutablePath:@"/bin/sh"]; + task.executionTimeOut = 1.0; + int status = 0; + NSData* stdoutData; + NSData* stderrData; + CFAbsoluteTime time = CFAbsoluteTimeGetCurrent(); + NSArray* arguments = @[ @"-c", @"(trap '' TERM INT; exec sleep 15) & wait" ]; // The background process ignores the signals ending the shell and holds on to its pipes + XCTAssertTrue([task runWithArguments:arguments stdin:nil stdout:&stdoutData stderr:&stderrData exitStatus:&status error:NULL]); + XCTAssertLessThan(CFAbsoluteTimeGetCurrent() - time, 10.0); + XCTAssertTrue(task.timedOut); + XCTAssertNotEqual(status, 0); + + // Not timing out leaves everything as before + arguments = @[ @"-c", @"echo done" ]; + XCTAssertTrue([task runWithArguments:arguments stdin:nil stdout:&stdoutData stderr:&stderrData exitStatus:&status error:NULL]); + XCTAssertFalse(task.timedOut); + XCTAssertEqual(status, 0); + XCTAssertEqualObjects([[NSString alloc] initWithData:stdoutData encoding:NSUTF8StringEncoding], @"done\n"); +} + +- (void)testTaskTimeout { + [self _testTaskTimeout]; + + // Same from a background thread, which is where transfers run + dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [self _testTaskTimeout]; + dispatch_semaphore_signal(semaphore); + }); + XCTAssertEqual(dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC)), 0); +} + - (void)testPathForHookWithName { NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]; diff --git a/GitUpKit/Core/GCRepository.h b/GitUpKit/Core/GCRepository.h index 1c02eb6b4..835db8939 100644 --- a/GitUpKit/Core/GCRepository.h +++ b/GitUpKit/Core/GCRepository.h @@ -42,8 +42,8 @@ typedef NS_ENUM(NSUInteger, GCFileMode) { typedef NS_ENUM(NSUInteger, GCCredentialHelperMode) { kGCCredentialHelperMode_Disabled = 0, // Never run the Git credential helpers (default) - kGCCredentialHelperMode_NonInteractive, // Run the helpers but forbid them from prompting the user (e.g. for automatic remote checks) - kGCCredentialHelperMode_Interactive // Run the helpers and let them prompt the user if they need to (e.g. Git Credential Manager) + kGCCredentialHelperMode_NonInteractive, // For automatic transfers (e.g. remote checks): the delegate is asked first, then the helpers which are told not to prompt the user + kGCCredentialHelperMode_Interactive // For transfers initiated by the user: the helpers are asked first and may prompt the user if they need to (e.g. Git Credential Manager), then the delegate }; @class GCRepository; @@ -61,7 +61,7 @@ typedef NS_ENUM(NSUInteger, GCCredentialHelperMode) { /// Walks up the file system to find the repository the given URL is contained in. Returns nil and sets the error if no repository is found. + (NSURL *)repositoryURLContainingURL:(NSURL *)url error:(NSError **)error; @property(nonatomic, weak) id delegate; -@property(nonatomic) GCCredentialHelperMode credentialHelperMode; // Whether HTTPS transfers consult the Git credential helpers configured through "credential.helper" before asking the delegate (macOS only) +@property(nonatomic) GCCredentialHelperMode credentialHelperMode; // Whether HTTP(S) transfers consult the Git credential helpers configured through "credential.helper" in addition to the delegate (macOS only) @property(nonatomic, readonly) NSString* repositoryPath; @property(nonatomic, readonly) NSString* workingDirectoryPath; // nil for a bare repository @property(nonatomic, readonly, getter=isReadOnly) BOOL readOnly; @@ -73,6 +73,8 @@ typedef NS_ENUM(NSUInteger, GCCredentialHelperMode) { - (instancetype)initWithNewLocalRepository:(NSString*)path bare:(BOOL)bare error:(NSError**)error; // git init {path} - (instancetype)initWithNewLocalRepository:(NSString*)path bare:(BOOL)bare defaultBranchName:(NSString*)defaultBranchName error:(NSError**)error; +- (void)inheritRemoteSettingsFromRepository:(GCRepository*)repository; // Copies the delegate and credential helper mode - Use on repositories opened on behalf of another one e.g. its submodules + - (BOOL)cleanupState:(NSError**)error; // Do NOT use on a bare repository - (BOOL)checkPathNotIgnored:(NSString*)path error:(NSError**)error; @@ -91,8 +93,10 @@ typedef NS_ENUM(NSUInteger, GCCredentialHelperMode) { - (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardInput:(NSString*)standardInput error:(NSError**)error; // Silently ignores non-existing hooks // Git credential helpers as configured through "credential.helper" - See git-credential(1) -- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction:(BOOL)allowInteraction username:(NSString**)username password:(NSString**)password error:(NSError**)error; // "git credential fill" - Returns NO if no helper provided credentials -- (BOOL)approveCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error; // "git credential approve" -- (BOOL)rejectCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error; // "git credential reject" +// The "description" returned along with the credentials is Git's complete answer, which may carry more than the username and password (e.g. an expiration date or a refresh token): +// it must be handed back unchanged once it's known whether the credentials work so the helpers can store or discard them +- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction:(BOOL)allowInteraction username:(NSString**)username password:(NSString**)password description:(NSString**)description error:(NSError**)error; // "git credential fill" - Returns NO if no helper provided credentials +- (BOOL)approveCredentialsWithDescription:(NSString*)description error:(NSError**)error; // "git credential approve" - The credentials were accepted +- (BOOL)rejectCredentialsWithDescription:(NSString*)description error:(NSError**)error; // "git credential reject" - The credentials were refused #endif @end diff --git a/GitUpKit/Core/GCRepository.m b/GitUpKit/Core/GCRepository.m index 4fe752399..4a497d37b 100644 --- a/GitUpKit/Core/GCRepository.m +++ b/GitUpKit/Core/GCRepository.m @@ -20,6 +20,7 @@ #import #import #if !TARGET_OS_IPHONE +#import #import #import #endif @@ -102,10 +103,9 @@ @implementation GCRepository { BOOL _didTrySSHAgent; NSMutableArray* _privateKeyList; NSUInteger _privateKeyIndex; - BOOL _didTryCredentialHelper; - NSURL* _helperCredentialsURL; // Set while credentials obtained from a Git credential helper are in use for the current transfer - NSString* _helperCredentialsUsername; - NSString* _helperCredentialsPassword; + BOOL _didTryCredentialHelpers; + BOOL _didAskDelegateForCredentials; + NSString* _helperCredentials; // Description of the credentials obtained from the Git credential helpers while they are in use for the current transfer #endif BOOL _hasFetchProgressDelegate; @@ -380,12 +380,17 @@ - (NSString*)getPATHUsingShell:(NSString*)shell error:(NSError**)error { return [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; } -// Resolve the user's PATH through their login shell (once per process) so that tools installed outside /usr/bin are found -- (NSString*)_userPATH:(NSError**)error { +// Resolve the user's PATH through their login shell so that tools installed outside /usr/bin are found +- (NSString*)getUserPATH:(NSError**)error { + return [self getPATHUsingShell:NSProcessInfo.processInfo.environment[@"SHELL"] error:error] ?: [self getPATHUsingShell:@"/bin/sh" error:error]; +} + +// Same but resolved only once per process +- (NSString*)_cachedUserPATH:(NSError**)error { static NSString* cachedPATH = nil; @synchronized([GCRepository class]) { if (cachedPATH == nil) { - cachedPATH = [self getPATHUsingShell:NSProcessInfo.processInfo.environment[@"SHELL"] error:error] ?: [self getPATHUsingShell:@"/bin/sh" error:error]; + cachedPATH = [self getUserPATH:error]; XLOG_DEBUG_CHECK(cachedPATH); } return cachedPATH; @@ -395,7 +400,7 @@ - (NSString*)_userPATH:(NSError**)error { - (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardInput:(NSString*)standardInput error:(NSError**)error { NSString* path = [self pathForHookWithName:name]; if (path) { - NSString* cachedPATH = [self _userPATH:error]; + NSString* cachedPATH = [self _cachedUserPATH:error]; CFAbsoluteTime time = CFAbsoluteTimeGetCurrent(); GCTask* task = [[GCTask alloc] initWithExecutablePath:path]; @@ -428,7 +433,6 @@ - (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardIn #pragma mark - Credential Helpers -// Serialize a credential description in the format expected by "git credential" - See git-credential(1) "INPUT/OUTPUT FORMAT" static BOOL _AppendCredentialAttribute(NSMutableString* string, NSString* key, NSString* value) { if (value == nil) { return YES; // Nothing to add (an empty value is a legitimate attribute though) @@ -440,7 +444,11 @@ static BOOL _AppendCredentialAttribute(NSMutableString* string, NSString* key, N return YES; } -static NSData* _CredentialDescriptionData(NSURL* url, NSString* username, NSString* password) { +// Serialize a credential query in the format expected by "git credential" - See git-credential(1) "INPUT/OUTPUT FORMAT" +static NSData* _CredentialQueryData(NSURL* url, NSString* username) { + if (!url.scheme.length || !url.host.length) { + return nil; // Not something credentials can be looked up for - Also covers nil, which NSURLComponents refuses with an exception + } NSURLComponents* components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO]; components.user = nil; // Passed separately as "username" below components.password = nil; @@ -451,26 +459,15 @@ static BOOL _AppendCredentialAttribute(NSMutableString* string, NSString* key, N return nil; } NSMutableString* string = [[NSMutableString alloc] init]; - if (!_AppendCredentialAttribute(string, @"url", urlString) || !_AppendCredentialAttribute(string, @"username", username) || !_AppendCredentialAttribute(string, @"password", password)) { + if (!_AppendCredentialAttribute(string, @"url", urlString) || !_AppendCredentialAttribute(string, @"username", username)) { return nil; } [string appendString:@"\n"]; // Blank line terminates the description return [string dataUsingEncoding:NSUTF8StringEncoding]; } -- (void)_clearHelperCredentials { - _helperCredentialsURL = nil; - _helperCredentialsUsername = nil; - _helperCredentialsPassword = nil; -} - -- (BOOL)_runCredentialCommand:(NSString*)command url:(NSURL*)url username:(NSString*)username password:(NSString*)password allowInteraction:(BOOL)allowInteraction output:(NSData**)output error:(NSError**)error { - NSData* input = _CredentialDescriptionData(url, username, password); - if (input == nil) { - GC_SET_GENERIC_ERROR(@"Unable to describe credentials for \"%@\"", url); - return NO; - } - NSString* path = [self _userPATH:NULL] ?: NSProcessInfo.processInfo.environment[@"PATH"]; +- (BOOL)_runCredentialCommand:(NSString*)command input:(NSData*)input allowInteraction:(BOOL)allowInteraction output:(NSData**)output error:(NSError**)error { + NSString* path = [self _cachedUserPATH:NULL] ?: NSProcessInfo.processInfo.environment[@"PATH"]; if (!path.length) { path = @"/usr/bin:/bin:/usr/sbin:/sbin"; } @@ -480,12 +477,13 @@ - (BOOL)_runCredentialCommand:(NSString*)command url:(NSURL*)url username:(NSStr task.currentDirectoryPath = self.workingDirectoryPath ?: self.repositoryPath; // So that repository-local configuration applies NSMutableDictionary* environment = [[NSMutableDictionary alloc] init]; environment[@"PATH"] = path; - environment[@"GIT_TERMINAL_PROMPT"] = @"0"; // Never block waiting on a terminal that doesn't exist + // Git itself must never prompt, neither on a terminal that doesn't exist nor through an askpass program: the delegate is there for that + environment[@"GIT_TERMINAL_PROMPT"] = @"0"; + environment[@"GIT_ASKPASS"] = @"/usr/bin/false"; // Takes precedence over "core.askPass" and SSH_ASKPASS if (allowInteraction) { task.executionTimeOut = 120.0; // Helpers may legitimately prompt the user (e.g. Git Credential Manager), but never hang forever } else { - // GIT_TERMINAL_PROMPT only silences Git itself: also tell helpers with their own UI to stay quiet - environment[@"GIT_ASKPASS"] = @"/usr/bin/false"; // Takes precedence over SSH_ASKPASS and fails any prompt Git would make through an askpass program + // Also tell helpers that have their own UI to stay quiet environment[@"GCM_INTERACTIVE"] = @"never"; // Git Credential Manager environment[@"GIT_CONFIG_COUNT"] = @"1"; // Equivalent of "-c credential.interactive=false", also seen by helpers that read Git configuration environment[@"GIT_CONFIG_KEY_0"] = @"credential.interactive"; @@ -494,15 +492,21 @@ - (BOOL)_runCredentialCommand:(NSString*)command url:(NSURL*)url username:(NSStr } task.additionalEnvironment = environment; int status; - NSData* stdoutData; - NSData* stderrData; - if (![task runWithArguments:@[ @"git", @"credential", command ] stdin:input stdout:&stdoutData stderr:&stderrData exitStatus:&status error:error]) { + NSData* stdoutData = nil; + NSData* stderrData = nil; + // Only capture the output when it matters: a helper leaving a background process behind (which can happen when storing) would keep these pipes open and stall the task until it times out + if (![task runWithArguments:@[ @"git", @"credential", command ] stdin:input stdout:(output ? &stdoutData : NULL) stderr:(output ? &stderrData : NULL) exitStatus:&status error:error]) { return NO; } XLOG_VERBOSE(@"Executed 'git credential %@' in %.3f seconds", command, CFAbsoluteTimeGetCurrent() - time); + if (task.timedOut) { + GC_SET_GENERIC_ERROR(@"'git credential %@' timed out", command); + return NO; + } if (status != 0) { - NSString* string = [[[NSString alloc] initWithData:(stderrData.length ? stderrData : stdoutData) encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; - GC_SET_GENERIC_ERROR(@"'git credential %@' exited with non-zero status (%i)%@%@", command, status, string.length ? @": " : @"", string ?: @""); + if (error) { + *error = GCNewErrorFromTaskFailure([NSString stringWithFormat:@"'git credential %@'", command], status, stdoutData, stderrData); + } return NO; } if (output) { @@ -511,9 +515,14 @@ - (BOOL)_runCredentialCommand:(NSString*)command url:(NSURL*)url username:(NSStr return YES; } -- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction:(BOOL)allowInteraction username:(NSString**)username password:(NSString**)password error:(NSError**)error { +- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction:(BOOL)allowInteraction username:(NSString**)username password:(NSString**)password description:(NSString**)description error:(NSError**)error { + NSData* input = _CredentialQueryData(url, (user.length ? user : url.user)); + if (input == nil) { + GC_SET_GENERIC_ERROR(@"Unable to describe credentials for \"%@\"", url); + return NO; + } NSData* output; - if (![self _runCredentialCommand:@"fill" url:url username:(url.user.length ? url.user : user) password:nil allowInteraction:allowInteraction output:&output error:error]) { + if (![self _runCredentialCommand:@"fill" input:input allowInteraction:allowInteraction output:&output error:error]) { return NO; } NSString* string = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding]; @@ -537,17 +546,85 @@ - (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction: return NO; } XLOG_VERBOSE(@"Obtained credentials for \"%@\" from Git credential helper", url); - *username = outUsername; - *password = outPassword; + if (username) { + *username = outUsername; + } + if (password) { + *password = outPassword; + } + if (description) { + *description = string; + } return YES; } -- (BOOL)approveCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error { - return [self _runCredentialCommand:@"approve" url:url username:username password:password allowInteraction:NO output:NULL error:error]; +// Hand the complete description back so the helpers also get the attributes they attached to the credentials (expiration date, refresh token, their own state...) +- (BOOL)_reportCredentialsWithDescription:(NSString*)description command:(NSString*)command error:(NSError**)error { + NSString* string = [description stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; + if (!string.length || ([string rangeOfString:@"\0"].location != NSNotFound)) { + GC_SET_GENERIC_ERROR(@"Invalid credentials description"); + return NO; + } + NSData* input = [[string stringByAppendingString:@"\n\n"] dataUsingEncoding:NSUTF8StringEncoding]; // Blank line terminates the description + return [self _runCredentialCommand:command input:input allowInteraction:NO output:NULL error:error]; +} + +- (BOOL)approveCredentialsWithDescription:(NSString*)description error:(NSError**)error { + return [self _reportCredentialsWithDescription:description command:@"approve" error:error]; +} + +- (BOOL)rejectCredentialsWithDescription:(NSString*)description error:(NSError**)error { + return [self _reportCredentialsWithDescription:description command:@"reject" error:error]; +} + +// Remember (by digest, not to keep secrets around) which credentials the helpers were already told are good. +// Git approves after every successful operation and so do transfers initiated by the user, which also keeps helpers like "cache" from expiring credentials still in use, +// but automatic transfers would start Git and every helper again after each check just to repeat it. +static NSMutableSet* _ApprovedCredentialDigests(void) { + static NSMutableSet* set = nil; + static dispatch_once_t once; + dispatch_once(&once, ^{ + set = [[NSMutableSet alloc] init]; + }); + return set; } -- (BOOL)rejectCredentialsForURL:(NSURL*)url username:(NSString*)username password:(NSString*)password error:(NSError**)error { - return [self _runCredentialCommand:@"reject" url:url username:username password:password allowInteraction:NO output:NULL error:error]; +static NSData* _CredentialsDigest(NSString* description) { + NSData* data = [description dataUsingEncoding:NSUTF8StringEncoding]; + unsigned char digest[CC_SHA256_DIGEST_LENGTH]; + CC_SHA256(data.bytes, (CC_LONG)data.length, digest); + return [NSData dataWithBytes:digest length:sizeof(digest)]; +} + +- (void)_approveHelperCredentials { + NSMutableSet* digests = _ApprovedCredentialDigests(); + NSData* digest = _CredentialsDigest(_helperCredentials); + if (_credentialHelperMode == kGCCredentialHelperMode_NonInteractive) { + @synchronized(digests) { + if ([digests containsObject:digest]) { + return; + } + } + } + NSError* error; + if ([self approveCredentialsWithDescription:_helperCredentials error:&error]) { + @synchronized(digests) { + [digests addObject:digest]; + } + } else { + XLOG_WARNING(@"Failed approving credentials with Git credential helpers: %@", error.localizedDescription); + } +} + +- (void)_rejectHelperCredentials { + NSMutableSet* digests = _ApprovedCredentialDigests(); + @synchronized(digests) { + [digests removeObject:_CredentialsDigest(_helperCredentials)]; + } + NSError* error; + if (![self rejectCredentialsWithDescription:_helperCredentials error:&error]) { + XLOG_WARNING(@"Failed rejecting credentials with Git credential helpers: %@", error.localizedDescription); + } } #endif @@ -597,6 +674,11 @@ - (instancetype)initWithClonedRepositoryFromURL:(NSURL*)url toPath:(NSString*)pa #pragma mark Remote Callbacks +- (void)inheritRemoteSettingsFromRepository:(GCRepository*)repository { + self.delegate = repository.delegate; + self.credentialHelperMode = repository.credentialHelperMode; +} + - (void)willStartRemoteTransferWithURL:(NSURL*)url { if ([_delegate respondsToSelector:@selector(repository:willStartTransferWithURL:)]) { if ([NSThread isMainThread]) { @@ -611,14 +693,11 @@ - (void)willStartRemoteTransferWithURL:(NSURL*)url { - (void)didFinishRemoteTransferWithURL:(NSURL*)url success:(BOOL)success { #if !TARGET_OS_IPHONE - if (_helperCredentialsPassword) { - if (success) { // Let the helpers cache the credentials like Git does - On failure Git only rejects credentials the server refused, which is handled when libgit2 asks for credentials again - NSError* error; - if (![self approveCredentialsForURL:_helperCredentialsURL username:_helperCredentialsUsername password:_helperCredentialsPassword error:&error]) { - XLOG_WARNING(@"Failed approving credentials with Git credential helpers: %@", error.localizedDescription); - } + if (_helperCredentials) { + if (success) { // Let the helpers store the credentials like Git does - On failure Git only rejects credentials the server refused, which is handled when libgit2 asks for credentials again + [self _approveHelperCredentials]; } - [self _clearHelperCredentials]; + _helperCredentials = nil; } #endif if ([_delegate respondsToSelector:@selector(repository:didFinishTransferWithURL:success:)]) { @@ -632,6 +711,42 @@ - (void)didFinishRemoteTransferWithURL:(NSURL*)url success:(BOOL)success { } } +#if !TARGET_OS_IPHONE + +// Ask the Git credential helpers, once per transfer - Runs on the transfer thread so the UI stays responsive while helpers work +static BOOL _FillCredentialsUsingHelpers(GCRepository* repository, git_cred** cred, const char* url, const char* user) { + if ((repository.credentialHelperMode == kGCCredentialHelperMode_Disabled) || repository->_didTryCredentialHelpers) { + return NO; + } + NSURL* helperURL = url ? GCURLFromGitURL([NSString stringWithUTF8String:url]) : nil; + NSString* scheme = helperURL.scheme.lowercaseString; + if (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) { + return NO; // Like Git, don't involve the helpers in anything else e.g. password authentication over SSH - Also covers URLs that can't be parsed + } + repository->_didTryCredentialHelpers = YES; + NSString* username = nil; + NSString* password = nil; + NSString* description = nil; + NSError* error; + if (![repository fillCredentialsForURL:helperURL + user:(user ? [NSString stringWithUTF8String:user] : nil) + allowInteraction:(repository.credentialHelperMode == kGCCredentialHelperMode_Interactive) + username:&username + password:&password + description:&description + error:&error]) { + XLOG_VERBOSE(@"Git credential helpers did not provide credentials for \"%s\": %@", url, error.localizedDescription); + return NO; + } + if (git_cred_userpass_plaintext_new(cred, username.UTF8String, password.UTF8String) != GIT_OK) { + return NO; + } + repository->_helperCredentials = description; + return YES; +} + +#endif + static int _CredentialsCallback(git_cred** cred, const char* url, const char* user, unsigned int allowed_types, void* payload) { GCRepository* repository = (__bridge GCRepository*)payload; if (allowed_types & GIT_CREDTYPE_SSH_KEY) { @@ -703,35 +818,20 @@ static int _CredentialsCallback(git_cred** cred, const char* url, const char* us } } if (allowed_types & GIT_CREDTYPE_USERPASS_PLAINTEXT) { + BOOL hasDelegate = [repository.delegate respondsToSelector:@selector(repository:requiresPlainTextAuthenticationForURL:user:username:password:)]; #if !TARGET_OS_IPHONE - if (repository->_helperCredentialsPassword) { // Being asked again means the server refused what the helpers provided: tell them and move on to the delegate - NSError* error; - if (![repository rejectCredentialsForURL:repository->_helperCredentialsURL username:repository->_helperCredentialsUsername password:repository->_helperCredentialsPassword error:&error]) { - XLOG_WARNING(@"Failed rejecting credentials with Git credential helpers: %@", error.localizedDescription); - } - [repository _clearHelperCredentials]; + if (repository->_helperCredentials) { // Being asked again means the server refused what the helpers provided: tell them and move on + [repository _rejectHelperCredentials]; + repository->_helperCredentials = nil; } - if ((repository.credentialHelperMode != kGCCredentialHelperMode_Disabled) && !repository->_didTryCredentialHelper) { // Runs on the transfer thread so the UI stays responsive while helpers work - repository->_didTryCredentialHelper = YES; - NSURL* helperURL = GCURLFromGitURL([NSString stringWithUTF8String:url]); - NSString* helperUsername = nil; - NSString* helperPassword = nil; - NSError* error; - if ([repository fillCredentialsForURL:helperURL - user:(user ? [NSString stringWithUTF8String:user] : nil) - allowInteraction:(repository.credentialHelperMode == kGCCredentialHelperMode_Interactive) - username:&helperUsername - password:&helperPassword - error:&error]) { - repository->_helperCredentialsURL = helperURL; - repository->_helperCredentialsUsername = helperUsername; - repository->_helperCredentialsPassword = helperPassword; - return git_cred_userpass_plaintext_new(cred, helperUsername.UTF8String, helperPassword.UTF8String); - } - XLOG_VERBOSE(@"Git credential helpers did not provide credentials for \"%s\": %@", url, error.localizedDescription); + // Helpers go first for transfers initiated by the user. Automatic ones ask the delegate first: a helper reading a Keychain item it didn't create + // (e.g. "osxkeychain" with a password saved by the application) makes macOS prompt the user, which nothing here can prevent. + BOOL helpersFirst = (repository.credentialHelperMode == kGCCredentialHelperMode_Interactive) || !hasDelegate || repository->_didAskDelegateForCredentials; + if (helpersFirst && _FillCredentialsUsingHelpers(repository, cred, url, user)) { + return GIT_OK; } #endif - if ([repository.delegate respondsToSelector:@selector(repository:requiresPlainTextAuthenticationForURL:user:username:password:)]) { // Must use sync dispatch + if (hasDelegate) { // Must use sync dispatch __block NSString* username = nil; __block NSString* password = nil; __block BOOL success; @@ -750,9 +850,17 @@ static int _CredentialsCallback(git_cred** cred, const char* url, const char* us password:&password]; }); } +#if !TARGET_OS_IPHONE + repository->_didAskDelegateForCredentials = YES; +#endif if (success) { return git_cred_userpass_plaintext_new(cred, username.UTF8String, password.UTF8String); } +#if !TARGET_OS_IPHONE + if (_FillCredentialsUsingHelpers(repository, cred, url, user)) { // Does nothing if the helpers were already asked + return GIT_OK; + } +#endif return GIT_EUSER; } } @@ -890,8 +998,9 @@ - (void)setRemoteCallbacks:(git_remote_callbacks*)callbacks { _didTrySSHAgent = NO; _privateKeyList = nil; _privateKeyIndex = 0; - _didTryCredentialHelper = NO; - [self _clearHelperCredentials]; + _didTryCredentialHelpers = NO; + _didAskDelegateForCredentials = NO; + _helperCredentials = nil; #endif _hasFetchProgressDelegate = [_delegate respondsToSelector:@selector(repository:updateTransferProgress:transferredBytes:)]; diff --git a/GitUpKit/Core/GCSubmodule.m b/GitUpKit/Core/GCSubmodule.m index c14bbb609..ad1f4d0bb 100644 --- a/GitUpKit/Core/GCSubmodule.m +++ b/GitUpKit/Core/GCSubmodule.m @@ -157,8 +157,7 @@ - (GCSubmodule*)addSubmoduleWithURL:(NSURL*)url atPath:(NSString*)path recursive if (repository == nil) { goto cleanup; } - repository.delegate = self.delegate; - repository.credentialHelperMode = self.credentialHelperMode; + [repository inheritRemoteSettingsFromRepository:self]; remote = [repository lookupRemoteWithName:@"origin" error:error]; if (remote == nil) { goto cleanup; @@ -196,8 +195,7 @@ - (BOOL)initializeSubmodule:(GCSubmodule*)submodule recursive:(BOOL)recursive er if (repository == nil) { return NO; } - repository.delegate = self.delegate; - repository.credentialHelperMode = self.credentialHelperMode; + [repository inheritRemoteSettingsFromRepository:self]; if (![repository initializeAllSubmodules:recursive error:error]) { return NO; } @@ -222,6 +220,7 @@ - (BOOL)initializeAllSubmodules:(BOOL)recursive error:(NSError**)error { if (repository == nil) { return NO; } + [repository inheritRemoteSettingsFromRepository:self]; // Nested submodules may need initializing too if (![repository initializeAllSubmodules:recursive error:error]) { return NO; } diff --git a/GitUpKit/Extensions/GCRepository+Utilities.m b/GitUpKit/Extensions/GCRepository+Utilities.m index a03591f23..ebf299a76 100644 --- a/GitUpKit/Extensions/GCRepository+Utilities.m +++ b/GitUpKit/Extensions/GCRepository+Utilities.m @@ -62,8 +62,7 @@ - (BOOL)_fetchRepository:(GCRepository*)repository recursive:(BOOL)recursive err } for (GCSubmodule* submodule in submodules) { GCRepository* subRepository = [[GCRepository alloc] initWithSubmodule:submodule error:error]; - subRepository.delegate = self.delegate; - subRepository.credentialHelperMode = self.credentialHelperMode; + [subRepository inheritRemoteSettingsFromRepository:self]; if (subRepository == nil) { return NO; } From 8a73388d118472e4bae3cc5dd863d59515e857cf Mon Sep 17 00:00:00 2001 From: David Gasperoni Date: Tue, 10 Nov 2026 00:48:27 +0100 Subject: [PATCH 5/5] Report credential outcomes to helpers configured for a URL path "git credential fill" selects the helpers using the full URL, then drops the path from its answer unless "credential.useHttpPath" is set. Feeding only that answer to a later "approve" or "reject" therefore no longer matched helpers configured for a specific path (credential.https://host/path.helper), which never learned whether their credentials worked. The description returned by -fillCredentialsForURL:... now starts with the URL the credentials are for, followed by Git's answer whose attributes take precedence, so the same helpers are selected again. Co-Authored-By: Claude Fable 5.2 --- GitUpKit/Core/GCRepository-Tests.m | 19 +++++++++++++++++++ GitUpKit/Core/GCRepository.h | 4 ++-- GitUpKit/Core/GCRepository.m | 28 ++++++++++++++-------------- 3 files changed, 35 insertions(+), 16 deletions(-) diff --git a/GitUpKit/Core/GCRepository-Tests.m b/GitUpKit/Core/GCRepository-Tests.m index c4983acea..956c6ae6d 100644 --- a/GitUpKit/Core/GCRepository-Tests.m +++ b/GitUpKit/Core/GCRepository-Tests.m @@ -226,6 +226,25 @@ - (void)testCredentialHelpers { XCTAssertTrue([log hasPrefix:@"[erase] interactive=never\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n"], @"%@", log); XCTAssertEqual([log containsString:@"password_expiry_utc=4102444800\n"], hasExpiry); + // A helper configured for a URL path only is told about the outcome too, although Git's answer doesn't include the path + XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"--unset-all", @"credential.helper", nil])); + XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"--add", @"credential.helper", @"", nil])); + NSString* helperPath = [helperDirectory stringByAppendingPathComponent:@"helper"]; + XCTAssertNotNil(([self runGitCLTWithRepository:repository command:@"config", @"credential.https://example.invalid/scoped/repo.git.helper", helperPath, nil])); + XCTAssertFalse([repository fillCredentialsForURL:url user:nil allowInteraction:NO username:&username password:&password description:&description error:&error]); // Other path + XCTAssertNil([self _takeCredentialHelperLog:helperDirectory]); + NSURL* scopedURL = [NSURL URLWithString:@"https://example.invalid/scoped/repo.git"]; + XCTAssertTrue([repository fillCredentialsForURL:scopedURL user:nil allowInteraction:NO username:&username password:&password description:&description error:&error]); + XCTAssertEqualObjects(username, @"bot"); + XCTAssertFalse([description containsString:@"path="]); + XCTAssertEqual(_CountOccurrences([self _takeCredentialHelperLog:helperDirectory], @"[get]"), 1); + XCTAssertTrue([repository approveCredentialsWithDescription:description error:&error]); + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertTrue([log hasPrefix:@"[store] interactive=never\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n"], @"%@", log); + XCTAssertTrue([repository rejectCredentialsWithDescription:description error:&error]); + log = [self _takeCredentialHelperLog:helperDirectory]; + XCTAssertTrue([log hasPrefix:@"[erase] interactive=never\nprotocol=https\nhost=example.invalid\nusername=bot\npassword=s3cret\n"], @"%@", log); + XCTAssertTrue([[NSFileManager defaultManager] removeItemAtPath:helperDirectory error:NULL]); [self destroyLocalRepository:repository]; } diff --git a/GitUpKit/Core/GCRepository.h b/GitUpKit/Core/GCRepository.h index 835db8939..34bc8cab2 100644 --- a/GitUpKit/Core/GCRepository.h +++ b/GitUpKit/Core/GCRepository.h @@ -93,8 +93,8 @@ typedef NS_ENUM(NSUInteger, GCCredentialHelperMode) { - (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardInput:(NSString*)standardInput error:(NSError**)error; // Silently ignores non-existing hooks // Git credential helpers as configured through "credential.helper" - See git-credential(1) -// The "description" returned along with the credentials is Git's complete answer, which may carry more than the username and password (e.g. an expiration date or a refresh token): -// it must be handed back unchanged once it's known whether the credentials work so the helpers can store or discard them +// The "description" returned along with the credentials is the URL they are for followed by Git's complete answer, which may carry more than the username and password +// (e.g. an expiration date or a refresh token): it must be handed back unchanged once it's known whether the credentials work so the same helpers can store or discard them - (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction:(BOOL)allowInteraction username:(NSString**)username password:(NSString**)password description:(NSString**)description error:(NSError**)error; // "git credential fill" - Returns NO if no helper provided credentials - (BOOL)approveCredentialsWithDescription:(NSString*)description error:(NSError**)error; // "git credential approve" - The credentials were accepted - (BOOL)rejectCredentialsWithDescription:(NSString*)description error:(NSError**)error; // "git credential reject" - The credentials were refused diff --git a/GitUpKit/Core/GCRepository.m b/GitUpKit/Core/GCRepository.m index 4a497d37b..17338ecbb 100644 --- a/GitUpKit/Core/GCRepository.m +++ b/GitUpKit/Core/GCRepository.m @@ -444,26 +444,22 @@ static BOOL _AppendCredentialAttribute(NSMutableString* string, NSString* key, N return YES; } -// Serialize a credential query in the format expected by "git credential" - See git-credential(1) "INPUT/OUTPUT FORMAT" -static NSData* _CredentialQueryData(NSURL* url, NSString* username) { +// The "url" attribute of a credential description in the format expected by "git credential" - See git-credential(1) "INPUT/OUTPUT FORMAT" +static NSString* _CredentialURLAttribute(NSURL* url) { if (!url.scheme.length || !url.host.length) { return nil; // Not something credentials can be looked up for - Also covers nil, which NSURLComponents refuses with an exception } NSURLComponents* components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO]; - components.user = nil; // Passed separately as "username" below + components.user = nil; // Passed separately as "username" components.password = nil; components.query = nil; components.fragment = nil; NSString* urlString = components.URL.absoluteString; - if (!urlString.length) { - return nil; - } NSMutableString* string = [[NSMutableString alloc] init]; - if (!_AppendCredentialAttribute(string, @"url", urlString) || !_AppendCredentialAttribute(string, @"username", username)) { + if (!urlString.length || !_AppendCredentialAttribute(string, @"url", urlString)) { return nil; } - [string appendString:@"\n"]; // Blank line terminates the description - return [string dataUsingEncoding:NSUTF8StringEncoding]; + return string; } - (BOOL)_runCredentialCommand:(NSString*)command input:(NSData*)input allowInteraction:(BOOL)allowInteraction output:(NSData**)output error:(NSError**)error { @@ -516,13 +512,15 @@ - (BOOL)_runCredentialCommand:(NSString*)command input:(NSData*)input allowInter } - (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction:(BOOL)allowInteraction username:(NSString**)username password:(NSString**)password description:(NSString**)description error:(NSError**)error { - NSData* input = _CredentialQueryData(url, (user.length ? user : url.user)); - if (input == nil) { + NSString* urlAttribute = _CredentialURLAttribute(url); + NSMutableString* query = [urlAttribute mutableCopy]; + if ((query == nil) || !_AppendCredentialAttribute(query, @"username", (user.length ? user : url.user))) { GC_SET_GENERIC_ERROR(@"Unable to describe credentials for \"%@\"", url); return NO; } + [query appendString:@"\n"]; // Blank line terminates the description NSData* output; - if (![self _runCredentialCommand:@"fill" input:input allowInteraction:allowInteraction output:&output error:error]) { + if (![self _runCredentialCommand:@"fill" input:[query dataUsingEncoding:NSUTF8StringEncoding] allowInteraction:allowInteraction output:&output error:error]) { return NO; } NSString* string = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding]; @@ -553,12 +551,14 @@ - (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction: *password = outPassword; } if (description) { - *description = string; + // Keep the URL in front of Git's answer, whose attributes then take precedence: unless "credential.useHttpPath" is set the answer has no path anymore, + // but Git needs it again to find the helpers configured for that path when the outcome is reported + *description = [urlAttribute stringByAppendingString:string]; } return YES; } -// Hand the complete description back so the helpers also get the attributes they attached to the credentials (expiration date, refresh token, their own state...) +// Hand the complete description back so the same helpers are selected and also get the attributes they attached to the credentials (expiration date, refresh token, their own state...) - (BOOL)_reportCredentialsWithDescription:(NSString*)description command:(NSString*)command error:(NSError**)error { NSString* string = [description stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; if (!string.length || ([string rangeOfString:@"\0"].location != NSNotFound)) {