Skip to content

Fix SHA calculations #7804

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 21, 2019
Merged
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
37 changes: 23 additions & 14 deletions src/Templating/test/Templates.Test/CdnScriptTagTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,7 @@ public static IEnumerable<object[]> SubresourceIntegrityCheckLinkData
[MemberData(nameof(SubresourceIntegrityCheckScriptData))]
public async Task CheckScriptSubresourceIntegrity(ScriptTag scriptTag)
{
string expectedIntegrity;
using (var responseStream = await _httpClient.GetStreamAsync(scriptTag.Src))
using (var alg = SHA256.Create())
{
var hash = alg.ComputeHash(responseStream);
expectedIntegrity = "sha256-" + Convert.ToBase64String(hash);
}
var expectedIntegrity = await GetShaIntegrity(scriptTag);

if (!expectedIntegrity.Equals(scriptTag.Integrity, StringComparison.OrdinalIgnoreCase))
{
Expand All @@ -95,13 +89,7 @@ public async Task CheckScriptSubresourceIntegrity(ScriptTag scriptTag)
[MemberData(nameof(SubresourceIntegrityCheckLinkData))]
public async Task CheckLinkSubresourceIntegrity(LinkTag linkTag)
{
string expectedIntegrity;
using (var responseStream = await _httpClient.GetStreamAsync(linkTag.HRef))
using (var alg = SHA256.Create())
{
var hash = alg.ComputeHash(responseStream);
expectedIntegrity = "sha256-" + Convert.ToBase64String(hash);
}
var expectedIntegrity = await GetShaIntegrity(linkTag);

if (!expectedIntegrity.Equals(linkTag.Integrity, StringComparison.OrdinalIgnoreCase))
{
Expand Down Expand Up @@ -162,6 +150,27 @@ public override string ToString()
}
}

private Task<string> GetShaIntegrity(ScriptTag scriptTag)
{
return GetShaIntegrity(scriptTag.Integrity, scriptTag.Src);
}

private Task<string> GetShaIntegrity(LinkTag linkTag)
{
return GetShaIntegrity(linkTag.Integrity, linkTag.HRef);
}

private async Task<string> GetShaIntegrity(string integrity, string src)
{
var prefix = integrity.Substring(0, 6);
using (var respStream = await _httpClient.GetStreamAsync(src))
using (HashAlgorithm alg = string.Equals(prefix, "sha256") ? (HashAlgorithm)SHA256.Create() : (HashAlgorithm)SHA384.Create())
{
var hash = alg.ComputeHash(respStream);
return $"{prefix}-" + Convert.ToBase64String(hash);
}
}

private static string GetFileContentFromArchive(ScriptTag scriptTag, string relativeFilePath)
{
var file = Path.Combine(_artifactsDir, scriptTag.FileName);
Expand Down