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
21 changes: 21 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,30 @@ name: Build
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
workflow_dispatch:

# The workflow only needs to read the code.
permissions:
contents: read

jobs:
test:
runs-on: windows-latest

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Setup .NET
uses: actions/setup-dotnet@v3
with:
dotnet-version: '10.0.x'

- name: Test (password known-answer tests)
run: dotnet test SecretKey.Core.Tests/SecretKey.Core.Tests.csproj --configuration Release

build:
runs-on: windows-latest

Expand Down
57 changes: 57 additions & 0 deletions SecretKey.Core.Tests/CryptoTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System.Text;
using SecretKey.Core;

namespace SecretKey.Core.Tests;

/// <summary>
/// Known-answer tests for the building blocks in Crypto.cs.
/// If any of these fail, previously generated passwords can no longer be reproduced.
/// </summary>
public class CryptoTests
{
[Fact]
public void MonthlyMasterKey_IsSha256OfRootKeyTextPlusDateCode()
{
byte[] key = Crypto.DeriveMonthlyMasterKey(V1TestHelper.TestRootKey, "2611");

Assert.Equal("4E0F0B5B77491DCA67A584A58EC1F6D4859775346265F8C03B51878FE2CF8A12", Convert.ToHexString(key));
}

[Fact]
public void HmacSha256_MatchesRfc4231TestCase2()
{
byte[] mac = Crypto.HmacSha256(Encoding.ASCII.GetBytes("Jefe"), Encoding.ASCII.GetBytes("what do ya want for nothing?"));

Assert.Equal("5BDCC146BF60754E6A042426089575C75A003F089D2739839DEC58B964EC3843", Convert.ToHexString(mac));
}

[Fact]
public void HmacSha256_OfAccountBlock_IsStable()
{
byte[] key = Crypto.DeriveMonthlyMasterKey(V1TestHelper.TestRootKey, "2611");
var block = new byte[32]; // v1: title + url + username, UTF-8, cut or zero-padded to 32 bytes
byte[] text = Encoding.UTF8.GetBytes("Bank" + "https://bank.example" + "ed");
Array.Copy(text, block, text.Length);

Assert.Equal("0F803F563CA1F44777139CCC4BB04B81DA0373509D3D28FC76E896BB234AD5C9", Convert.ToHexString(Crypto.HmacSha256(key, block)));
}

[Fact]
public void MapBlobToPattern_MapsEachMaskTokenFromOneHashByte()
{
byte[] bytes = Enumerable.Range(0, 32).Select(i => (byte)i).ToArray();

// X -> A-Z, x -> a-z, N -> 0-9, S -> "!@#$%&*()-_=+[]{}<>?", anything else is copied as-is.
// A literal still uses up a hash byte (v1 behavior).
Assert.Equal("Ab2$-Fg7)", Crypto.MapBlobToPattern(bytes, "XxNS-XxNS"));
}

[Fact]
public void MapBlobToPattern_WrapsAfter32Characters_V1Behavior()
{
byte[] bytes = Enumerable.Range(0, 32).Select(i => (byte)i).ToArray();

// Known v1 weakness: mask positions 33+ reuse the same 32 hash bytes.
Assert.Equal("0123456789012345678901234567890101234567", Crypto.MapBlobToPattern(bytes, new string('N', 40)));
}
}
110 changes: 110 additions & 0 deletions SecretKey.Core.Tests/PasswordDerivationV1Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
using static SecretKey.Core.Tests.V1TestHelper;

namespace SecretKey.Core.Tests;

/// <summary>
/// Locks the passwords SecretKey v1.0.0 produces, end to end (CSV in, CSV out).
///
/// Why this exists: the whole point of SecretKey is that the same root key and date code
/// give the same passwords forever. If any test here fails, a code change has altered
/// users' passwords. Do not "fix" the expected values to make a test pass — change the
/// code back, or put the new behavior behind an explicit, opt-in new version.
/// </summary>
public class PasswordDerivationV1Tests
{
[Theory]
[InlineData("Bhphotovideo", "https://www.bhphotovideo.com", "email@sample.com", DefaultMask, "2611",
"Bhphotovideo,https://www.bhphotovideo.com,email@sample.com,Wocqe8<tvg04")]
[InlineData("Bhphotovideo", "https://www.bhphotovideo.com", "email@sample.com", DefaultMask, "2612",
"Bhphotovideo,https://www.bhphotovideo.com,email@sample.com,Itjak8_enx59")]
[InlineData("Paramount+", "paramountplus.com", "email@yahoo.com", DefaultMask, "2611",
"Paramount+,https://paramountplus.com,email@yahoo.com,Gmrdj4<hdz14")]
[InlineData("Paramount+", "paramountplus.com", "email@yahoo.com", "xxxxxxxxNNNN", "2611",
"Paramount+,https://paramountplus.com,email@yahoo.com,gmrdjaph7914")]
[InlineData("MTA eTix", "https://www.mta.info/", "email@sample.com", DefaultMask, "2611",
"MTA eTix,https://www.mta.info/,email@sample.com,Zuzhl4]zit82")]
[InlineData("Solterra", "", "email@sample.com", DefaultMask, "2611",
"Solterra,,email@sample.com,Qbxml3&dlt19")]
[InlineData("Old Site", "http://example.org", "me", DefaultMask, "2611",
"Old Site,http://example.org,me,Kvxan9)vvg19")]
[InlineData("PayPal", "WWW.PayPal.com", "ed", DefaultMask, "2611",
"PayPal,https://WWW.PayPal.com,ed,Enwxh1@lfp63")] // URL letter case is kept as typed
[InlineData("Café", "https://café.example", "josé", DefaultMask, "2611",
"Café,https://café.example,josé,Skyhq4<kuy09")]
[InlineData("Bank", "https://bank.example", "ed", "Xxx-NNN.x", "2611",
"Bank,https://bank.example,ed,Pyl-014.p")]
public void KnownAccounts_ProduceKnownPasswords(string title, string url, string username, string mask, string dateCode, string expectedOutputLine)
{
Assert.Equal(expectedOutputLine, OutputLineFor(title, url, username, mask, dateCode));
}

[Fact]
public void UrlWithoutScheme_GetsHttpsPrefix_ButEmptyUrlStaysEmpty()
{
Assert.StartsWith("Paramount+,https://paramountplus.com,", OutputLineFor("Paramount+", "paramountplus.com", "email@yahoo.com"));
Assert.StartsWith("Solterra,,", OutputLineFor("Solterra", "", "email@sample.com"));
}

[Fact]
public void SpacesAroundFields_AreIgnored()
{
string padded = OutputLineFor(" Padded ", " example.com ", " user ");
string paddedInsideQuotes = Run(new[] { "\" Padded \",\" example.com \",\" user \",,,false,false,," })[1];
string clean = OutputLineFor("Padded", "example.com", "user");

Assert.Equal("Padded,https://example.com,user,Kgbqd5&vtr41", clean);
Assert.Equal(clean, padded);
Assert.Equal(clean, paddedInsideQuotes);
}

[Fact]
public void QuotedTitleContainingComma_IsReadAsOneField()
{
string[] lines = Run(new[] { "\"Smith, John Bank\",https://bank.example,john,,,false,false,," });

Assert.Equal("\"Smith, John Bank\",https://bank.example,john,Hmxkl2-ual91", lines[1]);
}

[Fact]
public void UsernameIsIgnored_WhenTitlePlusUrlFill32Bytes_V1Behavior()
{
// Known v1 weakness: only the first 32 bytes of title+url+username are used.
// "Bhphotovideo" + "https://www.bhphotovideo.com" is already 40 bytes, so two
// different logins on this site get the same password.
string[] lines = Run(new[]
{
Row("Bhphotovideo", "https://www.bhphotovideo.com", "alice@sample.com"),
Row("Bhphotovideo", "https://www.bhphotovideo.com", "bob@other.org"),
});

Assert.EndsWith(",Wocqe8<tvg04", lines[1]);
Assert.EndsWith(",Wocqe8<tvg04", lines[2]);
}

[Fact]
public void FieldsAreJoinedWithoutSeparator_V1Behavior()
{
// Known v1 weakness: ("ab", "", "c") and ("a", "", "bc") produce the same input bytes.
string first = OutputLineFor("ab", "", "c");
string second = OutputLineFor("a", "", "bc");

Assert.Equal(first.Split(',')[^1], second.Split(',')[^1]);
}

[Fact]
public void SampleInputFile_ProducesKnownOutput()
{
// Solterra's "passwordmask=" note is not applied by v1.0.0, so it gets the default mask.
string sample = Path.Combine(AppContext.BaseDirectory, "TestData", "sample_input.csv");
string[] rows = File.ReadAllLines(sample).Skip(1).ToArray();

Assert.Equal(new[]
{
"Title,Url,Username,Password",
"Bhphotovideo,https://www.bhphotovideo.com,email@sample.com,Wocqe8<tvg04",
"Paramount+,https://paramountplus.com,email@yahoo.com,Gmrdj4<hdz14",
"Solterra,,email@sample.com,Qbxml3&dlt19",
"MTA eTix,https://www.mta.info/,email@sample.com,Zuzhl4]zit82",
}, Run(rows));
}
}
29 changes: 29 additions & 0 deletions SecretKey.Core.Tests/SecretKey.Core.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>

<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\SecretKey.Core\SecretKey.Core.csproj" />
</ItemGroup>

<ItemGroup>
<!-- The repo's sample input, copied next to the tests so its passwords are locked too. -->
<None Include="..\sample_input.csv" Link="TestData\sample_input.csv" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

</Project>
57 changes: 57 additions & 0 deletions SecretKey.Core.Tests/V1TestHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using SecretKey.Core;

namespace SecretKey.Core.Tests;

/// <summary>
/// Shared setup for the v1 known-answer tests.
/// Every expected value in this project was produced by the v1.0.0 engine and
/// cross-checked against an independent implementation of the same algorithm.
/// </summary>
internal static class V1TestHelper
{
// TEST-ONLY root key. Never use this for real passwords.
public const string TestRootKey = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";

public const string DefaultMask = "XxxxxNSxxxNN";
public const string DateCode = "2611";

public const string InputHeader = "Title,Url,Username,Password,OTPAuth,Favorite,Archived,Tags,Notes";
public const string OutputHeader = "Title,Url,Username,Password";

/// <summary>Builds an unquoted input row in the 1Password-style column order the engine reads.</summary>
public static string Row(string title, string url, string username) =>
$"{title},{url},{username},,,false,false,,";

/// <summary>
/// Runs the real engine on the given input rows in a private temp folder and returns the output lines.
/// (The engine rewrites its input file in place, so it must never be pointed at a shared file.)
/// </summary>
public static string[] Run(IEnumerable<string> inputRows, string mask = DefaultMask, string dateCode = DateCode)
{
string dir = Path.Combine(Path.GetTempPath(), "secretkey-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
string input = Path.Combine(dir, "input.csv");
string output = Path.Combine(dir, "output.csv");
File.WriteAllLines(input, new[] { InputHeader }.Concat(inputRows));

Processor.Process(input, output, Crypto.DeriveMonthlyMasterKey(TestRootKey, dateCode), mask);

return File.ReadAllLines(output);
}
finally
{
Directory.Delete(dir, recursive: true);
}
}

/// <summary>Runs one account through the engine and returns its output line.</summary>
public static string OutputLineFor(string title, string url, string username, string mask = DefaultMask, string dateCode = DateCode)
{
string[] lines = Run(new[] { Row(title, url, username) }, mask, dateCode);
Assert.Equal(2, lines.Length);
Assert.Equal(OutputHeader, lines[0]);
return lines[1];
}
}
1 change: 1 addition & 0 deletions SecretKey.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<File Path="sample_input.csv" />
</Folder>
<Project Path="SecretKey.Core/SecretKey.Core.csproj" />
<Project Path="SecretKey.Core.Tests/SecretKey.Core.Tests.csproj" />
<Project Path="SecretKey/SecretKey.csproj" />
<Project Path="SecretKeyUI/SecretKeyUI.csproj" Id="7e38d3b0-fc1c-4a6b-9fe8-d421dfe2c20e">
<Platform Project="x64" />
Expand Down
Loading