Skip to content
Open
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
362 changes: 362 additions & 0 deletions backend/tests/Taskdeck.Api.Tests/RawJsonAdversarialApiTests.cs

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
using System.Text.Json;
using FluentAssertions;
using FsCheck;
using FsCheck.Fluent;
using FsCheck.Xunit;
using Taskdeck.Application.DTOs;
using Taskdeck.Domain.Entities;
using Xunit;

namespace Taskdeck.Application.Tests.Fuzz;

/// <summary>
/// Property-based JSON serialization round-trip tests for Chat DTOs.
/// Key property: serialize then deserialize produces identical object.
/// Exercises adversarial string content in titles, messages, and metadata.
/// </summary>
Comment on lines +12 to +16
Copy link

Copilot AI Apr 13, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The summary states the serialize→deserialize round-trip produces an “identical object”, but the tests currently validate selected fields rather than full structural equality (e.g., timestamps and all ids aren’t consistently asserted). Consider tightening the wording or expanding assertions to match the stated guarantee.

Copilot uses AI. Check for mistakes.
public class ChatDtoSerializationFuzzTests
{
private const int MaxTests = 200;

private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
WriteIndented = false
};

private static Gen<ChatMessageRole> RoleGen() =>
Gen.Elements(ChatMessageRole.User, ChatMessageRole.Assistant, ChatMessageRole.System);

private static Gen<ChatSessionStatus> StatusGen() =>
Gen.Elements(ChatSessionStatus.Active, ChatSessionStatus.Archived);

// ─────────────────────── ChatSessionDto round-trip ───────────────────────

[Property(MaxTest = MaxTests)]
public Property ChatSessionDto_RoundTrip_PreservesAllFields()
{
return Prop.ForAll(
Arb.From(FuzzTestGenerators.AdversarialStringGen()),
Arb.From(StatusGen()),
(title, status) =>
{
var dto = new ChatSessionDto(
Guid.NewGuid(),
Guid.NewGuid(),
Guid.NewGuid(),
title,
status,
DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow,
new List<ChatMessageDto>());

var json = JsonSerializer.Serialize(dto, JsonOptions);
var deserialized = JsonSerializer.Deserialize<ChatSessionDto>(json, JsonOptions);

deserialized.Should().NotBeNull();
deserialized!.Title.Should().Be(title);
deserialized.Status.Should().Be(status);
deserialized.Id.Should().Be(dto.Id);
deserialized.UserId.Should().Be(dto.UserId);
deserialized.BoardId.Should().Be(dto.BoardId);
});
}

// ─────────────────────── ChatMessageDto round-trip ───────────────────────

[Property(MaxTest = MaxTests)]
public Property ChatMessageDto_RoundTrip_PreservesAllFields()
{
return Prop.ForAll(
Arb.From(FuzzTestGenerators.AdversarialStringGen()),
Arb.From(RoleGen()),
Arb.From(FuzzTestGenerators.NullableStringGen()),
(content, role, degradedReason) =>
{
var dto = new ChatMessageDto(
Guid.NewGuid(),
Guid.NewGuid(),
role,
content,
"text",
null,
42,
DateTimeOffset.UtcNow,
degradedReason);

var json = JsonSerializer.Serialize(dto, JsonOptions);
var deserialized = JsonSerializer.Deserialize<ChatMessageDto>(json, JsonOptions);

deserialized.Should().NotBeNull();
deserialized!.Content.Should().Be(content);
deserialized.Role.Should().Be(role);
deserialized.DegradedReason.Should().Be(degradedReason);
deserialized.MessageType.Should().Be("text");
deserialized.TokenUsage.Should().Be(42);
});
}

// ─────────────────────── CreateChatSessionDto round-trip ───────────────────────

[Property(MaxTest = MaxTests)]
public Property CreateChatSessionDto_RoundTrip_Identity()
{
return Prop.ForAll(
Arb.From(FuzzTestGenerators.AdversarialStringGen()),
title =>
{
var dto = new CreateChatSessionDto(title, Guid.NewGuid());

var json = JsonSerializer.Serialize(dto, JsonOptions);
var deserialized = JsonSerializer.Deserialize<CreateChatSessionDto>(json, JsonOptions);

deserialized.Should().NotBeNull();
deserialized!.Title.Should().Be(title);
deserialized.BoardId.Should().Be(dto.BoardId);
});
}

// ─────────────────────── SendChatMessageDto round-trip ───────────────────────

[Property(MaxTest = MaxTests)]
public Property SendChatMessageDto_RoundTrip_Identity()
{
return Prop.ForAll(
Arb.From(FuzzTestGenerators.AdversarialStringGen()),
ArbMap.Default.ArbFor<bool>(),
(content, requestProposal) =>
{
var dto = new SendChatMessageDto(content, requestProposal);

var json = JsonSerializer.Serialize(dto, JsonOptions);
var deserialized = JsonSerializer.Deserialize<SendChatMessageDto>(json, JsonOptions);

deserialized.Should().NotBeNull();
deserialized!.Content.Should().Be(content);
deserialized.RequestProposal.Should().Be(requestProposal);
});
}

// ─────────────────────── ChatSessionDto with messages list ───────────────────────

[Property(MaxTest = MaxTests)]
public Property ChatSessionDto_WithMessages_RoundTrip()
{
return Prop.ForAll(
Arb.From(FuzzTestGenerators.AdversarialStringGen()),
Arb.From(FuzzTestGenerators.AdversarialStringGen()),
(title, msgContent) =>
{
var messages = new List<ChatMessageDto>
{
new(Guid.NewGuid(), Guid.NewGuid(), ChatMessageRole.User,
msgContent, "text", null, null, DateTimeOffset.UtcNow),
new(Guid.NewGuid(), Guid.NewGuid(), ChatMessageRole.Assistant,
title, "text", Guid.NewGuid(), 100, DateTimeOffset.UtcNow)
};

var dto = new ChatSessionDto(
Guid.NewGuid(), Guid.NewGuid(), null, title,
ChatSessionStatus.Active, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow,
messages);

var json = JsonSerializer.Serialize(dto, JsonOptions);
var deserialized = JsonSerializer.Deserialize<ChatSessionDto>(json, JsonOptions);

deserialized.Should().NotBeNull();
deserialized!.RecentMessages.Should().HaveCount(2);
deserialized.RecentMessages[0].Content.Should().Be(msgContent);
deserialized.RecentMessages[1].Content.Should().Be(title);
});
}

// ─────────────────────── Malformed JSON deserialization ───────────────────────

[Theory]
[InlineData("{}")]
[InlineData("{\"title\": null}")]
[InlineData("{\"extra_field\": \"value\"}")]
[InlineData("{\"title\": 12345}")]
[InlineData("null")]
public void CreateChatSessionDto_MalformedJson_HandledGracefully(string json)
{
try
{
var result = JsonSerializer.Deserialize<CreateChatSessionDto>(json, JsonOptions);
// If it deserializes, that's fine — API layer validates
}
catch (JsonException)
{
// Expected for truly malformed JSON
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using FsCheck;
using FsCheck.Fluent;

namespace Taskdeck.Application.Tests.Fuzz;

/// <summary>
/// Shared FsCheck generators for DTO serialization fuzz tests.
/// Centralises adversarial string generation so all fuzz tests
/// exercise the same comprehensive input space.
/// </summary>
internal static class FuzzTestGenerators
{
/// <summary>
/// Generates adversarial strings covering: Unicode edge cases (null byte, BOM,
/// replacement char, surrogates, zero-width, combining, CJK, Arabic, emoji),
/// control characters (bell, backspace, ANSI escape, CRLF), XSS/injection payloads,
/// JSON-sensitive characters (quotes, backslashes), length boundaries (empty,
/// whitespace), explicit null, and FsCheck random strings.
/// </summary>
public static Gen<string> AdversarialStringGen() => Gen.OneOf(
// Unicode edge cases
Gen.Constant("\u0000"), // null byte
Gen.Constant("\uFEFF"), // BOM
Gen.Constant("\uFFFD"), // replacement character
Gen.Constant("\u200B"), // zero-width space
Gen.Constant("\u202E"), // right-to-left override
Gen.Constant("\u0301"), // combining accent
Gen.Constant("\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466"), // family emoji
Gen.Constant("\u7530\u4E2D\u592A\u90CE"), // CJK
Gen.Constant("\u0645\u0631\u062D\u0628\u0627"), // Arabic RTL

// JSON-sensitive characters
Gen.Constant("\"quoted\"string\""),
Gen.Constant("back\\slash"),
Gen.Constant("new\nline\ttab"),
Gen.Constant("null\x00byte"),

// XSS/injection payloads
Gen.Constant("<script>alert('xss')</script>"),
Gen.Constant("'; DROP TABLE boards; --"),
Gen.Constant("{\"nested\": true}"),
Gen.Constant("{{constructor.constructor('return this')()}}"),
Gen.Constant("${7*7}"),

// Length boundary strings
Gen.Constant(""),
Gen.Constant(" "),

// Explicit null
Gen.Constant((string)null!),

// Arbitrary from FsCheck
ArbMap.Default.ArbFor<string>().Generator.Where(s => s != null)
);

/// <summary>
/// Wraps <see cref="AdversarialStringGen"/> as nullable for optional-field testing.
/// </summary>
public static Gen<string?> NullableStringGen() => Gen.OneOf(
Gen.Constant((string?)null),
AdversarialStringGen().Select(s => (string?)s)
);
}
Loading
Loading