Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Rapr/HttpClientExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ public static async Task DownloadAsync(
// Get the http headers first to examine the content length
using (var response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
{
// Otherwise an error page would be saved as if it were the download.
response.EnsureSuccessStatusCode();

var contentLength = response.Content.Headers.ContentLength;

using (var download = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
Expand Down
2 changes: 0 additions & 2 deletions Rapr/Rapr.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
<PackageReference Include="Microsoft.Dism" Version="6.1.0" GeneratePathProperty="true" />
<PackageReference Include="Microsoft.WindowsAPICodePack.Core" Version="1.1.0" GeneratePathProperty="true" />
<PackageReference Include="Microsoft.WindowsAPICodePack.Shell" Version="1.1.0" GeneratePathProperty="true" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" GeneratePathProperty="true" />
<PackageReference Include="ObjectListView.WinForms" Version="3.0.10-preview" GeneratePathProperty="true" />
<PackageReference Include="PortableSettingsProvider" Version="0.2.5" GeneratePathProperty="true" />
<PackageReference Include="Resource.Embedder" Version="2.2.0" />
Expand Down Expand Up @@ -72,7 +71,6 @@
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="$(PkgMicrosoft_Dism)\lib\net472\Microsoft.Dism.dll" Visible="false" />
<EmbeddedResource Include="$(PkgNewtonsoft_Json)\lib\net45\Newtonsoft.Json.dll" Visible="false" />
<EmbeddedResource Include="$(PkgObjectListView_WinForms)\lib\net462\ObjectListView.dll" Visible="false" />
<EmbeddedResource Include="$(PkgMicrosoft_WindowsAPICodePack_Core)\lib\Microsoft.WindowsAPICodePack.dll" Visible="false" />
<EmbeddedResource Include="$(PkgMicrosoft_WindowsAPICodePack_Shell)\lib\Microsoft.WindowsAPICodePack.Shell.dll" Visible="false" />
Expand Down
133 changes: 88 additions & 45 deletions Rapr/UpdateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,71 +3,84 @@
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json.Linq;

namespace Rapr
{
public class UpdateManager : IUpdateManager, IDisposable
{
private const string versionInfoUrl = "https://api.github.com/repos/lostindark/DriverStoreExplorer/releases/latest";
private readonly HttpClient httpClient = new HttpClient();
private readonly HttpClient httpClient = CreateHttpClient();
private bool disposedValue; // To detect redundant calls

public bool HandlesRestart => false;

private static HttpClient CreateHttpClient()
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
client.DefaultRequestHeaders.Add("User-Agent", "System.Net.Http Agent");
return client;
}

public async Task<VersionInfo> GetLatestVersionInfo()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

this.httpClient.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));

this.httpClient.DefaultRequestHeaders
.Add("User-Agent", "System.Net.Http Agent");

using (var response = await this.httpClient.GetAsync(new Uri(versionInfoUrl)).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var releaseInfo = JObject.Parse(responseBody);

var tagName = releaseInfo["tag_name"]?.ToString();
var htmlUrl = releaseInfo["html_url"]?.ToString();
var downloadUrl = releaseInfo.SelectToken("assets[0].browser_download_url")?.ToObject<string>();
var digest = releaseInfo.SelectToken("assets[0].digest")?.ToObject<string>();
return ParseLatestRelease(responseBody);
}

if (tagName == null || htmlUrl == null || downloadUrl == null)
{
return null;
}
return null;
}
}

// Parse "sha256:<hex>" format
string sha256 = null;
if (digest != null && digest.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase))
{
sha256 = digest.Substring("sha256:".Length);
}
internal static VersionInfo ParseLatestRelease(string json)
{
GitHubRelease release;
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
release = (GitHubRelease)new DataContractJsonSerializer(typeof(GitHubRelease)).ReadObject(stream);
}

return new VersionInfo
{
Version = Version.Parse(tagName.TrimStart('v', 'V')),
PageUrl = new Uri(htmlUrl),
DownloadUrl = new Uri(downloadUrl),
Sha256 = sha256
};
}
// Pick the zip release.yml uploads rather than whichever asset happens to be first.
var asset = release?.Assets?.FirstOrDefault(a =>
a.Name != null
&& a.Name.StartsWith("DriverStoreExplorer-", StringComparison.OrdinalIgnoreCase)
&& a.Name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase));

if (release?.TagName == null || release.HtmlUrl == null || asset?.BrowserDownloadUrl == null)
{
return null;
}

// Parse "sha256:<hex>" format
string sha256 = null;
if (asset.Digest != null && asset.Digest.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase))
{
sha256 = asset.Digest.Substring("sha256:".Length);
}

return new VersionInfo
{
Version = Version.Parse(release.TagName.TrimStart('v', 'V')),
PageUrl = new Uri(release.HtmlUrl),
DownloadUrl = new Uri(asset.BrowserDownloadUrl),
Sha256 = sha256
};
}

public async Task ApplyUpdateAsync(VersionInfo versionInfo, IProgress<float> progress)
Expand All @@ -82,6 +95,12 @@ public async Task ApplyUpdateAsync(VersionInfo versionInfo, IProgress<float> pro
throw new InvalidOperationException("Download URL is not from a trusted GitHub domain.");
}

// The new executable runs elevated, so don't install anything that can't be checked.
if (string.IsNullOrEmpty(versionInfo.Sha256))
{
throw new InvalidOperationException("The release does not provide a SHA-256 digest for the download.");
}

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

string tempBaseDir = Path.Combine(Path.GetTempPath(), "DriverStoreExplorer");
Expand Down Expand Up @@ -112,19 +131,16 @@ public async Task ApplyUpdateAsync(VersionInfo versionInfo, IProgress<float> pro
}

// Verify SHA256 hash
if (!string.IsNullOrEmpty(versionInfo.Sha256))
using (var sha256 = SHA256.Create())
using (var fileStream = new FileStream(tempZipPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var sha256 = SHA256.Create())
using (var fileStream = new FileStream(tempZipPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var hashBytes = sha256.ComputeHash(fileStream);
var actualHash = BitConverter.ToString(hashBytes).Replace("-", string.Empty);
var hashBytes = sha256.ComputeHash(fileStream);
var actualHash = BitConverter.ToString(hashBytes).Replace("-", string.Empty);

if (!actualHash.Equals(versionInfo.Sha256, StringComparison.OrdinalIgnoreCase))
{
File.Delete(tempZipPath);
throw new InvalidOperationException("SHA256 hash of the downloaded file does not match the expected value.");
}
if (!actualHash.Equals(versionInfo.Sha256, StringComparison.OrdinalIgnoreCase))
{
File.Delete(tempZipPath);
throw new InvalidOperationException("SHA256 hash of the downloaded file does not match the expected value.");
}
}

Expand Down Expand Up @@ -428,5 +444,32 @@ public void Dispose()
this.Dispose(true);
GC.SuppressFinalize(this);
}

// Only the fields of https://docs.github.com/rest/releases/releases#get-the-latest-release that are used.
[DataContract]
private sealed class GitHubRelease
{
[DataMember(Name = "tag_name")]
public string TagName { get; set; }

[DataMember(Name = "html_url")]
public string HtmlUrl { get; set; }

[DataMember(Name = "assets")]
public List<GitHubAsset> Assets { get; set; }
}

[DataContract]
private sealed class GitHubAsset
{
[DataMember(Name = "name")]
public string Name { get; set; }

[DataMember(Name = "browser_download_url")]
public string BrowserDownloadUrl { get; set; }

[DataMember(Name = "digest")]
public string Digest { get; set; }
}
}
}
1 change: 0 additions & 1 deletion Rapr/WinGetUpdateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ private static Task<string> RunCommandAsync(string fileName, string arguments)
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};

Expand Down
3 changes: 3 additions & 0 deletions RaprTests/DSEFormTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@

namespace Rapr.Tests
{
// These tests build WinForms controls and pump window messages. Run them on their own
// instead of alongside the other test classes.
[STATestClass]
[DoNotParallelize]
public class DSEFormTests
{
[TestMethod]
Expand Down
62 changes: 62 additions & 0 deletions RaprTests/HttpClientExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Rapr.Tests
{
[TestClass]
public class HttpClientExtensionsTests
{
[TestMethod]
public void FailedDownloadIsNotSavedAsTheFile()
{
using (var client = new HttpClient(new FixedResponseHandler(HttpStatusCode.NotFound, "<html>Not Found</html>")))
using (var destination = new MemoryStream())
{
var exception = Assert.ThrowsExactly<AggregateException>(
() => client.DownloadAsync(new Uri("https://github.com/missing.zip"), destination).Wait());

Assert.IsInstanceOfType<HttpRequestException>(exception.InnerException);
Assert.AreEqual(0, destination.Length);
}
}

[TestMethod]
public void SuccessfulDownloadIsCopied()
{
using (var client = new HttpClient(new FixedResponseHandler(HttpStatusCode.OK, "zip contents")))
using (var destination = new MemoryStream())
{
client.DownloadAsync(new Uri("https://github.com/release.zip"), destination).Wait();

Assert.AreEqual("zip contents", Encoding.UTF8.GetString(destination.ToArray()));
}
}

private sealed class FixedResponseHandler : HttpMessageHandler
{
private readonly HttpStatusCode statusCode;
private readonly string content;

public FixedResponseHandler(HttpStatusCode statusCode, string content)
{
this.statusCode = statusCode;
this.content = content;
}

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage(this.statusCode)
{
Content = new StringContent(this.content),
});
}
}
}
}
73 changes: 73 additions & 0 deletions RaprTests/UpdateManagerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ public class UpdateManagerTests
.GetMethod("InstallUpdate", BindingFlags.Static | BindingFlags.NonPublic)
.CreateDelegate(typeof(Action<string, string>));

private static readonly Func<string, VersionInfo> ParseLatestRelease =
(Func<string, VersionInfo>)typeof(UpdateManager)
.GetMethod("ParseLatestRelease", BindingFlags.Static | BindingFlags.NonPublic)
.CreateDelegate(typeof(Func<string, VersionInfo>));

private string testDirectory;
private string sourceDirectory;
private string appDirectory;
Expand All @@ -33,6 +38,74 @@ public void Cleanup()
Directory.Delete(this.testDirectory, recursive: true);
}

[TestMethod]
public void LatestReleaseIsReadFromTheGitHubResponse()
{
const string Json = @"{
""tag_name"": ""v1.0.63"",
""html_url"": ""https://github.com/lostindark/DriverStoreExplorer/releases/tag/v1.0.63"",
""draft"": false,
""assets"": [
{
""name"": ""DriverStoreExplorer-v1.0.63.zip"",
""size"": 1058111,
""digest"": ""sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"",
""browser_download_url"": ""https://github.com/lostindark/DriverStoreExplorer/releases/download/v1.0.63/DriverStoreExplorer-v1.0.63.zip""
}
]
}";

VersionInfo info = ParseLatestRelease(Json);

Assert.AreEqual(new Version(1, 0, 63), info.Version);
Assert.AreEqual("https://github.com/lostindark/DriverStoreExplorer/releases/tag/v1.0.63", info.PageUrl.ToString());
Assert.AreEqual("https://github.com/lostindark/DriverStoreExplorer/releases/download/v1.0.63/DriverStoreExplorer-v1.0.63.zip", info.DownloadUrl.ToString());
Assert.AreEqual("2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae", info.Sha256);
}

[TestMethod]
public void TheAppZipIsPickedEvenIfItIsNotTheFirstAsset()
{
const string Json = @"{
""tag_name"": ""v1.0.64"",
""html_url"": ""https://github.com/lostindark/DriverStoreExplorer/releases/tag/v1.0.64"",
""assets"": [
{
""name"": ""checksums.txt"",
""browser_download_url"": ""https://github.com/lostindark/DriverStoreExplorer/releases/download/v1.0.64/checksums.txt""
},
{
""name"": ""DriverStoreExplorer-v1.0.64.zip"",
""browser_download_url"": ""https://github.com/lostindark/DriverStoreExplorer/releases/download/v1.0.64/DriverStoreExplorer-v1.0.64.zip""
}
]
}";

Assert.EndsWith("/DriverStoreExplorer-v1.0.64.zip", ParseLatestRelease(Json).DownloadUrl.ToString());
}

[TestMethod]
public void UpdateWithoutDigestIsRefusedBeforeDownloading()
{
using (var manager = new UpdateManager())
{
var versionInfo = new VersionInfo
{
Version = new Version(9, 9, 9),
DownloadUrl = new Uri("https://github.com/lostindark/DriverStoreExplorer/releases/download/v9.9.9/DriverStoreExplorer-v9.9.9.zip"),
};

Assert.ThrowsExactly<InvalidOperationException>(
() => manager.ApplyUpdateAsync(versionInfo, null).GetAwaiter().GetResult());
}
}

[TestMethod]
public void ReleaseWithoutAssetsHasNoUpdate()
{
Assert.IsNull(ParseLatestRelease(@"{ ""tag_name"": ""v1.0.63"", ""html_url"": ""https://github.com/"", ""assets"": [] }"));
}

[TestMethod]
public void SameNameLibraryCannotReplaceTheExecutable()
{
Expand Down
Loading