Skip to content

Commit

Permalink
Add support for macOS enterprise deployable default settings (#1811)
Browse files Browse the repository at this point in the history
Similar to the functionality to set default settings for GCM via the
Registry on Windows, we implement support on macOS using the Apple
preferences system. Preferences can be deployed as payloads via MDM
configuration profiles.

The domain for GCM is `git-credential-manager` and configuration
settings should take the form of a dictionary under the `configuration`
key.
  • Loading branch information
mjcheetham authored Jan 28, 2025
2 parents 4c32c09 + b05317f commit b62021f
Show file tree
Hide file tree
Showing 9 changed files with 428 additions and 27 deletions.
33 changes: 32 additions & 1 deletion docs/enterprise-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,38 @@ those of the [Git configuration][config] settings.
The type of each registry key can be either `REG_SZ` (string) or `REG_DWORD`
(integer).

## macOS/Linux
## macOS

Default settings values come from macOS's preferences system. Configuration
profiles can be deployed to devices using a compatible Mobile Device Management
(MDM) solution.

Configuration for Git Credential Manager must take the form of a dictionary, set
for the domain `git-credential-manager` under the key `configuration`. For
example:

```shell
defaults write git-credential-manager configuration -dict-add <key> <value>
```

..where `<key>` is the name of the settings from the [Git configuration][config]
reference, and `<value>` is the desired value.

All values in the `configuration` dictionary must be strings. For boolean values
use `true` or `false`, and for integer values use the number in string form.

To read the current configuration:

```console
$ defaults read git-credential-manager configuration
{
<key1> = <value1>;
...
<keyN> = <valueN>;
}
```

## Linux

Default configuration setting stores has not been implemented.

Expand Down
66 changes: 66 additions & 0 deletions src/shared/Core.Tests/Interop/MacOS/MacOSPreferencesTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
using GitCredentialManager.Interop.MacOS;
using static GitCredentialManager.Tests.TestUtils;

namespace GitCredentialManager.Tests.Interop.MacOS;

public class MacOSPreferencesTests
{
private const string TestAppId = "com.example.gcm-test";
private const string DefaultsPath = "/usr/bin/defaults";

[MacOSFact]
public async Task MacOSPreferences_ReadPreferences()
{
try
{
await SetupTestPreferencesAsync();

var pref = new MacOSPreferences(TestAppId);

// Exists
string stringValue = pref.GetString("myString");
int? intValue = pref.GetInteger("myInt");
IDictionary<string, string> dictValue = pref.GetDictionary("myDict");

Assert.NotNull(stringValue);
Assert.Equal("this is a string", stringValue);
Assert.NotNull(intValue);
Assert.Equal(42, intValue);
Assert.NotNull(dictValue);
Assert.Equal(2, dictValue.Count);
Assert.Equal("value1", dictValue["dict-k1"]);
Assert.Equal("value2", dictValue["dict-k2"]);

// Does not exist
string missingString = pref.GetString("missingString");
int? missingInt = pref.GetInteger("missingInt");
IDictionary<string, string> missingDict = pref.GetDictionary("missingDict");

Assert.Null(missingString);
Assert.Null(missingInt);
Assert.Null(missingDict);
}
finally
{
await CleanupTestPreferencesAsync();
}
}

private static async Task SetupTestPreferencesAsync()
{
// Using the defaults command set up preferences for the test app
await RunCommandAsync(DefaultsPath, $"write {TestAppId} myString \"this is a string\"");
await RunCommandAsync(DefaultsPath, $"write {TestAppId} myInt -int 42");
await RunCommandAsync(DefaultsPath, $"write {TestAppId} myDict -dict dict-k1 value1 dict-k2 value2");
}

private static async Task CleanupTestPreferencesAsync()
{
// Delete the test app preferences
// defaults delete com.example.gcm-test
await RunCommandAsync(DefaultsPath, $"delete {TestAppId}");
}
}
2 changes: 1 addition & 1 deletion src/shared/Core/CommandContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public CommandContext()
gitPath,
FileSystem.GetCurrentDirectory()
);
Settings = new Settings(Environment, Git);
Settings = new MacOSSettings(Environment, Git, Trace);
}
else if (PlatformUtils.IsLinux())
{
Expand Down
1 change: 1 addition & 0 deletions src/shared/Core/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public static class Constants

public const string GcmDataDirectoryName = ".gcm";

public const string MacOSBundleId = "git-credential-manager";
public static readonly Guid DevBoxPartnerId = new("e3171dd9-9a5f-e5be-b36c-cc7c4f3f3bcf");

/// <summary>
Expand Down
33 changes: 8 additions & 25 deletions src/shared/Core/Interop/MacOS/MacOSKeychain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -302,35 +302,18 @@ private static string GetStringAttribute(IntPtr dict, IntPtr key)
return null;
}

IntPtr buffer = IntPtr.Zero;
try
if (CFDictionaryGetValueIfPresent(dict, key, out IntPtr value) && value != IntPtr.Zero)
{
if (CFDictionaryGetValueIfPresent(dict, key, out IntPtr value) && value != IntPtr.Zero)
if (CFGetTypeID(value) == CFStringGetTypeID())
{
if (CFGetTypeID(value) == CFStringGetTypeID())
{
int stringLength = (int)CFStringGetLength(value);
int bufferSize = stringLength + 1;
buffer = Marshal.AllocHGlobal(bufferSize);
if (CFStringGetCString(value, buffer, bufferSize, CFStringEncoding.kCFStringEncodingUTF8))
{
return Marshal.PtrToStringAuto(buffer, stringLength);
}
}

if (CFGetTypeID(value) == CFDataGetTypeID())
{
int length = CFDataGetLength(value);
IntPtr ptr = CFDataGetBytePtr(value);
return Marshal.PtrToStringAuto(ptr, length);
}
return CFStringToString(value);
}
}
finally
{
if (buffer != IntPtr.Zero)

if (CFGetTypeID(value) == CFDataGetTypeID())
{
Marshal.FreeHGlobal(buffer);
int length = CFDataGetLength(value);
IntPtr ptr = CFDataGetBytePtr(value);
return Marshal.PtrToStringAuto(ptr, length);
}
}

Expand Down
96 changes: 96 additions & 0 deletions src/shared/Core/Interop/MacOS/MacOSPreferences.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using GitCredentialManager.Interop.MacOS.Native;
using static GitCredentialManager.Interop.MacOS.Native.CoreFoundation;

namespace GitCredentialManager.Interop.MacOS;

public class MacOSPreferences
{
private readonly string _appId;

public MacOSPreferences(string appId)
{
EnsureArgument.NotNull(appId, nameof(appId));

_appId = appId;
}

/// <summary>
/// Return a <see cref="string"/> typed value from the app preferences.
/// </summary>
/// <param name="key">Preference name.</param>
/// <exception cref="InvalidOperationException">Thrown if the preference is not a string.</exception>
/// <returns>
/// <see cref="string"/> or null if the preference with the given key does not exist.
/// </returns>
public string GetString(string key)
{
return TryGet(key, CFStringToString, out string value)
? value
: null;
}

/// <summary>
/// Return a <see cref="int"/> typed value from the app preferences.
/// </summary>
/// <param name="key">Preference name.</param>
/// <exception cref="InvalidOperationException">Thrown if the preference is not an integer.</exception>
/// <returns>
/// <see cref="int"/> or null if the preference with the given key does not exist.
/// </returns>
public int? GetInteger(string key)
{
return TryGet(key, CFNumberToInt32, out int value)
? value
: null;
}

/// <summary>
/// Return a <see cref="IDictionary{TKey,TValue}"/> typed value from the app preferences.
/// </summary>
/// <param name="key">Preference name.</param>
/// <exception cref="InvalidOperationException">Thrown if the preference is not a dictionary.</exception>
/// <returns>
/// <see cref="IDictionary{TKey,TValue}"/> or null if the preference with the given key does not exist.
/// </returns>
public IDictionary<string, string> GetDictionary(string key)
{
return TryGet(key, CFDictionaryToDictionary, out IDictionary<string, string> value)
? value
: null;
}

private bool TryGet<T>(string key, Func<IntPtr, T> converter, out T value)
{
IntPtr cfValue = IntPtr.Zero;
IntPtr keyPtr = IntPtr.Zero;
IntPtr appIdPtr = CreateAppIdPtr();

try
{
keyPtr = CFStringCreateWithCString(IntPtr.Zero, key, CFStringEncoding.kCFStringEncodingUTF8);
cfValue = CFPreferencesCopyAppValue(keyPtr, appIdPtr);

if (cfValue == IntPtr.Zero)
{
value = default;
return false;
}

value = converter(cfValue);
return true;
}
finally
{
if (cfValue != IntPtr.Zero) CFRelease(cfValue);
if (keyPtr != IntPtr.Zero) CFRelease(keyPtr);
if (appIdPtr != IntPtr.Zero) CFRelease(appIdPtr);
}
}

private IntPtr CreateAppIdPtr()
{
return CFStringCreateWithCString(IntPtr.Zero, _appId, CFStringEncoding.kCFStringEncodingUTF8);
}
}
67 changes: 67 additions & 0 deletions src/shared/Core/Interop/MacOS/MacOSSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;

namespace GitCredentialManager.Interop.MacOS
{
/// <summary>
/// Reads settings from Git configuration, environment variables, and defaults from the system.
/// </summary>
public class MacOSSettings : Settings
{
private readonly ITrace _trace;

public MacOSSettings(IEnvironment environment, IGit git, ITrace trace)
: base(environment, git)
{
EnsureArgument.NotNull(trace, nameof(trace));
_trace = trace;

PlatformUtils.EnsureMacOS();
}

protected override bool TryGetExternalDefault(string section, string scope, string property, out string value)
{
value = null;

try
{
// Check for app default preferences for our bundle ID.
// Defaults can be deployed system administrators via device management profiles.
var prefs = new MacOSPreferences(Constants.MacOSBundleId);
IDictionary<string, string> dict = prefs.GetDictionary("configuration");

if (dict is null)
{
// No configuration key exists
return false;
}

// Wrap the raw dictionary in one configured with the Git configuration key comparer.
// This means we can use the same key comparison rules as Git in our configuration plist dict,
// That is, sections and names are insensitive to case, but the scope is case-sensitive.
var config = new Dictionary<string, string>(dict, GitConfigurationKeyComparer.Instance);

string name = string.IsNullOrWhiteSpace(scope)
? $"{section}.{property}"
: $"{section}.{scope}.{property}";

if (!config.TryGetValue(name, out value))
{
// No property exists
return false;
}

_trace.WriteLine($"Default setting found in app preferences: {name}={value}");
return true;
}
catch (Exception ex)
{
// Reading defaults is not critical to the operation of the application
// so we can ignore any errors and just log the failure.
_trace.WriteLine("Failed to read default setting from app preferences.");
_trace.WriteException(ex);
return false;
}
}
}
}
Loading

0 comments on commit b62021f

Please sign in to comment.