Skip to content
Draft
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
11 changes: 11 additions & 0 deletions .autover/changes/snapstart-trace-id-generator.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"Projects": [
{
"Name": "Amazon.Lambda.RuntimeSupport",
"Type": "Patch",
"ChangelogMessages": [
"Set Activity.TraceIdGenerator to a cryptographically random generator after a SnapStart restore so restored execution environments don't repeat trace IDs. A generator set by the function during initialization is not replaced."
]
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Diagnostics;
using System.Security.Cryptography;

namespace Amazon.Lambda.RuntimeSupport.Helpers
{
/// <summary>
/// Trace ID generator used for SnapStart restored execution environments.
/// </summary>
/// <remarks>
/// By default <see cref="Activity"/> generates trace IDs from an in-memory, per-thread pseudo-random
/// generator. A SnapStart snapshot captures that generator's state, so every execution environment restored
/// from the same snapshot continues the same sequence and produces the same trace IDs. This generator reads
/// from the operating system's cryptographic random source instead, which Lambda reseeds after restore.
/// </remarks>
internal static class SnapStartTraceIdGenerator
{
/// <summary>
/// Sets <see cref="Activity.TraceIdGenerator"/> to the SnapStart safe generator, unless a generator is
/// already set. Leaving an existing generator in place keeps one the function set during initialization.
/// </summary>
/// <returns>True if the generator was set; false if a generator was already set.</returns>
internal static bool TrySetTraceIdGenerator()
{
if (Activity.TraceIdGenerator != null)
{
return false;
}

Activity.TraceIdGenerator = GenerateTraceId;
return true;
}

/// <summary>
/// Creates a trace ID from 16 cryptographically random bytes.
/// </summary>
internal static ActivityTraceId GenerateTraceId()
{
Span<byte> bytes = stackalloc byte[16];
RandomNumberGenerator.Fill(bytes);
return ActivityTraceId.CreateFromBytes(bytes);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ internal static async Task<bool> InitializeWithSnapstartAsync(IRuntimeApiClient
await client.ReportInitializationErrorAsync(ex, Constants.LAMBDA_ERROR_TYPE_BEFORE_SNAPSHOT);
return false;
}

// The snapshot copied Activity's in-memory trace ID generator state, so restored environments would
// repeat trace IDs. Switch to a generator backed by OS randomness before the function's after restore
// hooks run, so a hook can still replace it. A generator the function set during init is left as is.
if (SnapStartTraceIdGenerator.TrySetTraceIdGenerator())
{
logger.LogDebug("Set Activity.TraceIdGenerator to a SnapStart safe trace ID generator.");
}

try
{
await ((SnapshotRestore.Registry.RestoreHooksRegistry)restoreHooksRegistry).InvokeAfterRestoreCallbacks();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Amazon.Lambda.RuntimeSupport.Helpers;
using Xunit;
using static Amazon.Lambda.RuntimeSupport.Bootstrap.Constants;

namespace Amazon.Lambda.RuntimeSupport.UnitTests;
[Collection("RuntimeSupportStateCheck")]
public class SnapstartTests
public class SnapstartTests : IDisposable
{
readonly TestHandler _testFunction;
readonly TestInitializer _testInitializer;
Expand Down Expand Up @@ -78,4 +80,51 @@ public async Task VerifyRestoreErrorIsCalledWhenExceptionInAfterRestoreCallables
Assert.True(_testRuntimeApiClient.ReportRestoreErrorAsyncCalled);
}
}

[Fact]
public async Task VerifyTraceIdGeneratorIsSetBeforeAfterRestoreCallbacks()
{
Activity.TraceIdGenerator = null;
Func<ActivityTraceId> generatorSeenByHook = null;
using var bootstrap =
new LambdaBootstrap(_testFunction.BaseHandlerAsync, _testInitializer.InitializeTrueAsync, configuration: new LambdaBootstrapConfiguration(false, true));
bootstrap.Client = _testRuntimeApiClient;
Core.SnapshotRestore.RegisterAfterRestore(() =>
{
generatorSeenByHook = Activity.TraceIdGenerator;
return ValueTask.CompletedTask;
});
await bootstrap.RunAsync(_testFunction.CancellationSource.Token);

Assert.Equal((Func<ActivityTraceId>)SnapStartTraceIdGenerator.GenerateTraceId, generatorSeenByHook);
}

[Fact]
public async Task VerifyTraceIdGeneratorSetDuringInitIsNotReplaced()
{
Func<ActivityTraceId> customGenerator = ActivityTraceId.CreateRandom;
Activity.TraceIdGenerator = customGenerator;
using var bootstrap =
new LambdaBootstrap(_testFunction.BaseHandlerAsync, _testInitializer.InitializeTrueAsync, configuration: new LambdaBootstrapConfiguration(false, true));
bootstrap.Client = _testRuntimeApiClient;
await bootstrap.RunAsync(_testFunction.CancellationSource.Token);

Assert.Same(customGenerator, Activity.TraceIdGenerator);
}

[Fact]
public void VerifyGeneratedTraceIdsAreUnique()
{
var first = SnapStartTraceIdGenerator.GenerateTraceId();
var second = SnapStartTraceIdGenerator.GenerateTraceId();

Assert.NotEqual(default, first);
Assert.NotEqual(first, second);
}

public void Dispose()
{
// Activity.TraceIdGenerator is process wide, so reset it for the tests that follow.
Activity.TraceIdGenerator = null;
}
}
Loading