Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type.MakeGenericType and MethodInfo.MakeGenericMethod should be marked dangerous #890

Open
mthjones opened this issue Jun 29, 2023 · 0 comments

Comments

@mthjones
Copy link
Member

mthjones commented Jun 29, 2023

Use of these methods can allow for complete bypass of analyzers. For example, it's possible to make an object that to any outside observer is [Immutable] but has interior mutability with no auditing necessary.

Repro:

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using static D2L.CodeStyle.Annotations.Objects;

namespace ImmutableBypass {
	[Immutable]
	public interface IImmutableInterface {
		ImmutableArray<string> Values { get; }
		void Oops();
	}

	[Immutable]
	public sealed class DefinitelyAnImmutableType<[Immutable] T> : IImmutableInterface
		where T : ICollection<string>, new()
	{
		public T SuperImmutableProperty { get; } = new T();
		public ImmutableArray<string> Values => SuperImmutableProperty.ToImmutableArray();
		
		public void Oops() {
			SuperImmutableProperty.Add( Guid.NewGuid().ToString() );
		}
	}

	public static class Program {
		public static void Main( string[] args ) {
			IImmutableInterface immutableObj = CreateImmutableObject();

			Console.WriteLine( immutableObj.Values.Length ); // => 0

			immutableObj.Oops();

			Console.WriteLine( immutableObj.Values.Length ); // => 1
		}

		private static IImmutableInterface CreateImmutableObject() {
			Type immutableType = typeof( DefinitelyAnImmutableType<> ).MakeGenericType( typeof( List<string> ) );
			return (IImmutableInterface)Activator.CreateInstance( immutableType );
		}
	}
}

(note: checking that constraints are immutable could also help, but also potentially possible to bypass by just doing an is/as cast at runtime)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant