Skip to content

Commit b62021f

Browse files
authored
Add support for macOS enterprise deployable default settings (#1811)
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.
2 parents 4c32c09 + b05317f commit b62021f

File tree

9 files changed

+428
-27
lines changed

9 files changed

+428
-27
lines changed

docs/enterprise-config.md

+32-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,38 @@ those of the [Git configuration][config] settings.
5555
The type of each registry key can be either `REG_SZ` (string) or `REG_DWORD`
5656
(integer).
5757

58-
## macOS/Linux
58+
## macOS
59+
60+
Default settings values come from macOS's preferences system. Configuration
61+
profiles can be deployed to devices using a compatible Mobile Device Management
62+
(MDM) solution.
63+
64+
Configuration for Git Credential Manager must take the form of a dictionary, set
65+
for the domain `git-credential-manager` under the key `configuration`. For
66+
example:
67+
68+
```shell
69+
defaults write git-credential-manager configuration -dict-add <key> <value>
70+
```
71+
72+
..where `<key>` is the name of the settings from the [Git configuration][config]
73+
reference, and `<value>` is the desired value.
74+
75+
All values in the `configuration` dictionary must be strings. For boolean values
76+
use `true` or `false`, and for integer values use the number in string form.
77+
78+
To read the current configuration:
79+
80+
```console
81+
$ defaults read git-credential-manager configuration
82+
{
83+
<key1> = <value1>;
84+
...
85+
<keyN> = <valueN>;
86+
}
87+
```
88+
89+
## Linux
5990

6091
Default configuration setting stores has not been implemented.
6192

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
using System.Collections.Generic;
2+
using System.Threading.Tasks;
3+
using Xunit;
4+
using GitCredentialManager.Interop.MacOS;
5+
using static GitCredentialManager.Tests.TestUtils;
6+
7+
namespace GitCredentialManager.Tests.Interop.MacOS;
8+
9+
public class MacOSPreferencesTests
10+
{
11+
private const string TestAppId = "com.example.gcm-test";
12+
private const string DefaultsPath = "/usr/bin/defaults";
13+
14+
[MacOSFact]
15+
public async Task MacOSPreferences_ReadPreferences()
16+
{
17+
try
18+
{
19+
await SetupTestPreferencesAsync();
20+
21+
var pref = new MacOSPreferences(TestAppId);
22+
23+
// Exists
24+
string stringValue = pref.GetString("myString");
25+
int? intValue = pref.GetInteger("myInt");
26+
IDictionary<string, string> dictValue = pref.GetDictionary("myDict");
27+
28+
Assert.NotNull(stringValue);
29+
Assert.Equal("this is a string", stringValue);
30+
Assert.NotNull(intValue);
31+
Assert.Equal(42, intValue);
32+
Assert.NotNull(dictValue);
33+
Assert.Equal(2, dictValue.Count);
34+
Assert.Equal("value1", dictValue["dict-k1"]);
35+
Assert.Equal("value2", dictValue["dict-k2"]);
36+
37+
// Does not exist
38+
string missingString = pref.GetString("missingString");
39+
int? missingInt = pref.GetInteger("missingInt");
40+
IDictionary<string, string> missingDict = pref.GetDictionary("missingDict");
41+
42+
Assert.Null(missingString);
43+
Assert.Null(missingInt);
44+
Assert.Null(missingDict);
45+
}
46+
finally
47+
{
48+
await CleanupTestPreferencesAsync();
49+
}
50+
}
51+
52+
private static async Task SetupTestPreferencesAsync()
53+
{
54+
// Using the defaults command set up preferences for the test app
55+
await RunCommandAsync(DefaultsPath, $"write {TestAppId} myString \"this is a string\"");
56+
await RunCommandAsync(DefaultsPath, $"write {TestAppId} myInt -int 42");
57+
await RunCommandAsync(DefaultsPath, $"write {TestAppId} myDict -dict dict-k1 value1 dict-k2 value2");
58+
}
59+
60+
private static async Task CleanupTestPreferencesAsync()
61+
{
62+
// Delete the test app preferences
63+
// defaults delete com.example.gcm-test
64+
await RunCommandAsync(DefaultsPath, $"delete {TestAppId}");
65+
}
66+
}

src/shared/Core/CommandContext.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ public CommandContext()
131131
gitPath,
132132
FileSystem.GetCurrentDirectory()
133133
);
134-
Settings = new Settings(Environment, Git);
134+
Settings = new MacOSSettings(Environment, Git, Trace);
135135
}
136136
else if (PlatformUtils.IsLinux())
137137
{

src/shared/Core/Constants.cs

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public static class Constants
1616

1717
public const string GcmDataDirectoryName = ".gcm";
1818

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

2122
/// <summary>

src/shared/Core/Interop/MacOS/MacOSKeychain.cs

+8-25
Original file line numberDiff line numberDiff line change
@@ -302,35 +302,18 @@ private static string GetStringAttribute(IntPtr dict, IntPtr key)
302302
return null;
303303
}
304304

305-
IntPtr buffer = IntPtr.Zero;
306-
try
305+
if (CFDictionaryGetValueIfPresent(dict, key, out IntPtr value) && value != IntPtr.Zero)
307306
{
308-
if (CFDictionaryGetValueIfPresent(dict, key, out IntPtr value) && value != IntPtr.Zero)
307+
if (CFGetTypeID(value) == CFStringGetTypeID())
309308
{
310-
if (CFGetTypeID(value) == CFStringGetTypeID())
311-
{
312-
int stringLength = (int)CFStringGetLength(value);
313-
int bufferSize = stringLength + 1;
314-
buffer = Marshal.AllocHGlobal(bufferSize);
315-
if (CFStringGetCString(value, buffer, bufferSize, CFStringEncoding.kCFStringEncodingUTF8))
316-
{
317-
return Marshal.PtrToStringAuto(buffer, stringLength);
318-
}
319-
}
320-
321-
if (CFGetTypeID(value) == CFDataGetTypeID())
322-
{
323-
int length = CFDataGetLength(value);
324-
IntPtr ptr = CFDataGetBytePtr(value);
325-
return Marshal.PtrToStringAuto(ptr, length);
326-
}
309+
return CFStringToString(value);
327310
}
328-
}
329-
finally
330-
{
331-
if (buffer != IntPtr.Zero)
311+
312+
if (CFGetTypeID(value) == CFDataGetTypeID())
332313
{
333-
Marshal.FreeHGlobal(buffer);
314+
int length = CFDataGetLength(value);
315+
IntPtr ptr = CFDataGetBytePtr(value);
316+
return Marshal.PtrToStringAuto(ptr, length);
334317
}
335318
}
336319

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using GitCredentialManager.Interop.MacOS.Native;
4+
using static GitCredentialManager.Interop.MacOS.Native.CoreFoundation;
5+
6+
namespace GitCredentialManager.Interop.MacOS;
7+
8+
public class MacOSPreferences
9+
{
10+
private readonly string _appId;
11+
12+
public MacOSPreferences(string appId)
13+
{
14+
EnsureArgument.NotNull(appId, nameof(appId));
15+
16+
_appId = appId;
17+
}
18+
19+
/// <summary>
20+
/// Return a <see cref="string"/> typed value from the app preferences.
21+
/// </summary>
22+
/// <param name="key">Preference name.</param>
23+
/// <exception cref="InvalidOperationException">Thrown if the preference is not a string.</exception>
24+
/// <returns>
25+
/// <see cref="string"/> or null if the preference with the given key does not exist.
26+
/// </returns>
27+
public string GetString(string key)
28+
{
29+
return TryGet(key, CFStringToString, out string value)
30+
? value
31+
: null;
32+
}
33+
34+
/// <summary>
35+
/// Return a <see cref="int"/> typed value from the app preferences.
36+
/// </summary>
37+
/// <param name="key">Preference name.</param>
38+
/// <exception cref="InvalidOperationException">Thrown if the preference is not an integer.</exception>
39+
/// <returns>
40+
/// <see cref="int"/> or null if the preference with the given key does not exist.
41+
/// </returns>
42+
public int? GetInteger(string key)
43+
{
44+
return TryGet(key, CFNumberToInt32, out int value)
45+
? value
46+
: null;
47+
}
48+
49+
/// <summary>
50+
/// Return a <see cref="IDictionary{TKey,TValue}"/> typed value from the app preferences.
51+
/// </summary>
52+
/// <param name="key">Preference name.</param>
53+
/// <exception cref="InvalidOperationException">Thrown if the preference is not a dictionary.</exception>
54+
/// <returns>
55+
/// <see cref="IDictionary{TKey,TValue}"/> or null if the preference with the given key does not exist.
56+
/// </returns>
57+
public IDictionary<string, string> GetDictionary(string key)
58+
{
59+
return TryGet(key, CFDictionaryToDictionary, out IDictionary<string, string> value)
60+
? value
61+
: null;
62+
}
63+
64+
private bool TryGet<T>(string key, Func<IntPtr, T> converter, out T value)
65+
{
66+
IntPtr cfValue = IntPtr.Zero;
67+
IntPtr keyPtr = IntPtr.Zero;
68+
IntPtr appIdPtr = CreateAppIdPtr();
69+
70+
try
71+
{
72+
keyPtr = CFStringCreateWithCString(IntPtr.Zero, key, CFStringEncoding.kCFStringEncodingUTF8);
73+
cfValue = CFPreferencesCopyAppValue(keyPtr, appIdPtr);
74+
75+
if (cfValue == IntPtr.Zero)
76+
{
77+
value = default;
78+
return false;
79+
}
80+
81+
value = converter(cfValue);
82+
return true;
83+
}
84+
finally
85+
{
86+
if (cfValue != IntPtr.Zero) CFRelease(cfValue);
87+
if (keyPtr != IntPtr.Zero) CFRelease(keyPtr);
88+
if (appIdPtr != IntPtr.Zero) CFRelease(appIdPtr);
89+
}
90+
}
91+
92+
private IntPtr CreateAppIdPtr()
93+
{
94+
return CFStringCreateWithCString(IntPtr.Zero, _appId, CFStringEncoding.kCFStringEncodingUTF8);
95+
}
96+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
using System;
2+
using System.Collections.Generic;
3+
4+
namespace GitCredentialManager.Interop.MacOS
5+
{
6+
/// <summary>
7+
/// Reads settings from Git configuration, environment variables, and defaults from the system.
8+
/// </summary>
9+
public class MacOSSettings : Settings
10+
{
11+
private readonly ITrace _trace;
12+
13+
public MacOSSettings(IEnvironment environment, IGit git, ITrace trace)
14+
: base(environment, git)
15+
{
16+
EnsureArgument.NotNull(trace, nameof(trace));
17+
_trace = trace;
18+
19+
PlatformUtils.EnsureMacOS();
20+
}
21+
22+
protected override bool TryGetExternalDefault(string section, string scope, string property, out string value)
23+
{
24+
value = null;
25+
26+
try
27+
{
28+
// Check for app default preferences for our bundle ID.
29+
// Defaults can be deployed system administrators via device management profiles.
30+
var prefs = new MacOSPreferences(Constants.MacOSBundleId);
31+
IDictionary<string, string> dict = prefs.GetDictionary("configuration");
32+
33+
if (dict is null)
34+
{
35+
// No configuration key exists
36+
return false;
37+
}
38+
39+
// Wrap the raw dictionary in one configured with the Git configuration key comparer.
40+
// This means we can use the same key comparison rules as Git in our configuration plist dict,
41+
// That is, sections and names are insensitive to case, but the scope is case-sensitive.
42+
var config = new Dictionary<string, string>(dict, GitConfigurationKeyComparer.Instance);
43+
44+
string name = string.IsNullOrWhiteSpace(scope)
45+
? $"{section}.{property}"
46+
: $"{section}.{scope}.{property}";
47+
48+
if (!config.TryGetValue(name, out value))
49+
{
50+
// No property exists
51+
return false;
52+
}
53+
54+
_trace.WriteLine($"Default setting found in app preferences: {name}={value}");
55+
return true;
56+
}
57+
catch (Exception ex)
58+
{
59+
// Reading defaults is not critical to the operation of the application
60+
// so we can ignore any errors and just log the failure.
61+
_trace.WriteLine("Failed to read default setting from app preferences.");
62+
_trace.WriteException(ex);
63+
return false;
64+
}
65+
}
66+
}
67+
}

0 commit comments

Comments
 (0)