示例#1
0
        public void HandlesAsyncMethods()
        {
            var m = TestHelper.RewriteAndGetMethodWrappedInScope(@"
                using System.Threading.Tasks;

                class Program {
                    void M() => Main().Wait(200);

                    async Task Main() {
                        await Task.Delay(100);
                    }
                }
            ", "Program", "M", new AssemblyGuardSettings {
                ApiPolicy = ApiPolicy.SafeDefault()
                            .Namespace("System.Runtime.CompilerServices", ApiAccess.Allowed)
                            .Namespace("System.Threading.Tasks", ApiAccess.Allowed)
            },
                                                                 new RuntimeGuardSettings {
                TimeLimit = TimeSpan.FromMilliseconds(100),
            });
            var ex = Assert.Throws <TargetInvocationException>(() => m());

            Assert.IsType <AggregateException>(ex.InnerException);
            Assert.IsType <TimeGuardException>(ex.InnerException?.InnerException);
        }
示例#2
0
        public void ThrowsGuardException_ForAsyncMethodWithTry()
        {
            var compiled = TestHelper.Compile(@"
                using System;
                using System.Threading.Tasks;

                class Program {
                    async Task Main() {
                        Console.WriteLine();

                        try {
                            await Task.Yield();
                        } catch { }
                    }
                }
            ");
            var ex       = Assert.Throws <AssemblyGuardException>(
                () => AssemblyGuard.Rewrite(compiled, Stream.Null, new AssemblyGuardSettings {
                ApiPolicy = ApiPolicy.SafeDefault()
                            .Namespace("System.Runtime.CompilerServices", ApiAccess.Allowed)
                            .Namespace("System.Threading.Tasks", ApiAccess.Allowed)
            })
                );

            Assert.Contains("System.Console", ex.Message);
        }
示例#3
0
 public static ApiPolicy CreatePolicy() => ApiPolicy.SafeDefault()
 .Namespace("System", Neutral, SetupSystem)
 .Namespace("System.Collections.Concurrent", Neutral, SetupSystemCollectionsConcurrent)
 .Namespace("System.Collections.Specialized", Neutral, SetupSystemCollectionsSpecialized)
 .Namespace("System.Diagnostics", Neutral, SetupSystemDiagnostics)
 .Namespace("System.Globalization", Neutral, SetupSystemGlobalization)
 .Namespace("System.IO", Neutral, SetupSystemIO)
 .Namespace("System.Linq.Expressions", Neutral, SetupSystemLinqExpressions)
 .Namespace("System.Net", Neutral, SetupSystemNet)
 .Namespace("System.Numerics", Neutral, SetupSystemNumerics)
 .Namespace("System.Reflection", Neutral, SetupSystemReflection)
 .Namespace("System.Runtime.InteropServices", Neutral, SetupSystemRuntimeInteropServices)
 .Namespace("System.Security.Cryptography", Neutral, SetupSystemSecurityCryptography)
 .Namespace("System.Web", Neutral, SetupSystemWeb)
 .Namespace("SharpLab.Runtime.Internal", Neutral,
            n => n.Type(typeof(Flow), Neutral,
                        t => t.Member(nameof(Flow.ReportException), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportLineStart), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportValue), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportRefValue), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportSpanValue), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportRefSpanValue), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportReadOnlySpanValue), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportRefReadOnlySpanValue), Allowed, NoGuardRewriter.Default)
                        ).Type(typeof(MemoryGraphArgumentNames), Neutral,
                               t => t.Member(nameof(MemoryGraphArgumentNames.AllocateNext), Allowed, CountArgumentRewriter.Default)
                               .Member(nameof(MemoryGraphArgumentNames.AddToNext), Allowed, NoGuardRewriter.Default)
                               )
            )
 .Namespace("", Neutral,
            n => n.Type(typeof(SharpLabObjectExtensions), Allowed)
            .Type(typeof(Inspect), Allowed)
            )
     #if !NETCOREAPP
 .Namespace("Microsoft.FSharp.Core", Neutral, SetupFSharpCore)
 .Namespace("Microsoft.FSharp.Collections", Neutral,
            n => n.Type(typeof(FSharpList <>), Allowed)
            .Type(typeof(ListModule), Neutral,
                  t => t.Member(nameof(ListModule.Iterate), Allowed)
                  )
            .Type(typeof(SeqModule), Neutral,
                  t => t.Member(nameof(SeqModule.ToArray), Allowed, CollectedEnumerableArgumentRewriter.Default)
                  .Member(nameof(SeqModule.ToList), Allowed, CollectedEnumerableArgumentRewriter.Default)
                  )
            )
     #endif
 .Namespace("Microsoft.VisualBasic", Neutral, SetupMicrosoftVisualBasic)
 .Namespace("Microsoft.VisualBasic.CompilerServices", Neutral,
            n => n.Type(typeof(Conversions), Allowed,
                        t => t.Member(nameof(Conversions.FromCharAndCount), Allowed, new CountArgumentRewriter("Count"))
                        // Those need extra review
                        .Member(nameof(Conversions.ChangeType), Denied)
                        .Member(nameof(Conversions.FallbackUserDefinedConversion), Denied)
                        .Member(nameof(Conversions.FromCharArray), Denied)
                        .Member(nameof(Conversions.FromCharArraySubset), Denied)
                        .Member(nameof(Conversions.ToCharArrayRankOne), Denied)
                        )
            .Type(typeof(StandardModuleAttribute), Allowed)
            );
示例#4
0
        private static AssemblyGuardSettings CreateGuardSettings(ApiPolicy apiPolicy)
        {
            var settings = AssemblyGuardSettings.DefaultForCSharpAssembly();

            settings.ApiPolicy = apiPolicy;
            settings.AllowExplicitLayoutInTypesMatchingPattern    = new Regex(settings.AllowExplicitLayoutInTypesMatchingPattern.ToString(), RegexOptions.Compiled);
            settings.AllowPointerOperationsInTypesMatchingPattern = new Regex(settings.AllowPointerOperationsInTypesMatchingPattern.ToString(), RegexOptions.Compiled);
            return(settings);
        }
示例#5
0
        public void Type_CanAddTypeInEmptyNamespace()
        {
            var policy = ApiPolicy.SafeDefault();

            policy.Namespace("", ApiAccess.Neutral, n => {
                n.Type(typeof(TestClassWithoutNamespace), ApiAccess.Allowed);
            });

            Assert.Equal(ApiAccess.Allowed, policy.Namespaces[""].Types[nameof(TestClassWithoutNamespace)].Access);
        }
示例#6
0
 public static ApiPolicy CreatePolicy() => ApiPolicy.SafeDefault()
 .Namespace("System", Neutral, SetupSystem)
 .Namespace("System.Threading", Neutral, SetupThreading)
 .Namespace("System.Collections.Concurrent", Neutral, SetupSystemCollectionsConcurrent)
 .Namespace("System.Collections.Specialized", Neutral, SetupSystemCollectionsSpecialized)
 //.Namespace("System.Globalization", Neutral, SetupSystemGlobalization)
 //.Namespace("System.IO", Neutral, SetupSystemIO)
 //.Namespace("System.Linq.Expressions", Neutral, SetupSystemLinqExpressions)
 //.Namespace("System.Net", Neutral, SetupSystemNet)
 .Namespace("System.Numerics", Neutral, SetupSystemNumerics);
示例#7
0
        private static AssemblyGuardSettings CreateGuardSettings(ApiPolicy apiPolicy)
        {
            var settings = AssemblyGuardSettings.DefaultForCSharpAssembly();

            settings.ApiPolicy = apiPolicy;
            settings.AllowExplicitLayoutInTypesMatchingPattern         = new Regex(settings.AllowExplicitLayoutInTypesMatchingPattern.ToString(), RegexOptions.Compiled);
            settings.AllowPointerOperationsInTypesMatchingPattern      = new Regex(settings.AllowPointerOperationsInTypesMatchingPattern.ToString(), RegexOptions.Compiled);
            settings.AllowCustomTypesMatchingPatternInSystemNamespaces = new Regex(
                settings.AllowCustomTypesMatchingPatternInSystemNamespaces.ToString() + @"|System\.Range|System\.Index|System\.Extensions", RegexOptions.Compiled
                );
            return(settings);
        }
示例#8
0
 private AssemblyGuardSettings GetGuardSettingsForTestDisposable()
 {
     return(new AssemblyGuardSettings {
         ApiPolicy = ApiPolicy.SafeDefault().Namespace(
             "Unbreakable.Tests", ApiAccess.Neutral,
             n => n.Type(
                 typeof(TestDisposable), ApiAccess.Allowed,
                 t => t.Constructor(ApiAccess.Allowed, new DisposableReturnRewriter())
                 .Member(nameof(TestDisposable.GetSelfToRewrite), ApiAccess.Allowed, new DisposableReturnRewriter())
                 )
             )
     });
 }
示例#9
0
 public static ApiPolicy CreatePolicy() => ApiPolicy.SafeDefault()
 .Namespace("System", Neutral,
            n => n.Type(typeof(Console), Neutral,
                        t => t.Member(nameof(Console.Write), Allowed)
                        .Member(nameof(Console.WriteLine), Allowed)
                        // required by F#'s printf
                        .Getter(nameof(Console.Out), Allowed)
                        ).Type(typeof(STAThreadAttribute), Allowed)
            .Type(typeof(NotImplementedException), Neutral, t => t.Constructor(Allowed))
            .Type(typeof(Type), Neutral, SetupSystemType)
            )
 .Namespace("System.Diagnostics", Neutral, SetupSystemDiagnostics)
 .Namespace("System.Reflection", Neutral, SetupSystemReflection)
 .Namespace("System.Linq.Expressions", Neutral, SetupSystemLinqExpressions)
 .Namespace("System.IO", Neutral,
            // required by F#'s printf
            n => n.Type(typeof(TextWriter), Neutral)
            )
 .Namespace("SharpLab.Runtime.Internal", Neutral,
            n => n.Type(typeof(Flow), Neutral,
                        t => t.Member(nameof(Flow.ReportException), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportLineStart), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportValue), Allowed, NoGuardRewriter.Default)
                        )
            )
 .Namespace("", Neutral,
            n => n.Type(typeof(SharpLabObjectExtensions), Allowed)
            )
 .Namespace("Microsoft.FSharp.Core", Neutral, SetupFSharpCore)
 .Namespace("Microsoft.FSharp.Collections", Neutral,
            n => n.Type(typeof(FSharpList <>), Allowed)
            .Type(typeof(ListModule), Neutral,
                  t => t.Member(nameof(ListModule.Iterate), Allowed)
                  )
            .Type(typeof(SeqModule), Neutral,
                  t => t.Member(nameof(SeqModule.ToArray), Allowed, CollectedEnumerableArgumentRewriter.Default)
                  .Member(nameof(SeqModule.ToList), Allowed, CollectedEnumerableArgumentRewriter.Default)
                  )
            )
 .Namespace("Microsoft.VisualBasic.CompilerServices", Neutral,
            n => n.Type(typeof(Conversions), Allowed,
                        t => t.Member(nameof(Conversions.FromCharAndCount), Allowed, new CountArgumentRewriter("Count"))
                        // Those need extra review
                        .Member(nameof(Conversions.ChangeType), Denied)
                        .Member(nameof(Conversions.FallbackUserDefinedConversion), Denied)
                        .Member(nameof(Conversions.FromCharArray), Denied)
                        .Member(nameof(Conversions.FromCharArraySubset), Denied)
                        .Member(nameof(Conversions.ToCharArrayRankOne), Denied)
                        )
            .Type(typeof(StandardModuleAttribute), Allowed)
            );
示例#10
0
        public void HandlesGenericReferenceTypes(string code, int expected)
        {
            var m = TestHelper.RewriteAndGetMethodWrappedInScope(@"
                using System;
                using Unbreakable.Tests.Internal;
                class C {
                    " + code + @"
                }
            ", "C", "M", new AssemblyGuardSettings {
                ApiPolicy = ApiPolicy.SafeDefault().Namespace("Unbreakable.Tests.Internal", ApiAccess.Allowed)
            });

            Assert.Equal(expected, m());
        }
示例#11
0
        private static AssemblyGuardSettings CreateGuardSettings(ApiPolicy apiPolicy)
        {
            var settings = AssemblyGuardSettings.DefaultForCSharpAssembly();

            settings.ApiPolicy = apiPolicy;

            Regex?CompileRegex(Regex?original) => original != null
                ? new Regex(original.ToString(), original.Options | RegexOptions.Compiled)
                : null;

            settings.AllowExplicitLayoutInTypesMatchingPattern    = CompileRegex(settings.AllowExplicitLayoutInTypesMatchingPattern);
            settings.AllowPointerOperationsInTypesMatchingPattern = CompileRegex(settings.AllowPointerOperationsInTypesMatchingPattern);

            return(settings);
        }
示例#12
0
        public void AllowsTypesInEmptyNamespace_IfAllowed()
        {
            var m = TestHelper.RewriteAndGetMethodWrappedInScope(@"
                using System;
                class C {
                    public object M() {
                        return new " + nameof(TestClassWithoutNamespace) + @"();
                    }
                }
            ", "C", "M", new AssemblyGuardSettings {
                ApiPolicy = ApiPolicy.SafeDefault().Namespace("", ApiAccess.Allowed)
            });

            Assert.NotNull(m());
        }
示例#13
0
        public void ThrowsGuardException_ForPointerTypes(string code)
        {
            // pointers, available in local functions due to a Roslyn bug, reported by Andy Gocke‏ (@andygocke)
            var policy = ApiPolicy.SafeDefault()
                         .Namespace("System.Security", ApiAccess.Neutral, n => n.Type(typeof(UnverifiableCodeAttribute), ApiAccess.Allowed));
            var compiled = TestHelper.Compile(@"
                class X {
                    unsafe void M(int a) { " + code + @" }
                }
            ", allowUnsafe: true);

            Assert.Throws <AssemblyGuardException>(
                () => AssemblyGuard.Rewrite(compiled, new MemoryStream(), new AssemblyGuardSettings {
                ApiPolicy = policy
            })
                );
        }
示例#14
0
 public Executor(
     IAssemblyResolver assemblyResolver,
     ISymbolReaderProvider symbolReaderProvider,
     ApiPolicy apiPolicy,
     IReadOnlyCollection <IAssemblyRewriter> rewriters,
     RecyclableMemoryStreamManager memoryStreamManager,
     ExecutionResultSerializer serializer,
     IMonitor monitor
     )
 {
     _assemblyResolver     = assemblyResolver;
     _symbolReaderProvider = symbolReaderProvider;
     _guardSettings        = CreateGuardSettings(apiPolicy);
     _rewriters            = rewriters;
     _memoryStreamManager  = memoryStreamManager;
     _serializer           = serializer;
     _monitor = monitor;
 }
示例#15
0
        public void ThrowsGuardException_ForDelegatesCreatedFromMethodsWithRewriters(string code)
        {
            var compiled = TestHelper.Compile(@"
                using System;
                using System.Linq.Expressions;
                class C {
                    void M() { " + code + @" }
                }"
                                              );
            var policy = ApiPolicy.SafeDefault()
                         .Namespace("System.Linq.Expressions", ApiAccess.Allowed)
                         .Namespace("System.Reflection", ApiAccess.Allowed);

            Assert.Throws <AssemblyGuardException>(
                () => AssemblyGuard.Rewrite(compiled, new MemoryStream(), new AssemblyGuardSettings {
                ApiPolicy = policy
            })
                );
        }
示例#16
0
 public Executor(
     IAssemblyResolver assemblyResolver,
     ISymbolReaderProvider symbolReaderProvider,
     ApiPolicy apiPolicy,
     IReadOnlyCollection <IAssemblyRewriter> rewriters,
     RecyclableMemoryStreamManager memoryStreamManager,
     ExecutionResultSerializer serializer,
     IMonitor monitor
     ) : base(
         assemblyResolver,
         symbolReaderProvider,
         apiPolicy,
         rewriters,
         memoryStreamManager,
         serializer,
         monitor
         )
 {
 }
示例#17
0
        public void HandlesAsyncMethods()
        {
            var m = TestHelper.RewriteAndGetMethodWrappedInScope(@"
                using System.Threading.Tasks;

                class Program {
                    bool M() => Main().Wait(100);

                    async Task Main() {
                        await Task.Yield();
                    }
                }
            ", "Program", "M", new AssemblyGuardSettings {
                ApiPolicy = ApiPolicy.SafeDefault()
                            .Namespace("System.Runtime.CompilerServices", ApiAccess.Allowed)
                            .Namespace("System.Threading.Tasks", ApiAccess.Allowed)
            });

            Assert.True(m() is true);
        }
示例#18
0
        public void DoesNotEnforceApiPolicy_ForUserCode()
        {
            var compiled = TestHelper.Compile(@"
                namespace N {
                    class C1 {
                        void M(C2 c2) { c2.M(); }
                    }

                    class C2 {
                        public void M() {}
                    }
                }
            ");

            var exception = Record.Exception(() => AssemblyGuard.Rewrite(compiled, new MemoryStream(), new AssemblyGuardSettings {
                ApiPolicy = ApiPolicy.SafeDefault().Namespace("N", ApiAccess.Denied)
            }));

            Assert.Null(exception);
        }
示例#19
0
    public ApimStack()
    {
        var config = new Pulumi.Config();

        var tenantId = config.Require("tenantId");
        var authorizationEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize";
        var tokenEndpoint         = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token";
        var defaultScope          = config.Require("scope");
        var clientId     = config.Require("clientId");
        var clientSecret = config.Require("clientSecret");

        // Create an Azure Resource Group
        var resourceGroup = new ResourceGroup("rg-chris-apim");

        //Service Plan
        var appServicePlan = new Plan("plan-api", new PlanArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Kind = "App",
            Sku  = new PlanSkuArgs
            {
                Tier = "Basic",
                Size = "B1"
            }
        });

        var app = new AppService("app-api", new AppServiceArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AppServicePlanId  = appServicePlan.Id
        });

        var apim = new Service("apim-api", new ServiceArgs {
            ResourceGroupName = resourceGroup.Name,
            PublisherName     = "chrisjensenuk",
            PublisherEmail    = "*****@*****.**",
            SkuName           = "Developer_1"
        });

        var apimAuth = new AuthorizationServer("apim-oauth", new AuthorizationServerArgs
        {
            ApiManagementName          = apim.Name,
            ResourceGroupName          = resourceGroup.Name,
            DisplayName                = "apim-oauth",
            ClientRegistrationEndpoint = "http://localhost",
            GrantTypes                  = { "authorizationCode" },
            AuthorizationEndpoint       = authorizationEndpoint,
            AuthorizationMethods        = { "GET", "POST" },
            TokenEndpoint               = tokenEndpoint,
            ClientAuthenticationMethods = "Body",
            BearerTokenSendingMethods   = "authorizationHeader",
            DefaultScope                = defaultScope,
            ClientId     = clientId,
            ClientSecret = clientSecret
        });

        var api = new Api("example-api", new ApiArgs
        {
            ResourceGroupName = resourceGroup.Name,
            ApiManagementName = apim.Name,
            Revision          = "1",
            DisplayName       = "Example API",
            Path      = "example",
            Protocols =
            {
                "https"
            },
            Oauth2Authorization = new ApiOauth2AuthorizationArgs
            {
                AuthorizationServerName = apimAuth.Name
            },
            Import = new ApiImportArgs
            {
                ContentFormat = "openapi+json",
                ContentValue  = Constants.SwaggerJson
            },
            ServiceUrl = app.Name.Apply(n => $"http://{n}.azurewebsites.net")
        });

        var policy = new ApiPolicy("example-api-policy", new ApiPolicyArgs
        {
            ResourceGroupName = resourceGroup.Name,
            ApiManagementName = apim.Name,
            ApiName           = api.Name,
            XmlContent        = Constants.ApiPolicyXml
        });
    }
示例#20
0
 public static ApiPolicy CreatePolicy() => ApiPolicy.SafeDefault()
 .Namespace("System", Neutral,
            n => n.Type(typeof(Console), Neutral,
                        t => t.Member(nameof(Console.Write), Allowed)
                        .Member(nameof(Console.WriteLine), Allowed)
                        // required by F#'s printf
                        .Getter(nameof(Console.Out), Allowed)
                        ).Type(typeof(STAThreadAttribute), Allowed)
            .Type(typeof(NotImplementedException), Neutral, t => t.Constructor(Allowed))
            .Type(typeof(Type), Neutral, SetupSystemType)
            )
 .Namespace("System.Diagnostics", Neutral, SetupSystemDiagnostics)
 .Namespace("System.Reflection", Neutral, SetupSystemReflection)
 .Namespace("System.Linq.Expressions", Neutral, SetupSystemLinqExpressions)
 .Namespace("System.IO", Neutral,
            // required by F#'s printf
            n => n.Type(typeof(TextWriter), Neutral)
            )
 .Namespace("SharpLab.Runtime.Internal", Neutral,
            n => n.Type(typeof(Flow), Neutral,
                        t => t.Member(nameof(Flow.ReportException), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportLineStart), Allowed, NoGuardRewriter.Default)
                        .Member(nameof(Flow.ReportValue), Allowed, NoGuardRewriter.Default)
                        )
            )
 .Namespace("", Neutral,
            n => n.Type(typeof(SharpLabObjectExtensions), Allowed)
            )
 .Namespace("Microsoft.FSharp.Core", Neutral,
            n => n.Type(typeof(CompilationArgumentCountsAttribute), Allowed)
            .Type(typeof(CompilationMappingAttribute), Allowed)
            .Type(typeof(EntryPointAttribute), Allowed)
            .Type(typeof(ExtraTopLevelOperators), Neutral,
                  t => t.Member(nameof(ExtraTopLevelOperators.CreateDictionary), Allowed, CollectedEnumerableArgumentRewriter.Default)
                  .Member(nameof(ExtraTopLevelOperators.CreateSet), Allowed, CollectedEnumerableArgumentRewriter.Default)
                  .Member(nameof(ExtraTopLevelOperators.LazyPattern), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.PrintFormat), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.PrintFormatLine), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.PrintFormatToTextWriter), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.PrintFormatLineToTextWriter), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.PrintFormatToString), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.SpliceExpression), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.SpliceUntypedExpression), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.ToByte), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.ToDouble), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.ToSByte), Allowed)
                  .Member(nameof(ExtraTopLevelOperators.ToSingle), Allowed)
                  )
            .Type(typeof(ExtraTopLevelOperators.Checked), Allowed)
            .Type(typeof(FSharpChoice <,>), Allowed)
            .Type(typeof(FSharpFunc <,>), Allowed)
            .Type(typeof(FSharpOption <>), Allowed)
            .Type(typeof(LanguagePrimitives), Neutral,
                  t => t.Getter(nameof(LanguagePrimitives.GenericComparer), Allowed)
                  .Getter(nameof(LanguagePrimitives.GenericEqualityComparer), Allowed)
                  .Getter(nameof(LanguagePrimitives.GenericEqualityERComparer), Allowed)
                  )
            .Type(typeof(OptimizedClosures.FSharpFunc <, ,>), Allowed)
            .Type(typeof(OptimizedClosures.FSharpFunc <, , ,>), Allowed)
            .Type(typeof(OptimizedClosures.FSharpFunc <, , , ,>), Allowed)
            .Type(typeof(Microsoft.FSharp.Core.Operators), Allowed,
                  t => t.Member("ConsoleError", Denied)
                  .Member("ConsoleIn", Denied)
                  .Member("ConsoleOut", Denied)
                  .Member("Lock", Denied)
                  )
            .Type(typeof(PrintfFormat <, , ,>), Allowed)
            .Type(typeof(PrintfFormat <, , , ,>), Allowed)
            .Type(typeof(PrintfModule), Neutral,
                  t => t.Member(nameof(PrintfModule.PrintFormat), Allowed)
                  .Member(nameof(PrintfModule.PrintFormatLine), Allowed)
                  .Member(nameof(PrintfModule.PrintFormatToTextWriter), Allowed)
                  .Member(nameof(PrintfModule.PrintFormatLineToTextWriter), Allowed)
                  )
            .Type(typeof(Unit), Allowed)
            )
 .Namespace("Microsoft.FSharp.Collections", Neutral,
            n => n.Type(typeof(FSharpList <>), Allowed)
            )
 .Namespace("Microsoft.VisualBasic.CompilerServices", Neutral,
            n => n.Type(typeof(Conversions), Allowed,
                        t => t.Member(nameof(Conversions.FromCharAndCount), Allowed, new CountArgumentRewriter("Count"))
                        // Those need extra review
                        .Member(nameof(Conversions.ChangeType), Denied)
                        .Member(nameof(Conversions.FallbackUserDefinedConversion), Denied)
                        .Member(nameof(Conversions.FromCharArray), Denied)
                        .Member(nameof(Conversions.FromCharArraySubset), Denied)
                        .Member(nameof(Conversions.ToCharArrayRankOne), Denied)
                        )
            .Type(typeof(StandardModuleAttribute), Allowed)
            );
        private void WriteNamespaceReport(StreamWriter writer, string @namespace, IEnumerable <Type> types, ApiPolicy policy)
        {
            if (!policy.Namespaces.TryGetValue(@namespace, out var namespacePolicy))
            {
                return;
            }
            writer.WriteLine(@namespace);
            if (namespacePolicy.Access == Denied)
            {
                return;
            }

            var typesWithNames = types.Select(type => new {
                value = type,
                name  = @namespace.Length > 0 ? type.FullName.Substring(@namespace.Length + 1) : type.FullName
            });

            foreach (var type in typesWithNames.OrderBy(t => t.name))
            {
                WriteTypeReport(writer, type.value, type.name, namespacePolicy);
            }
        }
示例#22
0
    public DeploymentStack()
    {
        // Define variables
        var config             = new Pulumi.Config();
        var rgName             = string.Format("{0}-{1}-{2}-{3}", config.Require("prefix"), config.Require("resourceFunction"), config.Require("environment"), config.Require("azureRegion"));
        var storageAccountName = string.Format("{0}{1}sa{2}{3}", config.Require("prefix"), config.Require("resourceFunction"), config.Require("environment"), config.Require("azureRegion"));
        var apimName           = string.Format("{0}-{1}-{2}-{3}", config.Require("prefix"), config.Require("resourceFunction"), config.Require("environment"), config.Require("azureRegion"));
        var kvName             = string.Format("{0}-{1}-kv-{2}-{3}", config.Require("prefix"), config.Require("resourceFunction"), config.Require("environment"), config.Require("azureRegion"));
        var appInsightsName    = string.Format("{0}-{1}-appinsights-{2}-{3}", config.Require("prefix"), config.Require("resourceFunction"), config.Require("environment"), config.Require("azureRegion"));
        var tags = new InputMap <string>()
        {
            { "belongsto", "Core Resources" },
            { "environment", "Development" },
            { "costcenter", "Backend" },
            { "owner", "IT" }
        };

        // Get current identity details
        var clientConfig     = Output.Create(Pulumi.Azure.Core.Invokes.GetClientConfig());
        var tenantId         = clientConfig.Apply(c => c.TenantId);
        var currentPrincipal = clientConfig.Apply(c => c.ObjectId);

        // Create the Azure Resource Group
        var rg = new ResourceGroup("rg", new ResourceGroupArgs()
        {
            Name     = rgName,
            Location = config.Require("azureLocation"),
            Tags     = tags
        });

        // Create the storage account to contain policy, OpenApi and other deployment related files
        var sa = new Account("sa", new AccountArgs
        {
            ResourceGroupName = rg.Name,
            Name                   = storageAccountName,
            AccountKind            = "StorageV2",
            AccountReplicationType = "LRS",
            AccountTier            = "Standard",
            EnableHttpsTrafficOnly = true,
            Tags                   = tags
        },
                             new CustomResourceOptions()
        {
            DependsOn = { rg }
        });
        var saContainerApim = new Container("apim-files",
                                            new ContainerArgs()
        {
            StorageAccountName = sa.Name, ContainerAccessType = "private"
        },
                                            new CustomResourceOptions()
        {
            DependsOn = { rg }
        });

        var saContainerApi = new Container("api-files",
                                           new ContainerArgs()
        {
            StorageAccountName = sa.Name, ContainerAccessType = "private"
        },
                                           new CustomResourceOptions()
        {
            DependsOn = { rg }
        });

        // Create key vault to contain the certificate secret
        var kv = new KV.KeyVault("kv", new KV.KeyVaultArgs()
        {
            Name = kvName,
            ResourceGroupName        = rg.Name,
            EnabledForDiskEncryption = false,
            SkuName        = "standard",
            TenantId       = tenantId,
            AccessPolicies =
            {
                new KeyVaultAccessPoliciesArgs
                {
                    TenantId               = tenantId,
                    ObjectId               = currentPrincipal,
                    SecretPermissions      = { "get" },
                    CertificatePermissions ={ "delete", "create", "get", "import", "list", "update" },
                }
            },
            Tags = tags
        });

        // Upload the certificate to Key Vault --> Currently disabled because no valid pfx which breaks the deployment
        // var pfxBytes = System.IO.File.ReadAllBytes("certificates/"+ config.Require("customDomainsCertificateName"));
        // var cert = new KV.Certificate("apim-tls-certificate", new KV.CertificateArgs()
        // {
        //     Name = "apim-tls-certificate",
        //     KeyVaultId = kv.Id,
        //     KeyVaultCertificate = new CertificateCertificateArgs()
        //     {
        //         Contents = System.Convert.ToBase64String(pfxBytes),
        //         Password = config.Require("customDomainsCertificatePasword")
        //     },
        //     CertificatePolicy = new CertificateCertificatePolicyArgs()
        //     {
        //         IssuerParameters = new CertificateCertificatePolicyIssuerParametersArgs()
        //         {
        //             Name = config.Require("customDomainsCertificateIssuer")
        //         },
        //         KeyProperties = new CertificateCertificatePolicyKeyPropertiesArgs()
        //         {
        //             Exportable = true,
        //             KeySize = 2048,
        //             KeyType = "RSA",
        //             ReuseKey = false
        //         },
        //         SecretProperties = new CertificateCertificatePolicySecretPropertiesArgs()
        //         {
        //             ContentType = "application/x-pkcs12"
        //         }
        //     }
        // },
        // new CustomResourceOptions()
        // {
        //     DependsOn = { rg, kv }
        // });

        // APIM resource
        var apim = new Service("apim", new ServiceArgs()
        {
            Name = apimName,
            ResourceGroupName = rg.Name,
            SkuName           = "Developer_1",
            PublisherEmail    = config.Require("publisherEmail"),
            PublisherName     = config.Require("publisherName"),
            Tags     = tags,
            Identity = new ServiceIdentityArgs()
            {
                Type = "SystemAssigned"
            }
        },
                               new CustomResourceOptions()
        {
            CustomTimeouts = new CustomTimeouts {
                Create = TimeSpan.FromMinutes(60)
            },
            DependsOn = { rg, sa, kv }
        });

        // Change Key Vault policy to be able to have APIM access the certificate
        // var kvApimPolicy = new KV.AccessPolicy("apim-policy", new KV.AccessPolicyArgs()
        // {
        //     TenantId = tenantId,
        //     ObjectId = apim.Identity.PrincipalId,
        //     SecretPermissions = {"get"},
        //     CertificatePermissions = {"get", "list"},
        //     KeyVaultId = kv.Id
        // });

        // Set custom domain
        // Call Powershell to assign custom domain to APIM instance

        // Create product on APIM
        var apimProduct = new Product("apimProduct", new ProductArgs()
        {
            ResourceGroupName    = rg.Name,
            ApiManagementName    = apim.Name,
            DisplayName          = config.Require("productName"),
            ProductId            = config.Require("productId"),
            ApprovalRequired     = bool.Parse(config.Require("productApprovalRequired")),
            Published            = bool.Parse(config.Require("productPublished")),
            SubscriptionRequired = bool.Parse(config.Require("productSubscriptionRequired")),
            SubscriptionsLimit   = int.Parse(config.Require("productSubscriptionLimit"))
        },
                                      new CustomResourceOptions()
        {
            DependsOn = { apim }
        });
        var apimProductPolicy = new ProductPolicy("apimProductPolicy", new ProductPolicyArgs()
        {
            ResourceGroupName = rg.Name,
            ApiManagementName = apim.Name,
            ProductId         = config.Require("productId"),
            XmlContent        = @"<policies>
                            <inbound>
                                <base />
                            </inbound>
                            <backend>
                                <base />
                            </backend>
                            <outbound>
                                <set-header name='Server' exists-action='delete' />
                                <set-header name='X-Powered-By' exists-action='delete' />
                                <set-header name='X-AspNet-Version' exists-action='delete' />
                                <base />
                            </outbound>
                            <on-error>
                                <base />
                            </on-error>
                        </policies>"
        },
                                                  new CustomResourceOptions()
        {
            DependsOn = { apim, apimProduct }
        });

        // Create user
        var apimUser = new User("user", new UserArgs()
        {
            ResourceGroupName = rg.Name,
            ApiManagementName = apim.Name,
            UserId            = string.Format("{0}-user", config.Require("productId")),
            Email             = string.Format("{0}-{1}@didago.nl", config.Require("productId"), config.Require("environment")),
            FirstName         = "user",
            LastName          = config.Require("productName"),
            State             = "active"
        },
                                new CustomResourceOptions()
        {
            DependsOn = { apim }
        });

        // Create subscription
        var apimSubscription = new Subscription("subscription", new SubscriptionArgs()
        {
            ResourceGroupName = rg.Name,
            ApiManagementName = apim.Name,
            DisplayName       = "Some subscription",
            ProductId         = apimProduct.Id,
            UserId            = apimUser.Id,
            PrimaryKey        = config.Require("productSubscriptionKey")
        },
                                                new CustomResourceOptions()
        {
            DependsOn = { apim, apimProduct, apimUser }
        });

        // Create Application Insights
        var appInsights = new Insights("appinsights", new InsightsArgs()
        {
            Name = appInsightsName,
            ResourceGroupName = rg.Name,
            ApplicationType   = "web",
            Tags = tags
        });
        // Create APIM diagnostics logger
        var apimLogger = new Logger("apimLogger", new LoggerArgs()
        {
            Name = $"{apimName}-logger",
            ResourceGroupName   = rg.Name,
            ApiManagementName   = apim.Name,
            ApplicationInsights = new LoggerApplicationInsightsArgs()
            {
                InstrumentationKey = appInsights.InstrumentationKey
            }
        },
                                    new CustomResourceOptions()
        {
            DependsOn = { appInsights, apim }
        });

        // Add health probe to APIM, create operation, policy and assign to product
        var apiHealthProbe = new Api("healthProbe", new ApiArgs()
        {
            ResourceGroupName = rg.Name,
            ApiManagementName = apim.Name,
            DisplayName       = "Health probe",
            Path      = "health-probe",
            Protocols = "https",
            Revision  = "1"
        },
                                     new CustomResourceOptions()
        {
            DependsOn = { apim }
        });
        var apimHealthProbeOperation = new ApiOperation("pingOperation", new ApiOperationArgs()
        {
            ResourceGroupName = rg.Name,
            ApiManagementName = apim.Name,
            ApiName           = apiHealthProbe.Name,
            DisplayName       = "Ping",
            Method            = "GET",
            UrlTemplate       = "/",
            OperationId       = "get-ping"
        },
                                                        new CustomResourceOptions()
        {
            DependsOn = { apiHealthProbe }
        });
        var apiHealthProbePolicy = new ApiPolicy("healthProbePolicy", new ApiPolicyArgs()
        {
            ResourceGroupName = rg.Name,
            ApiManagementName = apim.Name,
            ApiName           = apiHealthProbe.Name,
            XmlContent        = @"<policies>
                            <inbound>
                                <return-response>
                                    <set-status code='200' />
                                </return-response>
                                <base />
                            </inbound>
                        </policies>"
        },
                                                 new CustomResourceOptions()
        {
            DependsOn = { apimHealthProbeOperation }
        });
        var apiHealtProbeProduct = new ProductApi("healthProbeProduct", new ProductApiArgs()
        {
            ResourceGroupName = rg.Name,
            ApiManagementName = apim.Name,
            ApiName           = apiHealthProbe.Name,
            ProductId         = apimProduct.ProductId
        },
                                                  new CustomResourceOptions()
        {
            DependsOn = { apim, apimProduct, apiHealthProbePolicy }
        });
    }
示例#23
0
 public ApiFilter(ApiPolicy policy)
 {
     Policy = policy;
 }
示例#24
0
        private static void WriteNamespaceReport(StreamWriter writer, string @namespace, IEnumerable <Type> types, ApiPolicy policy)
        {
            if (!policy.Namespaces.TryGetValue(@namespace, out var namespacePolicy))
            {
                return;
            }
            writer.WriteLine(@namespace);
            if (namespacePolicy.Access == Denied)
            {
                return;
            }

            var typesWithNames = types.Select(type => new {
                value = type,
                name  = @namespace.Length > 0 ? type.FullName !.Substring(@namespace.Length + 1) : type.FullName !
            });