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
80 changes: 54 additions & 26 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,41 @@ on:
push:
branches:
- main
pull_request:

# Serialize runs on a ref and cancel superseded ones, so an older run can't roll prod
# back to its (older) image after a newer run has already deployed.
concurrency:
group: vapi-cicd-${{ github.ref }}
cancel-in-progress: true

# Least privilege: no job writes to the repo (images push with Docker Hub
# credentials, deploys use SSH secrets).
permissions:
contents: read

jobs:
deps:
# Gate every PR and every deploy on the .NET test suite (crypto golden vectors,
# RPC failover, JS-semantics parity helpers).
test:
runs-on: ubuntu-24.04
strategy:
matrix:
node-version: [20.12.2]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: npm install, lint and/or test
run: |
yarn
env:
CI: true
- uses: actions/checkout@v4
with:
# PR-triggered job; don't leave the token in .git/config
persist-credentials: false
- uses: actions/setup-dotnet@v4
with:
dotnet-version: 10.0.x
- name: Build
run: dotnet build dotnet/EcencyApi/EcencyApi.csproj -c Release
- name: Test
run: dotnet test dotnet/EcencyApi.Tests/EcencyApi.Tests.csproj -c Release
Comment thread
coderabbitai[bot] marked this conversation as resolved.

build:
needs: deps
# Build/push only on merges to main; PRs stop at the test gate.
if: github.event_name == 'push'
needs: test
runs-on: ubuntu-24.04
outputs:
digest: ${{ steps.docker_build.outputs.digest }}
Expand All @@ -37,24 +46,44 @@ jobs:
steps:
-
name: Check Out Repo
uses: actions/checkout@v2
uses: actions/checkout@v4
-
name: Login to Docker Hub
uses: docker/login-action@v1
if: ${{env.DOCKERHUB_USERNAME != 0}}
uses: docker/login-action@v3
if: ${{ env.DOCKERHUB_USERNAME != 0 }}
with:
username: ${{secrets.DOCKERHUB_USERNAME}}
password: ${{secrets.DOCKERHUB_TOKEN}}
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
-
# One-time, idempotent: before the first C# image overwrites :latest,
# preserve the last Node build under a durable tag. Rollback to the
# pre-rewrite service is then always `ecency/api:node-legacy`.
name: Preserve last Node image as rollback tag
if: ${{ env.DOCKERHUB_USERNAME != 0 }}
run: |
if docker manifest inspect ecency/api:node-legacy >/dev/null 2>&1; then
echo "node-legacy tag already exists; skipping"
else
docker buildx imagetools create --tag ecency/api:node-legacy ecency/api:latest
echo "tagged current :latest as ecency/api:node-legacy"
fi
-
# The deployed implementation is the C# service under dotnet/. Every build
# is also tagged with the commit SHA, so any previous version can be
# redeployed by tag (the deploy boxes prune local images, so rollback
# comes from the registry):
# docker service update --image ecency/api:sha-<commit> vision_vapi
name: Build and push
id: docker_build
uses: docker/build-push-action@v2
if: ${{env.DOCKERHUB_USERNAME != 0}}
uses: docker/build-push-action@v5
if: ${{ env.DOCKERHUB_USERNAME != 0 }}
with:
context: ./
file: ./Dockerfile
context: ./dotnet
file: ./dotnet/Dockerfile
push: true
tags: ecency/api:latest
tags: |
ecency/api:latest
ecency/api:sha-${{ github.sha }}
-
name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}
Expand Down Expand Up @@ -112,4 +141,3 @@ jobs:
fi
echo "vision_vapi on $IMAGE (UpdateStatus=${state:-none})"
docker system prune -f

6 changes: 6 additions & 0 deletions dotnet/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
**/bin/
**/obj/
parity/
tools/
EcencyApi.Tests/
README.md
3 changes: 3 additions & 0 deletions dotnet/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
bin/
obj/
*.user
34 changes: 34 additions & 0 deletions dotnet/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Multi-stage build for the C# port of vision-api.
# Produces a self-contained ASP.NET Core service on the same 4000 port and
# /healthcheck.json contract as the Node image, so it is a drop-in swap in the
# vision_vapi stack.

FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src

COPY EcencyApi/EcencyApi.csproj EcencyApi/
RUN dotnet restore EcencyApi/EcencyApi.csproj

COPY EcencyApi/ EcencyApi/
RUN dotnet publish EcencyApi/EcencyApi.csproj -c Release -o /app --no-restore

FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime
WORKDIR /app

# Static assets served by express.static in the Node version (public/).
COPY EcencyApi/public/ ./public/
COPY --from=build /app ./

# Run as the non-root user the aspnet base image ships; port 4000 is unprivileged.
RUN chown -R app:app /app
USER app

ENV API_PORT=4000
ENV ASPNETCORE_URLS=
EXPOSE 4000

# Same health contract the Node healthCheck.js polled.
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD ["dotnet", "EcencyApi.dll", "--healthcheck"]

ENTRYPOINT ["dotnet", "EcencyApi.dll"]
Comment thread
coderabbitai[bot] marked this conversation as resolved.
24 changes: 24 additions & 0 deletions dotnet/EcencyApi.Tests/EcencyApi.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<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.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="../EcencyApi/EcencyApi.csproj" />
</ItemGroup>

<ItemGroup>
<None Include="fixtures/**" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

</Project>
159 changes: 159 additions & 0 deletions dotnet/EcencyApi.Tests/HiveCryptoTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using EcencyApi.Infrastructure;
using Xunit;

namespace EcencyApi.Tests;

/// <summary>
/// Byte-for-byte verification of the crypto port against golden vectors
/// generated from the exact dhive/js-base64 versions the Node service uses
/// (dotnet/tools/gen-vectors.js).
/// </summary>
public class HiveCryptoTests
{
private static readonly JsonObject Vectors = LoadVectors();

private static JsonObject LoadVectors()
{
var path = Path.Combine(AppContext.BaseDirectory, "fixtures", "crypto-vectors.json");
return (JsonObject)JsonNode.Parse(File.ReadAllText(path))!;
}

[Fact]
public void FromLogin_MatchesDhive()
{
foreach (var v in Vectors["fromLogin"]!.AsArray())
{
var username = v!["username"]!.GetValue<string>();
var password = v["password"]!.GetValue<string>();
var role = v["role"]!.GetValue<string>();

var key = HiveCrypto.FromLogin(username, password, role);

Assert.Equal(v["wif"]!.GetValue<string>(), HiveCrypto.ToWif(key));
Assert.Equal(v["publicKey"]!.GetValue<string>(),
HiveCrypto.PublicKeyToString(key.CreatePubKey()));
}
}

[Fact]
public void Sign_MatchesDhiveByteForByte()
{
foreach (var v in Vectors["sign"]!.AsArray())
{
var key = HiveCrypto.FromLogin(
v!["username"]!.GetValue<string>(),
v["password"]!.GetValue<string>(),
v["role"]!.GetValue<string>());

var digest = HiveCrypto.Sha256Utf8(v["message"]!.GetValue<string>());
Assert.Equal(v["digestHex"]!.GetValue<string>(), Convert.ToHexStringLower(digest));

Assert.Equal(v["signature"]!.GetValue<string>(), HiveCrypto.Sign(key, digest));
}
}

[Fact]
public void Recover_MatchesDhive()
{
foreach (var v in Vectors["recover"]!.AsArray())
{
var digest = Convert.FromHexString(v!["digestHex"]!.GetValue<string>());
var recovered = HiveCrypto.RecoverPublicKey(v["signature"]!.GetValue<string>(), digest);

Assert.Equal(v["recoveredPublicKey"]!.GetValue<string>(), recovered);
}
}

[Fact]
public void B64uEncode_MatchesJsBase64()
{
foreach (var v in Vectors["b64u"]!.AsArray())
{
Assert.Equal(v!["encoded"]!.GetValue<string>(),
B64u.Encode(v["input"]!.GetValue<string>()));
}
}

[Fact]
public void HsTokenCreate_FullFlow_MatchesNode()
{
foreach (var v in Vectors["hsTokenCreate"]!.AsArray())
{
var username = v!["username"]!.GetValue<string>();
var password = v["password"]!.GetValue<string>();
var app = v["app"]!.GetValue<string>();
var timestamp = v["timestamp"]!.GetValue<long>();

// Reproduce hsTokenCreate exactly: build the message object with JS
// property order, hash the JSON.stringify form, sign, then append
// signatures and b64u-encode.
var messageObj = new JsonObject
{
["signed_message"] = new JsonObject { ["type"] = "code", ["app"] = app },
["authors"] = new JsonArray(username),
["timestamp"] = timestamp,
};

var hash = HiveCrypto.Sha256Utf8(JsJson.Stringify(messageObj));
var key = HiveCrypto.FromLogin(username, password, "posting");
var signature = HiveCrypto.Sign(key, hash);
messageObj["signatures"] = new JsonArray(signature);

var signedJson = JsJson.Stringify(messageObj);
Assert.Equal(v["signedJson"]!.GetValue<string>(), signedJson);
Assert.Equal(v["code"]!.GetValue<string>(), B64u.Encode(signedJson));
}
}

[Fact]
public void ValidateCodeReserialization_MatchesNode()
{
foreach (var v in Vectors["validateCodeRaw"]!.AsArray())
{
var token = (JsonObject)JsonNode.Parse(v!["tokenJson"]!.GetValue<string>())!;

// The exact re-serialization validateCode performs:
// JSON.stringify({signed_message, authors, timestamp}) with the
// parsed nodes (nested key order preserved from the token).
var raw = new JsonObject
{
["signed_message"] = token["signed_message"]!.DeepClone(),
["authors"] = token["authors"]!.DeepClone(),
["timestamp"] = token["timestamp"]!.DeepClone(),
};

var rawMessage = JsJson.Stringify(raw);
Assert.Equal(v["rawMessage"]!.GetValue<string>(), rawMessage);
Assert.Equal(v["digestHex"]!.GetValue<string>(),
Convert.ToHexStringLower(HiveCrypto.Sha256Utf8(rawMessage)));
}
}

[Fact]
public void NumberFormatting_MatchesV8()
{
foreach (var v in Vectors["numberFormat"]!.AsArray())
{
var value = v!["value"]!.GetValue<double>();
var expected = v["text"]!.GetValue<string>();
// JSON.stringify path (fixture "value" is V8-serialized, so parsing it
// and re-serializing must reproduce "text" byte-for-byte)
Assert.Equal(expected, JsJson.Stringify(JsonValue.Create(value)));
}
}

[Theory]
[InlineData("{\"a\":1,\"b\":\"x\"}")]
[InlineData("{\"b\":2,\"a\":1}")] // property order preserved, not sorted
[InlineData("[1,2.5,\"s\",true,null,{}]")]
[InlineData("{\"n\":1751900000.123}")]
[InlineData("{\"u\":\"caf\\u00e9 漢字\"}")]
public void JsJson_RoundTripsParsedJson(string json)
{
var node = JsonNode.Parse(json);
var expected = json.Replace("\\u00e9", "é"); // JSON.stringify emits raw unicode
Assert.Equal(expected, JsJson.Stringify(node));
}
}
Loading
Loading