using System;
using System.IO;
using NUnit.Framework;
using ServiceStack.Messaging;

namespace ServiceStack.Text.Tests.Issues;

//ZDI-CAN-25837
public class FindTypeVulnerability
{
    static string CreateJsonWithType(string assemblyName) => 
        @"{""__type"": ""MyType, " + assemblyName + @""",}";

    [Test]
    public void Does_not_allow_paths_in_type()
    {
        string[] validTypes =
        [
            AssemblyUtils.WriteType(GetType()),
            AssemblyUtils.WriteType(typeof(string)),
            AssemblyUtils.WriteType(typeof(IMessage)),
        ];
        foreach (var validType in validTypes)
        {
            Assert.That(AssemblyUtils.DefaultValidateTypeName(validType));
            Assert.That(AssemblyUtils.FindType(validType), Is.Not.Null);
        }

        string[] invalidTypes =
        [
            "./MyType",
            "../MyType",
            "..\\MyType",
            ".\\MyType",
        ];
        foreach (var invalidType in invalidTypes)
        {
            Assert.That(AssemblyUtils.DefaultValidateTypeName(invalidType), Is.False);
            Assert.Throws<NotSupportedException>(() => AssemblyUtils.FindType(invalidType));
            var json = CreateJsonWithType(invalidType);
            Assert.Throws<NotSupportedException>(() => JsonSerializer.DeserializeFromString<MemoryStream>(json));
        }
    }
}