diff --git a/GitUp/Application/Document.m b/GitUp/Application/Document.m index f3131a31..de3ed428 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]) { @@ -1925,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/GCCommitSigning.m b/GitUpKit/Core/GCCommitSigning.m index 76359c4a..b9f4419c 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 c3ebade7..61eec058 100644 --- a/GitUpKit/Core/GCLiveRepository.m +++ b/GitUpKit/Core/GCLiveRepository.m @@ -841,7 +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 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 b915102f..232af7d4 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 c0d527f2..674c9cd0 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 b96a0aff..956c6ae6 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,6 +127,332 @@ - (void)testInitialization { XCTAssertFalse([[GCRepository alloc] initWithNewLocalRepository:self.repository.workingDirectoryPath bare:NO error:NULL]); } +// 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\\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, 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 description:&description error:&error]); + XCTAssertNotNil(error); + XCTAssertNil(username); + XCTAssertNil(password); + 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([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"); + 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); + + // 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]; +} + +// 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); + } + 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 cf7240f0..34bc8cab 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, // 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; @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 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; @@ -66,6 +73,8 @@ typedef NS_ENUM(NSUInteger, GCFileMode) { - (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; @@ -82,5 +91,12 @@ 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) +// 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 #endif @end diff --git a/GitUpKit/Core/GCRepository.m b/GitUpKit/Core/GCRepository.m index 8ee27942..17338ecb 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,6 +103,9 @@ @implementation GCRepository { BOOL _didTrySSHAgent; NSMutableArray* _privateKeyList; NSUInteger _privateKeyIndex; + 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; @@ -376,14 +380,27 @@ - (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 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; + } +} + +- (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardInput:(NSString*)standardInput error:(NSError**)error { + NSString* path = [self pathForHookWithName:name]; + if (path) { + NSString* cachedPATH = [self _cachedUserPATH:error]; CFAbsoluteTime time = CFAbsoluteTimeGetCurrent(); GCTask* task = [[GCTask alloc] initWithExecutablePath:path]; @@ -414,6 +431,202 @@ - (BOOL)runHookWithName:(NSString*)name arguments:(NSArray*)arguments standardIn return YES; } +#pragma mark - Credential Helpers + +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) + } + 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; +} + +// 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" + components.password = nil; + components.query = nil; + components.fragment = nil; + NSString* urlString = components.URL.absoluteString; + NSMutableString* string = [[NSMutableString alloc] init]; + if (!urlString.length || !_AppendCredentialAttribute(string, @"url", urlString)) { + return nil; + } + return string; +} + +- (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"; + } + + 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 + NSMutableDictionary* environment = [[NSMutableDictionary alloc] init]; + environment[@"PATH"] = path; + // 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 { + // 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"; + environment[@"GIT_CONFIG_VALUE_0"] = @"false"; + task.executionTimeOut = 30.0; + } + task.additionalEnvironment = environment; + int status; + 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) { + if (error) { + *error = GCNewErrorFromTaskFailure([NSString stringWithFormat:@"'git credential %@'", command], status, stdoutData, stderrData); + } + return NO; + } + if (output) { + *output = stdoutData; + } + return YES; +} + +- (BOOL)fillCredentialsForURL:(NSURL*)url user:(NSString*)user allowInteraction:(BOOL)allowInteraction username:(NSString**)username password:(NSString**)password description:(NSString**)description error:(NSError**)error { + 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:[query dataUsingEncoding:NSUTF8StringEncoding] allowInteraction:allowInteraction 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 == 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; + } + XLOG_VERBOSE(@"Obtained credentials for \"%@\" from Git credential helper", url); + if (username) { + *username = outUsername; + } + if (password) { + *password = outPassword; + } + if (description) { + // 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 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)) { + 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; +} + +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 #if DEBUG @@ -461,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]) { @@ -474,6 +692,14 @@ - (void)willStartRemoteTransferWithURL:(NSURL*)url { } - (void)didFinishRemoteTransferWithURL:(NSURL*)url success:(BOOL)success { +#if !TARGET_OS_IPHONE + 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]; + } + _helperCredentials = nil; + } +#endif if ([_delegate respondsToSelector:@selector(repository:didFinishTransferWithURL:success:)]) { if ([NSThread isMainThread]) { [_delegate repository:self didFinishTransferWithURL:url success:success]; @@ -485,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) { @@ -556,7 +818,20 @@ static int _CredentialsCallback(git_cred** cred, const char* url, const char* us } } if (allowed_types & GIT_CREDTYPE_USERPASS_PLAINTEXT) { - if ([repository.delegate respondsToSelector:@selector(repository:requiresPlainTextAuthenticationForURL:user:username:password:)]) { // Must use sync dispatch + BOOL hasDelegate = [repository.delegate respondsToSelector:@selector(repository:requiresPlainTextAuthenticationForURL:user:username:password:)]; +#if !TARGET_OS_IPHONE + if (repository->_helperCredentials) { // Being asked again means the server refused what the helpers provided: tell them and move on + [repository _rejectHelperCredentials]; + repository->_helperCredentials = nil; + } + // 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 (hasDelegate) { // Must use sync dispatch __block NSString* username = nil; __block NSString* password = nil; __block BOOL success; @@ -575,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; } } @@ -715,6 +998,9 @@ - (void)setRemoteCallbacks:(git_remote_callbacks*)callbacks { _didTrySSHAgent = NO; _privateKeyList = nil; _privateKeyIndex = 0; + _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 6a5d144f..ad1f4d0b 100644 --- a/GitUpKit/Core/GCSubmodule.m +++ b/GitUpKit/Core/GCSubmodule.m @@ -157,7 +157,7 @@ - (GCSubmodule*)addSubmoduleWithURL:(NSURL*)url atPath:(NSString*)path recursive if (repository == nil) { goto cleanup; } - repository.delegate = self.delegate; + [repository inheritRemoteSettingsFromRepository:self]; remote = [repository lookupRemoteWithName:@"origin" error:error]; if (remote == nil) { goto cleanup; @@ -195,7 +195,7 @@ - (BOOL)initializeSubmodule:(GCSubmodule*)submodule recursive:(BOOL)recursive er if (repository == nil) { return NO; } - repository.delegate = self.delegate; + [repository inheritRemoteSettingsFromRepository:self]; if (![repository initializeAllSubmodules:recursive error:error]) { return NO; } @@ -220,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 153ed7df..ebf299a7 100644 --- a/GitUpKit/Extensions/GCRepository+Utilities.m +++ b/GitUpKit/Extensions/GCRepository+Utilities.m @@ -62,7 +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 inheritRemoteSettingsFromRepository:self]; if (subRepository == nil) { return NO; }