Skip to content

Commit 7de6bd6

Browse files
Harden CLI session isolation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 9c84b35 commit 7de6bd6

13 files changed

Lines changed: 383 additions & 86 deletions

File tree

‎src/UniGetUI.Avalonia/AvaloniaCliHandler.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,10 @@ internal static class AvaloniaCliHandler
3232
private enum ExitCode
3333
{
3434
Success = 0,
35-
Failed = -1,
36-
InvalidParameter = -1073741811,
37-
NoSuchFile = -1073741809,
38-
UnknownSettingsKey = -2,
35+
Failed = 1,
36+
InvalidParameter = 2,
37+
NoSuchFile = 3,
38+
UnknownSettingsKey = 4,
3939
}
4040

4141
/// <summary>

‎src/UniGetUI.Avalonia/Infrastructure/AvaloniaBootstrapper.cs‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,10 @@ private static async Task InitializeBackgroundApiAsync()
153153
if (Settings.Get(Settings.K.DisableApi))
154154
return;
155155

156-
_backgroundApi = new BackgroundApiRunner();
156+
_backgroundApi = new BackgroundApiRunner
157+
{
158+
SessionKind = BackgroundApiTransportOptions.GuiSessionKind,
159+
};
157160
_backgroundApi.AppInfoProvider = () =>
158161
Dispatcher.UIThread.InvokeAsync(GetAppInfo).GetAwaiter().GetResult();
159162
_backgroundApi.ShowAppHandler = () =>
@@ -193,7 +196,17 @@ private static async Task InitializeBackgroundApiAsync()
193196
}
194197
}
195198

196-
public static void StopBackgroundApi() => _backgroundApi?.Stop();
199+
public static async Task StopBackgroundApiAsync()
200+
{
201+
if (_backgroundApi is null)
202+
{
203+
return;
204+
}
205+
206+
BackgroundApiRunner backgroundApi = _backgroundApi;
207+
_backgroundApi = null;
208+
await backgroundApi.Stop();
209+
}
197210

198211
private static AutomationAppInfo GetAppInfo()
199212
{

‎src/UniGetUI.Avalonia/Infrastructure/HeadlessDaemonHost.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ void RequestShutdown()
3636
PEInterface.LoadLoaders();
3737
await Task.Run(PEInterface.LoadManagers);
3838

39-
backgroundApi = new BackgroundApiRunner();
39+
backgroundApi = new BackgroundApiRunner
40+
{
41+
SessionKind = BackgroundApiTransportOptions.HeadlessSessionKind,
42+
};
4043
backgroundApi.AppInfoProvider = () =>
4144
new AutomationAppInfo
4245
{

‎src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,7 @@ public void ShowFromTray()
560560
public void QuitApplication()
561561
{
562562
_allowClose = true;
563+
AvaloniaBootstrapper.StopBackgroundApiAsync().GetAwaiter().GetResult();
563564
(global::Avalonia.Application.Current?.ApplicationLifetime
564565
as IClassicDesktopStyleApplicationLifetime)?.Shutdown();
565566
}

‎src/UniGetUI.Core.SecureSettings/SecureGHTokenManager.cs‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ namespace UniGetUI.Core.SecureSettings
66
public static class SecureGHTokenManager
77
{
88
private const string GitHubResourceName = "UniGetUI/GitHubAccessToken";
9+
private const string CredentialNamespaceEnvironmentVariable = "UNIGETUI_GITHUB_TOKEN_NAMESPACE";
910
private static readonly string UserName = Environment.UserName;
1011

1112
public static void StoreToken(string token)
@@ -21,7 +22,7 @@ public static void StoreToken(string token)
2122
if (GetToken() is not null)
2223
DeleteToken(); // Delete any old token(s)
2324

24-
CoreCredentialStore.SetSecret(GitHubResourceName, UserName, token);
25+
CoreCredentialStore.SetSecret(GetScopedResourceName(), UserName, token);
2526
Logger.Info("GitHub access token stored/updated securely.");
2627
}
2728
catch (Exception ex)
@@ -37,7 +38,7 @@ public static void StoreToken(string token)
3738
{
3839
try
3940
{
40-
string? token = CoreCredentialStore.GetSecret(GitHubResourceName, UserName);
41+
string? token = CoreCredentialStore.GetSecret(GetScopedResourceName(), UserName);
4142
if (token is null)
4243
{
4344
return null;
@@ -57,7 +58,7 @@ public static void DeleteToken()
5758
{
5859
try
5960
{
60-
CoreCredentialStore.DeleteSecret(GitHubResourceName, UserName);
61+
CoreCredentialStore.DeleteSecret(GetScopedResourceName(), UserName);
6162
Logger.Info("GitHub access token deleted.");
6263
}
6364
catch (Exception ex)
@@ -68,5 +69,16 @@ public static void DeleteToken()
6869
Logger.Error(ex);
6970
}
7071
}
72+
73+
private static string GetScopedResourceName()
74+
{
75+
string? credentialNamespace = Environment.GetEnvironmentVariable(
76+
CredentialNamespaceEnvironmentVariable
77+
);
78+
79+
return string.IsNullOrWhiteSpace(credentialNamespace)
80+
? GitHubResourceName
81+
: $"{GitHubResourceName}/{credentialNamespace.Trim()}";
82+
}
7183
}
7284
}

‎src/UniGetUI.Interface.BackgroundApi/AutomationCliCommandRunner.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ namespace UniGetUI.Interface;
77
public enum AutomationCliExitCode
88
{
99
Success = 0,
10-
Failed = -1,
11-
InvalidParameter = -1073741811,
12-
BackgroundApiUnavailable = -3,
13-
UnknownAutomationCommand = -4,
10+
Failed = 1,
11+
InvalidParameter = 2,
12+
BackgroundApiUnavailable = 3,
13+
UnknownAutomationCommand = 4,
1414
}
1515

1616
public static class AutomationCliCommandRunner

‎src/UniGetUI.Interface.BackgroundApi/AutomationManagerSettingsApi.cs‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -188,13 +188,7 @@ public static AutomationSettingInfo ClearSetting(string settingKey)
188188

189189
public static void ResetSettingsPreservingSession()
190190
{
191-
string currentSessionToken = Settings.GetValue(Settings.K.CurrentSessionToken);
192191
Settings.ResetSettings();
193-
194-
if (!string.IsNullOrWhiteSpace(currentSessionToken))
195-
{
196-
Settings.SetValue(Settings.K.CurrentSessionToken, currentSessionToken);
197-
}
198192
}
199193

200194
public static async Task<AutomationManagerInfo> SetManagerEnabledAsync(

‎src/UniGetUI.Interface.BackgroundApi/BackgroundApi.cs‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ internal static class ApiTokenHolder
2525

2626
public class BackgroundApiRunner
2727
{
28+
public string SessionId { get; } = Guid.NewGuid().ToString("N");
29+
public string SessionKind { get; init; } = BackgroundApiTransportOptions.GuiSessionKind;
2830
public event EventHandler<EventArgs>? OnOpenWindow;
2931
public event EventHandler<EventArgs>? OnOpenUpdatesPage;
3032
public event EventHandler<EventArgs>? OnUpgradeAll;
@@ -38,6 +40,7 @@ public class BackgroundApiRunner
3840
private IHost? _host;
3941
private BackgroundApiTransportOptions _transportOptions =
4042
BackgroundApiTransportOptions.LoadForServer();
43+
private int _stopRequested;
4144

4245
public BackgroundApiRunner() { }
4346

@@ -50,7 +53,6 @@ public async Task Start()
5053
{
5154
_transportOptions = BackgroundApiTransportOptions.LoadForServer();
5255
ApiTokenHolder.Token = CoreTools.RandomString(64);
53-
Settings.SetValue(Settings.K.CurrentSessionToken, ApiTokenHolder.Token);
5456
Logger.Info("Generated a background API auth token for the current session");
5557

5658
var builder = Host.CreateDefaultBuilder();
@@ -186,7 +188,12 @@ public async Task Start()
186188
});
187189
_host = builder.Build();
188190
await _host.StartAsync();
189-
_transportOptions.Persist();
191+
_transportOptions.Persist(
192+
SessionId,
193+
ApiTokenHolder.Token,
194+
SessionKind,
195+
Environment.ProcessId
196+
);
190197
Logger.Info(
191198
_transportOptions.TransportKind == BackgroundApiTransportKind.NamedPipe
192199
? $"Api running on named pipe {_transportOptions.NamedPipeName}"
@@ -2007,17 +2014,30 @@ private async Task WIDGETS_V2_GetIconForPackage(HttpContext context)
20072014

20082015
public async Task Stop()
20092016
{
2017+
if (Interlocked.Exchange(ref _stopRequested, 1) == 1)
2018+
{
2019+
return;
2020+
}
2021+
20102022
try
20112023
{
2012-
ArgumentNullException.ThrowIfNull(_host);
2013-
await _host.StopAsync();
2014-
BackgroundApiTransportOptions.DeletePersistedMetadata();
2024+
if (_host is not null)
2025+
{
2026+
await _host.StopAsync();
2027+
_host.Dispose();
2028+
_host = null;
2029+
}
2030+
20152031
Logger.Info("Api was shut down");
20162032
}
20172033
catch (Exception ex)
20182034
{
20192035
Logger.Error(ex);
20202036
}
2037+
finally
2038+
{
2039+
BackgroundApiTransportOptions.DeletePersistedMetadata(SessionId);
2040+
}
20212041
}
20222042
}
20232043
}

‎src/UniGetUI.Interface.BackgroundApi/BackgroundApiClient.cs‎

Lines changed: 84 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1+
using System.Diagnostics;
12
using System.IO.Pipes;
23
using System.Net.Http.Json;
34
using System.Text.Json;
45
using UniGetUI.Core.Data;
56
using UniGetUI.Core.Logging;
6-
using UniGetUI.Core.SettingsEngine;
77

88
namespace UniGetUI.Interface;
99

@@ -17,13 +17,42 @@ public sealed class BackgroundApiClient : IDisposable
1717
private BackgroundApiClient(BackgroundApiTransportOptions transportOptions, string? token = null)
1818
{
1919
TransportOptions = transportOptions;
20-
_token = token ?? Settings.GetValue(Settings.K.CurrentSessionToken);
20+
_token = token ?? string.Empty;
2121
_httpClient = CreateHttpClient(transportOptions);
2222
}
2323

2424
public static BackgroundApiClient CreateForCli(IReadOnlyList<string>? args = null)
2525
{
26-
return new BackgroundApiClient(BackgroundApiTransportOptions.LoadForClient(args));
26+
args ??= Environment.GetCommandLineArgs();
27+
BackgroundApiTransportOptions requestedOptions = BackgroundApiTransportOptions.LoadForClient(args);
28+
29+
if (BackgroundApiTransportOptions.HasExplicitClientOverride(args))
30+
{
31+
var matchingRegistrations = BackgroundApiTransportOptions.LoadPersistedRegistrations()
32+
.Where(candidate => candidate.Matches(requestedOptions))
33+
.ToArray();
34+
var registration = SelectLiveRegistration(
35+
matchingRegistrations
36+
);
37+
38+
return new BackgroundApiClient(
39+
requestedOptions,
40+
registration?.Token ?? matchingRegistrations.FirstOrDefault()?.Token
41+
);
42+
}
43+
44+
var preferredRegistration = SelectLiveRegistration(
45+
BackgroundApiTransportOptions.OrderRegistrationsForCliSelection(
46+
BackgroundApiTransportOptions.LoadPersistedRegistrations()
47+
)
48+
);
49+
50+
return preferredRegistration is not null
51+
? new BackgroundApiClient(
52+
preferredRegistration.ToTransportOptions(),
53+
preferredRegistration.Token
54+
)
55+
: new BackgroundApiClient(requestedOptions);
2756
}
2857

2958
public async Task<BackgroundApiStatus> GetStatusAsync()
@@ -1433,6 +1462,58 @@ or TaskCanceledException
14331462
or OperationCanceledException;
14341463
}
14351464

1465+
private static BackgroundApiEndpointRegistration? SelectLiveRegistration(
1466+
IEnumerable<BackgroundApiEndpointRegistration> candidates
1467+
)
1468+
{
1469+
foreach (BackgroundApiEndpointRegistration candidate in candidates)
1470+
{
1471+
if (candidate.ProcessId > 0 && !IsProcessRunning(candidate.ProcessId))
1472+
{
1473+
BackgroundApiTransportOptions.DeletePersistedMetadata(candidate.SessionId);
1474+
continue;
1475+
}
1476+
1477+
if (IsEndpointAlive(candidate))
1478+
{
1479+
return candidate;
1480+
}
1481+
1482+
BackgroundApiTransportOptions.DeletePersistedMetadata(candidate.SessionId);
1483+
}
1484+
1485+
return null;
1486+
}
1487+
1488+
private static bool IsEndpointAlive(BackgroundApiEndpointRegistration candidate)
1489+
{
1490+
try
1491+
{
1492+
using var client = new BackgroundApiClient(candidate.ToTransportOptions(), candidate.Token);
1493+
return client.GetStatusAsync().GetAwaiter().GetResult().Running;
1494+
}
1495+
catch (Exception ex) when (IsConnectivityException(ex) || ex is InvalidOperationException)
1496+
{
1497+
Logger.Debug(
1498+
$"Background API registration {candidate.SessionId} probe failed: {ex.Message}"
1499+
);
1500+
return false;
1501+
}
1502+
}
1503+
1504+
private static bool IsProcessRunning(int processId)
1505+
{
1506+
try
1507+
{
1508+
using Process process = Process.GetProcessById(processId);
1509+
return !process.HasExited;
1510+
}
1511+
catch (Exception)
1512+
{
1513+
return false;
1514+
}
1515+
}
1516+
14361517
private void EnsureTokenAvailable()
14371518
{
14381519
if (string.IsNullOrWhiteSpace(_token))

0 commit comments

Comments
 (0)