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
46 changes: 42 additions & 4 deletions src/Temporalio/Nexus/NexusWorkflowRunHandle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,33 @@ internal NexusWorkflowRunHandle(
/// </summary>
internal int Version { get; private init; }

/// <summary>
/// Encode bytes to a base64url string with no padding.
/// </summary>
/// <param name="data">Bytes to encode.</param>
/// <returns>Base64url encoded string.</returns>
internal static string Base64UrlEncode(byte[] data) =>
Convert.ToBase64String(data)
.Replace('+', '-')
.Replace('/', '_')
.TrimEnd('=');

/// <summary>
/// Decode a base64url string to bytes.
/// </summary>
/// <param name="s">Base64url encoded string.</param>
/// <returns>Decoded bytes.</returns>
internal static byte[] Base64UrlDecode(string s)
{
s = s.Replace('-', '+').Replace('_', '/');
switch (s.Length % 4)
{
case 2: s += "=="; break;
case 3: s += "="; break;
}
return Convert.FromBase64String(s);
}

/// <summary>
/// Create a handle based on the string token.
/// </summary>
Expand All @@ -63,14 +90,25 @@ internal static NexusWorkflowRunHandle FromToken(string token)
byte[] bytes;
try
{
bytes = Convert.FromBase64String(token);
bytes = Base64UrlDecode(token);
}
catch (FormatException)
{
throw new ArgumentException("Token invalid");
}
var tokenObj = JsonSerializer.Deserialize<Token>(bytes, TokenSerializerOptions) ??
Token? tokenObj;
try
{
tokenObj = JsonSerializer.Deserialize<Token>(bytes, TokenSerializerOptions);
}
catch (JsonException e)
{
throw new ArgumentException("Token invalid", e);
}
if (tokenObj == null)
{
throw new ArgumentException("Token invalid");
}
if (tokenObj.Version != null && tokenObj.Version != 0)
{
throw new ArgumentException($"Unsupported token version: {tokenObj.Version}");
Expand All @@ -82,7 +120,7 @@ internal static NexusWorkflowRunHandle FromToken(string token)
/// Create a string token based on this handle.
/// </summary>
/// <returns>Operation token.</returns>
internal string ToToken() => Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(
internal string ToToken() => Base64UrlEncode(JsonSerializer.SerializeToUtf8Bytes(
new Token(Namespace, WorkflowId, Version == 0 ? null : Version),
TokenSerializerOptions));

Expand All @@ -93,7 +131,7 @@ private record Token(
string WorkflowId,
[property: JsonPropertyName("v")]
int? Version,
[property: JsonPropertyName("t'")]
[property: JsonPropertyName("t")]
int Type = 1);
}

Expand Down
121 changes: 121 additions & 0 deletions tests/Temporalio.Tests/Nexus/NexusWorkflowRunHandleTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
namespace Temporalio.Tests.Nexus;

using System.Text;
using System.Text.Json;
using Temporalio.Nexus;
using Xunit;

public class NexusWorkflowRunHandleTests
{
[Fact]
public void ToToken_RoundTrips()
{
var handle = new NexusWorkflowRunHandle("my-namespace", "my-workflow-id", 0);
Comment thread
jmaeagle99 marked this conversation as resolved.
Resolved
var token = handle.ToToken();
var decoded = NexusWorkflowRunHandle.FromToken(token);

Assert.Equal("my-namespace", decoded.Namespace);
Assert.Equal("my-workflow-id", decoded.WorkflowId);
Assert.Equal(0, decoded.Version);
}

[Fact]
public void ToToken_UsesBase64Url_NoPadding()
{
var handle = new NexusWorkflowRunHandle("my-namespace", "my-workflow-id", 0);
var token = handle.ToToken();

// Base64url should not contain + or / or =
Assert.DoesNotContain("+", token);
Assert.DoesNotContain("/", token);
Assert.DoesNotContain("=", token);
}

[Fact]
public void ToToken_JsonUsesCorrectKeys()
{
var handle = new NexusWorkflowRunHandle("ns", "wid", 0);
var token = handle.ToToken();

// Decode manually to inspect JSON
var json = Encoding.UTF8.GetString(NexusWorkflowRunHandle.Base64UrlDecode(token));
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;

// Key must be "t" (not "t'")
Assert.Equal(1, root.GetProperty("t").GetInt32());
Assert.Equal("ns", root.GetProperty("ns").GetString());
Assert.Equal("wid", root.GetProperty("wid").GetString());
}

[Fact]
public void FromToken_AcceptsVersionNull()
{
var json = """{"t":1,"ns":"ns","wid":"wid","v":null}""";
var token = NexusWorkflowRunHandle.Base64UrlEncode(Encoding.UTF8.GetBytes(json));

var handle = NexusWorkflowRunHandle.FromToken(token);

Assert.Equal("ns", handle.Namespace);
Assert.Equal("wid", handle.WorkflowId);
Assert.Equal(0, handle.Version);
}

[Fact]
public void FromToken_AcceptsVersionZero()
{
var json = """{"t":1,"ns":"ns","wid":"wid","v":0}""";
var token = NexusWorkflowRunHandle.Base64UrlEncode(Encoding.UTF8.GetBytes(json));

var handle = NexusWorkflowRunHandle.FromToken(token);

Assert.Equal(0, handle.Version);
}

[Fact]
public void FromToken_RejectsUnsupportedVersion()
{
var json = """{"t":1,"ns":"ns","wid":"wid","v":1}""";
var token = NexusWorkflowRunHandle.Base64UrlEncode(Encoding.UTF8.GetBytes(json));

Assert.Throws<ArgumentException>(() => NexusWorkflowRunHandle.FromToken(token));
}

[Fact]
public void FromToken_RejectsInvalidBase64()
Comment thread
jmaeagle99 marked this conversation as resolved.
Resolved
{
Assert.Throws<ArgumentException>(() => NexusWorkflowRunHandle.FromToken("!!!invalid!!!"));
}

[Fact]
public void FromToken_RejectsInvalidJson()
{
var token = NexusWorkflowRunHandle.Base64UrlEncode(Encoding.UTF8.GetBytes("not valid json"));
Assert.Throws<ArgumentException>(() => NexusWorkflowRunHandle.FromToken(token));
}

[Fact]
public void CrossSdkCompatibility_PythonToken()
{
// This token was generated by Python SDK with {"t":1,"ns":"default","wid":"my-wf"} and base64url encoding
var pythonToken = "eyJ0IjoxLCJucyI6ImRlZmF1bHQiLCJ3aWQiOiJteS13ZiJ9";

var handle = NexusWorkflowRunHandle.FromToken(pythonToken);

Assert.Equal("default", handle.Namespace);
Assert.Equal("my-wf", handle.WorkflowId);
Comment thread
Quinn-With-Two-Ns marked this conversation as resolved.
Resolved
Assert.Equal(0, handle.Version);
}

[Fact]
public void ToToken_SpecialCharactersInValues_RoundTrips()
{
// Namespace/workflow IDs with characters that differ between base64 and base64url
var handle = new NexusWorkflowRunHandle("ns/with+special", "wf?id=1&foo=bar", 0);
var token = handle.ToToken();
var decoded = NexusWorkflowRunHandle.FromToken(token);

Assert.Equal("ns/with+special", decoded.Namespace);
Assert.Equal("wf?id=1&foo=bar", decoded.WorkflowId);
}
}
Loading