/// <summary>
        ///   Initializes a new instance of the <see cref="ServiceBusConnection"/> class.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string to use for connecting to the Service Bus namespace.</param>
        /// <param name="options">A set of options to apply when configuring the connection.</param>
        ///
        /// <remarks>
        ///   If the connection string is copied from the Service Bus entity itself, it will contain the name of the desired Service Bus entity,
        ///   and can be used directly without passing the  name="entityName" />.  The name of the Service Bus entity should be
        ///   passed only once, either as part of the connection string or separately.
        /// </remarks>
        ///
        internal ServiceBusConnection(
            string connectionString,
            ServiceBusClientOptions options)
        {
            Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));
            ValidateConnectionOptions(options);

            var connectionStringProperties = ServiceBusConnectionStringProperties.Parse(connectionString);

            ValidateConnectionStringProperties(connectionStringProperties, nameof(connectionString));

            FullyQualifiedNamespace = connectionStringProperties.Endpoint.Host;
            TransportType           = options.TransportType;
            EntityPath   = connectionStringProperties.EntityPath;
            RetryOptions = options.RetryOptions;

            SharedAccessSignature sharedAccessSignature;

            if (string.IsNullOrEmpty(connectionStringProperties.SharedAccessSignature))
            {
                sharedAccessSignature = new SharedAccessSignature(
                    BuildConnectionResource(options.TransportType, FullyQualifiedNamespace, EntityPath),
                    connectionStringProperties.SharedAccessKeyName,
                    connectionStringProperties.SharedAccessKey);
            }
            else
            {
                sharedAccessSignature = new SharedAccessSignature(connectionStringProperties.SharedAccessSignature);
            }

            var sharedCredential = new SharedAccessCredential(sharedAccessSignature);
            var tokenCredential  = new ServiceBusTokenCredential(sharedCredential);

#pragma warning disable CA2214 // Do not call overridable methods in constructors. This internal method is virtual for testing purposes.
            _innerClient = CreateTransportClient(tokenCredential, options);
#pragma warning restore CA2214 // Do not call overridable methods in constructors
        }
Пример #2
0
        internal static (string token, string audience) ValidateAndParseMessage(string iotHubHostName, AmqpMessage message)
        {
            string type = message.ApplicationProperties.Map[CbsConstants.PutToken.Type] as string;

            if (!CbsConstants.SupportedTokenTypes.Any(t => string.Equals(type, t, StringComparison.OrdinalIgnoreCase)))
            {
                throw new InvalidOperationException("Cbs message missing Type property");
            }

            if (string.IsNullOrEmpty(message.ApplicationProperties.Map[CbsConstants.PutToken.Audience] as string))
            {
                throw new InvalidOperationException("Cbs message missing audience property");
            }

            if (!(message.ApplicationProperties.Map[CbsConstants.Operation] is string operation) ||
                !operation.Equals(CbsConstants.PutToken.OperationValue, StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException($"Cbs message missing operation value {CbsConstants.PutToken.OperationValue}");
            }

            string token = message.ValueBody.Value as string;

            if (string.IsNullOrEmpty(token))
            {
                throw new InvalidOperationException("Cbs message does not contain a valid token");
            }

            try
            {
                SharedAccessSignature sharedAccessSignature = SharedAccessSignature.Parse(iotHubHostName, token);
                return(token, sharedAccessSignature.Audience);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Cbs message does not contain a valid token", e);
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            Productevent productname = await req.Content.ReadAsAsync <Productevent>();

            string name = productname.Productname;

            List <EventGridEvent> eventlist = new List <EventGridEvent>();

            for (int i = 0; i < 1; i++)
            {
                eventlist.Add(new EventGridEvent()
                {
                    Id          = Guid.NewGuid().ToString(),
                    EventType   = "integration.event.eventpublished",
                    EventTime   = DateTime.Now,
                    Subject     = "IntegrationEvent",
                    DataVersion = "1.0",
                    Data        = new Productevent()
                    {
                        Productname = name
                    }
                });
            }
            string sharedaccesstoken = SharedAccessSignature.GenerateSharedAccessSignature(eventgridendpoint, DateTime.Now.AddHours(1), eventgridkey);

            using (var reqclient = new HttpClient())
            {
                HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, eventgridendpoint);
                requestMessage.Headers.Add("aeg-sas-token", sharedaccesstoken);
                var jsonString = JsonConvert.SerializeObject(eventlist);
                var content    = new StringContent(jsonString, Encoding.UTF8, "application/json");
                requestMessage.Content = content;
                HttpResponseMessage response = await reqclient.SendAsync(requestMessage);
            }

            return(req.CreateResponse(HttpStatusCode.OK));
        }
Пример #4
0
        public static async Task <bool> IsRequestAuthorizedAsync(IHttpRequestWrapper request, bool ignoreRequestAge = false)
        {
            var headers     = request.Headers;
            var queryParams = request.QueryParameters;
            // See what type of auth scheme is applied to this request
            bool sharedKeyRequest = SharedKey.IsRequestType(headers);
            bool sasRequest       = SharedAccessSignature.IsRequestType(queryParams);

            if (sharedKeyRequest && sasRequest)
            {
                // Can't be a SAS & SharedKey Authorization together
                return(false);
            }
            else if (sasRequest)
            {
                return(await SharedAccessSignature.IsAuthorizedAsync(request, headers, queryParams, ignoreRequestAge));
            }
            else if (sharedKeyRequest)
            {
                return(SharedKey.IsAuthorized(request, headers, queryParams, ignoreRequestAge));
            }
            // Anonymous
            return(await Anonymous.IsAuthorizedAsync(request));
        }
        bool ValidateTokenWithSecurityIdentity(SharedAccessSignature sharedAccessSignature, ServiceIdentity serviceIdentity)
        {
            if (serviceIdentity.Authentication.Type != ServiceAuthenticationType.SymmetricKey)
            {
                Events.InvalidServiceIdentityType(serviceIdentity);
                return(false);
            }

            if (serviceIdentity.Status != ServiceIdentityStatus.Enabled)
            {
                Events.ServiceIdentityNotEnabled(serviceIdentity);
                return(false);
            }

            return(serviceIdentity.Authentication.SymmetricKey.Map(
                       s =>
            {
                var rule = new SharedAccessSignatureAuthorizationRule
                {
                    PrimaryKey = s.PrimaryKey,
                    SecondaryKey = s.SecondaryKey
                };

                try
                {
                    sharedAccessSignature.Authenticate(rule);
                    return true;
                }
                catch (UnauthorizedAccessException e)
                {
                    Events.KeysMismatch(serviceIdentity.Id, e);
                    return false;
                }
            })
                   .GetOrElse(() => throw new InvalidOperationException($"Unable to validate token because the service identity has empty symmetric keys")));
        }
Пример #6
0
        public async Task CreateClientPopulatesTheProxy()
        {
            var options = new EventHubClientOptions
            {
                TransportType = TransportType.AmqpWebSockets,
                Proxy         = Mock.Of <IWebProxy>()
            };

            var host         = "my.eventhub.com";
            var eventHubPath = "some-path";
            var resource     = $"amqps://{ host }/{ eventHubPath }";
            var signature    = new SharedAccessSignature(resource, "keyName", "KEY", TimeSpan.FromHours(1));
            var credential   = new SharedAccessSignatureCredential(signature);
            var client       = (AmqpEventHubClient)TrackOneEventHubClient.CreateClient(host, eventHubPath, credential, options);

            try
            {
                Assert.That(client.WebProxy, Is.SameAs(options.Proxy), "The client should honor the proxy.");
            }
            finally
            {
                await client?.CloseAsync();
            }
        }
        public void ValidateAudienceWithEdgeHubHostNameTest()
        {
            // Arrange
            string iothubHostName             = "testiothub.azure-devices.net";
            string edgehubHostName            = "edgehub1";
            string deviceId                   = "d1";
            var    underlyingAuthenticator    = Mock.Of <IAuthenticator>();
            var    deviceScopeIdentitiesCache = Mock.Of <IDeviceScopeIdentitiesCache>();
            string key = GetKey();

            var authenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, iothubHostName, edgehubHostName, underlyingAuthenticator, true, true);

            var    identity = Mock.Of <IDeviceIdentity>(d => d.DeviceId == deviceId && d.Id == deviceId);
            string token    = GetDeviceToken(edgehubHostName, deviceId, key);
            SharedAccessSignature sharedAccessSignature = SharedAccessSignature.Parse(edgehubHostName, token);
            string audience = sharedAccessSignature.Audience;

            // Act
            bool isAuthenticated = authenticator.ValidateAudience(audience, identity);

            // Assert
            Assert.True(isAuthenticated);
            Mock.Get(underlyingAuthenticator).VerifyAll();
        }
Пример #8
0
    static Task <int> Main()
    {
        return(Deployment.RunAsync(async() => {
            var resourceGroup = new ResourceGroup("keyvault-rg");

            // Create a storage account for Blobs
            var storageAccount = new Account("storage", new AccountArgs
            {
                ResourceGroupName = resourceGroup.Name,
                AccountReplicationType = "LRS",
                AccountTier = "Standard",
            });

            // The container to put our files into
            var storageContainer = new Container("files", new ContainerArgs
            {
                StorageAccountName = storageAccount.Name,
                ContainerAccessType = "private",
            });

            // Azure SQL Server that we want to access from the application
            var administratorLoginPassword = new RandomPassword("password",
                                                                new RandomPasswordArgs {
                Length = 16, Special = true
            }).Result;
            var sqlServer = new SqlServer("sqlserver", new SqlServerArgs
            {
                ResourceGroupName = resourceGroup.Name,
                // The login and password are required but won't be used in our application
                AdministratorLogin = "******",
                AdministratorLoginPassword = administratorLoginPassword,
                Version = "12.0",
            });

            // Azure SQL Database that we want to access from the application
            var database = new Database("db", new DatabaseArgs
            {
                ResourceGroupName = resourceGroup.Name,
                ServerName = sqlServer.Name,
                RequestedServiceObjectiveName = "S0",
            });

            // The connection string that has no credentials in it: authertication will come through MSI
            var connectionString = Output.Format($"Server=tcp:{sqlServer.Name}.database.windows.net;Database={database.Name};");

            // A file in Blob Storage that we want to access from the application
            var textBlob = new Blob("text", new BlobArgs
            {
                StorageAccountName = storageAccount.Name,
                StorageContainerName = storageContainer.Name,
                Type = "block",
                Source = "./README.md",
            });

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

            // ASP.NET deployment package
            var blob = new ZipBlob("zip", new ZipBlobArgs
            {
                StorageAccountName = storageAccount.Name,
                StorageContainerName = storageContainer.Name,
                Type = "block",
                Content = new FileArchive("./webapp/bin/Debug/netcoreapp2.2/publish"),
            });

            var clientConfig = await Pulumi.Azure.Core.Invokes.GetClientConfig();
            var tenantId = clientConfig.TenantId;
            var currentPrincipal = clientConfig.ObjectId;

            // Key Vault to store secrets (e.g. Blob URL with SAS)
            var vault = new KeyVault("vault", new KeyVaultArgs
            {
                ResourceGroupName = resourceGroup.Name,
                SkuName = "standard",
                TenantId = tenantId,
                AccessPolicies =
                {
                    new KeyVaultAccessPoliciesArgs
                    {
                        TenantId = tenantId,
                        // The current principal has to be granted permissions to Key Vault so that it can actually add and then remove
                        // secrets to/from the Key Vault. Otherwise, 'pulumi up' and 'pulumi destroy' operations will fail.
                        ObjectId = currentPrincipal,
                        SecretPermissions ={ "delete",                         "get", "list", "set" },
                    }
                },
            });

            // Put the URL of the zip Blob to KV
            var secret = new Secret("deployment-zip", new SecretArgs
            {
                KeyVaultId = vault.Id,
                Value = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount),
            });
            var secretUri = Output.Format($"{secret.VaultUri}secrets/{secret.Name}/{secret.Version}");


            // The application hosted in App Service
            var app = new AppService("app", new AppServiceArgs
            {
                ResourceGroupName = resourceGroup.Name,
                AppServicePlanId = appServicePlan.Id,
                // A system-assigned managed service identity to be used for authentication and authorization to the SQL Database and the Blob Storage
                Identity = new AppServiceIdentityArgs {
                    Type = "SystemAssigned"
                },

                AppSettings =
                {
                    // Website is deployed from a URL read from the Key Vault
                    { "WEBSITE_RUN_FROM_ZIP", Output.Format($"@Microsoft.KeyVault(SecretUri={secretUri})") },

                    // Note that we simply provide the URL without SAS or keys
                    { "StorageBlobUrl",       textBlob.Url                                                 },
                },
                ConnectionStrings =
                {
                    new AppServiceConnectionStringsArgs
                    {
                        Name = "db",
                        Type = "SQLAzure",
                        Value = connectionString,
                    },
                },
            });

            // Work around a preview issue https://github.com/pulumi/pulumi-azure/issues/192
            var principalId = app.Identity.Apply(id => id.PrincipalId ?? "11111111-1111-1111-1111-111111111111");

            // Grant App Service access to KV secrets
            var policy = new AccessPolicy("app-policy", new AccessPolicyArgs
            {
                KeyVaultId = vault.Id,
                TenantId = tenantId,
                ObjectId = principalId,
                SecretPermissions = { "get" },
            });

            // Make the App Service the admin of the SQL Server (double check if you want a more fine-grained security model in your real app)
            var sqlAdmin = new ActiveDirectoryAdministrator("adadmin", new ActiveDirectoryAdministratorArgs
            {
                ResourceGroupName = resourceGroup.Name,
                TenantId = tenantId,
                ObjectId = principalId,
                Login = "******",
                ServerName = sqlServer.Name,
            });

            // Grant access from App Service to the container in the storage
            var blobPermission = new Assignment("readblob", new AssignmentArgs
            {
                PrincipalId = principalId,
                Scope = Output.Format($"{storageAccount.Id}/blobServices/default/containers/{storageContainer.Name}"),
                RoleDefinitionName = "Storage Blob Data Reader",
            });

            // Add SQL firewall exceptions
            var firewallRules = app.OutboundIpAddresses.Apply(
                ips => ips.Split(",").Select(
                    ip => new FirewallRule($"FR{ip}", new FirewallRuleArgs
            {
                ResourceGroupName = resourceGroup.Name,
                StartIpAddress = ip,
                EndIpAddress = ip,
                ServerName = sqlServer.Name,
            })
                    ).ToList());

            return new Dictionary <string, object>
            {
                { "endpoint", Output.Format($"https://{app.DefaultSiteHostname}") },
            };
        }));
    }
Пример #9
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("starting deployment");

            string rgName             = "PulumiTest";
            string storageAccountName = "sa";

            var resourceGroup = CreateResourceGroup(rgName, Locations.WestEurope);

            var plan = GetAppServicePlan("CoolApps", new PlanArgs
            {
                Location = Locations.WestEurope, Kind = AppServiceKind.App,
                Sku      = new PlanSkuArgs
                {
                    Tier = AppServiceTier.Basic,
                    Size = "B1"
                }
            });

            var storageAccount = new Account(storageAccountName, new AccountArgs
            {
                ResourceGroupName      = rgName,
                AccountReplicationType = "LRS",
                AccountTier            = "Standard"
            });

            var container = GetContainer(storageAccountName, "Messages");

            var appInsights = new Insights("appInsights", new InsightsArgs
            {
                ApplicationType   = "web",
                ResourceGroupName = rgName
            });

            var config   = new Config();
            var username = config.Get("sqlAdmin") ?? "pulumi";
            var password = config.RequireSecret("sqlPassword");

            var blob = new Blob("messages", new BlobArgs
            {
                StorageAccountName   = storageAccount.Name,
                StorageContainerName = container.Name,
                Type   = "Block",
                Source = new FileArchive("wwwroot"),
            });

            var codeBlobUrl = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount);

            var sqlServer = new SqlServer("sql", new SqlServerArgs
            {
                ResourceGroupName          = rgName,
                AdministratorLogin         = username,
                AdministratorLoginPassword = password,
                Version = "12.0",
            });

            var database = new Database("db", new DatabaseArgs
            {
                ResourceGroupName             = rgName,
                ServerName                    = sqlServer.Name,
                RequestedServiceObjectiveName = "S0",
            });

            var app = new AppService("app", new AppServiceArgs
            {
                ResourceGroupName = resourceGroup.Name,
                AppServicePlanId  = plan.Id,
                AppSettings       =
                {
                    { "WEBSITE_RUN_FROM_PACKAGE",                   codeBlobUrl                                                              },
Пример #10
0
 public void ParseSignatureFailsWhenValuesAreMissing(string signature)
 {
     Assert.That(() => SharedAccessSignature.ParseSignature(signature), Throws.ArgumentException);
 }
Пример #11
0
        public void ConstructorValidatesTheSignatureResource()
        {
            var signature = new SharedAccessSignature(String.Empty, "keyName", "key", String.Empty, DateTimeOffset.UtcNow);

            Assert.That(() => new TrackOneSharedAccessSignatureToken(signature), Throws.InstanceOf <ArgumentException>());
        }
Пример #12
0
        public void ConstructorValidatesTheSignatureHasAKey()
        {
            var signature = new SharedAccessSignature("SharedAccessSignature sr=amqps%3A%2F%2Fmy.eh.com%2Fsomepath%2F&sig=%2BLsuqDlN8Us5lp%2FGdyEUMnU1XA4HdXx%2BJUdtkRNr7qI%3D&se=1562258488&skn=keykeykey");

            Assert.That(() => new TrackOneSharedAccessTokenProvider(signature), Throws.InstanceOf <ArgumentException>());
        }
Пример #13
0
    public AppServiceStack()
    {
        var resourceGroup = new ResourceGroup("appservice-rg");

        var storageAccount = new Account("sa", new AccountArgs
        {
            ResourceGroupName      = resourceGroup.Name,
            AccountReplicationType = "LRS",
            AccountTier            = "Standard",
        });

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

        var container = new Container("zips", new ContainerArgs
        {
            StorageAccountName  = storageAccount.Name,
            ContainerAccessType = "private",
        });

        var blob = new Blob("zip", new BlobArgs
        {
            StorageAccountName   = storageAccount.Name,
            StorageContainerName = container.Name,
            Type   = "Block",
            Source = new FileArchive("wwwroot"),
        });

        var codeBlobUrl = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount);

        var config    = new Config();
        var username  = config.Get("sqlAdmin") ?? "pulumi";
        var password  = config.RequireSecret("sqlPassword");
        var sqlServer = new SqlServer("sql", new SqlServerArgs
        {
            ResourceGroupName          = resourceGroup.Name,
            AdministratorLogin         = username,
            AdministratorLoginPassword = password,
            Version = "12.0",
        });

        var database = new Database("db", new DatabaseArgs
        {
            ResourceGroupName             = resourceGroup.Name,
            ServerName                    = sqlServer.Name,
            RequestedServiceObjectiveName = "S0",
        });

        var app = new AppService("app", new AppServiceArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AppServicePlanId  = appServicePlan.Id,
            AppSettings       =
            {
                { "WEBSITE_RUN_FROM_PACKAGE", codeBlobUrl },
            },
        public async Task SharedAccessSignature()
        {
            await using var eventHubScope = await EventHubScope.CreateAsync(1);

            await using var storageScope = await StorageScope.CreateAsync();

            #region Snippet:EventHubs_Processor_Sample05_SharedAccessSignature

            var storageConnectionString = "<< CONNECTION STRING FOR THE STORAGE ACCOUNT >>";
            var blobContainerName       = "<< NAME OF THE BLOB CONTAINER >>";
            /*@@*/
            /*@@*/ storageConnectionString = StorageTestEnvironment.Instance.StorageConnectionString;
            /*@@*/ blobContainerName       = storageScope.ContainerName;

            //@@ var credential = new AzureSasCredential("<< SHARED ACCESS KEY STRING >>");
            var fullyQualifiedNamespace = "<< NAMESPACE (likely similar to {your-namespace}.servicebus.windows.net) >>";
            var eventHubName            = "<< NAME OF THE EVENT HUB >>";
            var consumerGroup           = "<< NAME OF THE EVENT HUB CONSUMER GROUP >>";
            /*@@*/
            /*@@*/ fullyQualifiedNamespace = EventHubsTestEnvironment.Instance.FullyQualifiedNamespace;
            /*@@*/ eventHubName            = eventHubScope.EventHubName;
            /*@@*/ consumerGroup           = eventHubScope.ConsumerGroups.First();
            /*@@*/
            /*@@*/ var resource   = $"amqps://{ EventHubsTestEnvironment.Instance.FullyQualifiedNamespace }/{ eventHubScope.EventHubName }".ToLowerInvariant();
            /*@@*/ var signature  = new SharedAccessSignature(resource, EventHubsTestEnvironment.Instance.SharedAccessKeyName, EventHubsTestEnvironment.Instance.SharedAccessKey);
            /*@@*/ var credential = new AzureSasCredential(signature.Value);

            var storageClient = new BlobContainerClient(
                storageConnectionString,
                blobContainerName);

            var processor = new EventProcessorClient(
                storageClient,
                consumerGroup,
                fullyQualifiedNamespace,
                eventHubName,
                credential);

            try
            {
                using var cancellationSource = new CancellationTokenSource();
                cancellationSource.CancelAfter(TimeSpan.FromSeconds(30));

                // The event handlers are not relevant for this sample; for
                // illustration, they're delegating the implementation to the
                // host application.

                processor.ProcessEventAsync += Application.ProcessorEventHandler;
                processor.ProcessErrorAsync += Application.ProcessorErrorHandler;

                try
                {
                    await processor.StartProcessingAsync(cancellationSource.Token);

                    await Task.Delay(Timeout.Infinite, cancellationSource.Token);
                }
                catch (TaskCanceledException)
                {
                    // This is expected if the cancellation token is
                    // signaled.
                }
                finally
                {
                    // This may take up to the length of time defined
                    // as part of the configured TryTimeout of the processor;
                    // by default, this is 60 seconds.

                    await processor.StopProcessingAsync();
                }
            }
            catch
            {
                // If this block is invoked, then something external to the
                // processor was the source of the exception.
            }
            finally
            {
                // It is encouraged that you unregister your handlers when you have
                // finished using the Event Processor to ensure proper cleanup.

                processor.ProcessEventAsync -= Application.ProcessorEventHandler;
                processor.ProcessErrorAsync -= Application.ProcessorErrorHandler;
            }

            #endregion
        }
Пример #15
0
        public static Dictionary <string, object> Run()
        {
            var resourceGroup = new ResourceGroup("dotnet-rg", new ResourceGroupArgs
            {
                Location = "West Europe"
            });

            var cosmosapp = new CosmosApp("capp", new CosmosAppArgs
            {
                ResourceGroupName = resourceGroup.Name,
                Locations         = new[] { resourceGroup.Location },
            });

            var storageAccount = new Account("sa", new AccountArgs
            {
                ResourceGroupName      = resourceGroup.Name,
                AccountReplicationType = "LRS",
                AccountTier            = "Standard",
            });

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

            var container = new Container("c", new ContainerArgs
            {
                StorageAccountName  = storageAccount.Name,
                ContainerAccessType = "private",
            });

            var blob = new ZipBlob("zip", new ZipBlobArgs
            {
                StorageAccountName   = storageAccount.Name,
                StorageContainerName = container.Name,
                Type    = "block",
                Content = new FileArchive("wwwroot"),
            });

            var codeBlobUrl = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount);

            //var username = "******"; // TODO: Pulumi.Config
            //var password = "******";
            //var sqlServer = new SqlServer("sql", new SqlServerArgs
            //{
            //    ResourceGroupName = resourceGroup.Name,
            //    AdministratorLogin = username,
            //    AdministratorLoginPassword = password,
            //    Version = "12.0",
            //});

            //var database = new Database("db", new DatabaseArgs
            //{
            //    ResourceGroupName = resourceGroup.Name,
            //    ServerName = sqlServer.Name,
            //    RequestedServiceObjectiveName = "S0",
            //});

            var app = new AppService("app", new AppServiceArgs
            {
                ResourceGroupName = resourceGroup.Name,
                AppServicePlanId  = appServicePlan.Id,
                AppSettings       =
                {
                    { "WEBSITE_RUN_FROM_ZIP", codeBlobUrl },
                },
                //ConnectionStrings = new[]
                //{
                //    new AppService.ConnectionStringArgs
                //    {
                //        Name = "db",
                //        Type = "SQLAzure",
                //        Value = Output.All<string>(sqlServer.Name, database.Name).Apply(values =>
                //        {
                //            return $"Server= tcp:${values[0]}.database.windows.net;initial catalog=${values[1]};userID=${username};password=${password};Min Pool Size=0;Max Pool Size=30;Persist Security Info=true;";
                //        }),
                //    },
                //},
            });

            return(new Dictionary <string, object>
            {
                { "endpoint", app.DefaultSiteHostname },
            });
        }
Пример #16
0
 public void ParseToleratesExtraTokens(string signature)
 {
     Assert.That(() => SharedAccessSignature.ParseSignature(signature), Throws.Nothing);
 }
Пример #17
0
 public void ParseToleratesTrailingDelimiters(string signature)
 {
     Assert.That(() => SharedAccessSignature.ParseSignature(signature), Throws.Nothing);
 }
Пример #18
0
 public void ParseSignatureFailsWhenExpirationIsInvalid(string signature)
 {
     Assert.That(() => SharedAccessSignature.ParseSignature(signature), Throws.ArgumentException);
 }
Пример #19
0
    static Task <int> Main()
    {
        return(Deployment.RunAsync(() =>
        {
            // Create an Azure Resource Group
            var resourceGroup = new ResourceGroup("resourceGroup", new ResourceGroupArgs
            {
                Name = "pulumi"
            });

            // Create an Azure Storage Account
            var storageAccount = new Account("storage", new AccountArgs
            {
                Name = "wwwcontainer",
                ResourceGroupName = resourceGroup.Name,
                AccountReplicationType = "LRS",
                AccountTier = "Standard",
            });

            var appServicePlan = new Plan("asp", new PlanArgs
            {
                ResourceGroupName = resourceGroup.Name,
                Name = "website",
                Kind = "App",
                Sku = new PlanSkuArgs
                {
                    Tier = "Basic",
                    Size = "B1",
                },
            });

            var container = new Container("zips", new ContainerArgs
            {
                StorageAccountName = storageAccount.Name,
                ContainerAccessType = "private",
            });

            var blob = new ZipBlob("zip", new ZipBlobArgs
            {
                StorageAccountName = storageAccount.Name,
                StorageContainerName = container.Name,
                Type = "block",
                Content = new FileArchive(@"C:\code\ozcode\pulumiapp\pulumiapp\bin\Debug\netcoreapp3.1\publish"),
            });

            var codeBlobUrl = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount);

            var config = new Config();
            var username = config.Get("sqlAdmin") ?? "pulumi";
            var password = config.RequireSecret("sqlPassword");
            var sqlServer = new SqlServer("sql", new SqlServerArgs
            {
                Name = "pulumiserver",
                ResourceGroupName = resourceGroup.Name,
                AdministratorLogin = username,
                AdministratorLoginPassword = password,
                Version = "12.0",
            });

            var database = new Database("db", new DatabaseArgs
            {
                Name = "pulumidatabase",
                ResourceGroupName = resourceGroup.Name,
                ServerName = sqlServer.Name,
                RequestedServiceObjectiveName = "S0",
            });

            var app = new AppService("app", new AppServiceArgs
            {
                Name = "pulumiwebapp",
                ResourceGroupName = resourceGroup.Name,
                AppServicePlanId = appServicePlan.Id,
                AppSettings =
                {
                    { "WEBSITE_RUN_FROM_PACKAGE", codeBlobUrl                                                                 },
                    { "OzCode:Agent:Token",       "76c0dff5-a7ba-415c-858f-b1bc1124a42c|73b8df28-4f14-468d-a978-918900c1736c" }
                },
Пример #20
0
    public MyStack()
    {
        ProjectStack = $"{Deployment.Instance.ProjectName}-{Deployment.Instance.StackName}";

        StackSuffix = Regex.Replace(Deployment.Instance.StackName, "[^a-z0-9]", string.Empty, RegexOptions.IgnoreCase);

        var stagingModelVersion = GetModelVersionForStagingSlot();

        var productionModelVersion = GetModelVersionForProductionSlot() ?? stagingModelVersion;

        Console.WriteLine($"ML Model Version. Staging: {stagingModelVersion} Prod: {productionModelVersion}");

        var resourceGroup = new ResourceGroup(ProjectStack);

        var storageAccount = new Account("sa" + StackSuffix.ToLowerInvariant(), new AccountArgs
        {
            ResourceGroupName      = resourceGroup.Name,
            AccountReplicationType = "LRS",
            AccountTier            = "Standard"
        });

        var appServicePlan = new Plan("asp" + StackSuffix.ToLowerInvariant(), new PlanArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Kind = "FunctionApp",
            Sku  = new PlanSkuArgs
            {
                Tier = "Dynamic",
                Size = "Y1",
            }
        });

        var container = new Container("cntzip" + StackSuffix.ToLowerInvariant(), new ContainerArgs
        {
            StorageAccountName  = storageAccount.Name,
            ContainerAccessType = "private"
        });

        var blob = new Blob("blobzip" + StackSuffix.ToLowerInvariant(), new BlobArgs
        {
            StorageAccountName   = storageAccount.Name,
            StorageContainerName = container.Name,
            Type   = "Block",
            Source = new FileArchive("../ml/Predictor/bin/Release/netcoreapp3.1/publish/")
        });

        var codeBlobUrl = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount);

        var appInsights = new Insights("fxai" + StackSuffix.ToLowerInvariant(), new InsightsArgs
        {
            ResourceGroupName = resourceGroup.Name,
            ApplicationType   = "web"
        });

        var valuesMap = new InputMap <string>()
        {
            { "runtime", "dotnet" },
            { "WEBSITE_RUN_FROM_PACKAGE", codeBlobUrl },
            { "AzureWebJobsStorage", storageAccount.PrimaryConnectionString },
            { "ML_MODEL_URI", productionModelVersion },
            { "APPINSIGHTS_INSTRUMENTATIONKEY", appInsights.InstrumentationKey }
        };

        var app = new FunctionApp("fxapp" + StackSuffix.ToLowerInvariant(), new FunctionAppArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AppServicePlanId  = appServicePlan.Id,
            AppSettings       = valuesMap,
            SiteConfig        = new FunctionAppSiteConfigArgs
            {
                Cors = new FunctionAppSiteConfigCorsArgs
                {
                    AllowedOrigins = new InputList <string>
                    {
                        "http://localhost:5500"
                    },
                    SupportCredentials = true
                }
            },
            StorageAccountName      = storageAccount.Name,
            StorageAccountAccessKey = storageAccount.PrimaryAccessKey,
            Version = "~3"
        });

        var stagingSlot = new FunctionAppSlot("staging", new FunctionAppSlotArgs
        {
            Name = "staging",
            ResourceGroupName       = resourceGroup.Name,
            AppServicePlanId        = appServicePlan.Id,
            StorageAccountName      = storageAccount.Name,
            StorageAccountAccessKey = storageAccount.PrimaryAccessKey,
            FunctionAppName         = app.Name,
            Version    = "~3",
            SiteConfig = new FunctionAppSlotSiteConfigArgs
            {
                Cors = new FunctionAppSlotSiteConfigCorsArgs
                {
                    AllowedOrigins = new InputList <string>
                    {
                        "http://localhost:5500"
                    },
                    SupportCredentials = true
                }
            },
            AppSettings =
            {
                { "runtime",                        "dotnet"                               },
                { "WEBSITE_RUN_FROM_PACKAGE",       codeBlobUrl                            },
                { "AzureWebJobsStorage",            storageAccount.PrimaryConnectionString },
                { "ML_MODEL_URI",                   stagingModelVersion                    },
                { "APPINSIGHTS_INSTRUMENTATIONKEY", appInsights.InstrumentationKey         }
            },
        });

        StorageConnectionString = Output.Format($"{storageAccount.PrimaryConnectionString}");

        StaginEndpoint = Output.Format($"https://{stagingSlot.DefaultHostname}");

        Endpoint = Output.Format($"https://{app.DefaultHostname}");

        ModelVersion = Output.Format($"{productionModelVersion}");
    }
Пример #21
0
    static Task <int> Main(string[] args)
    {
        return(Deployment.RunAsync(() => {
            var resourceGroup = new ResourceGroup("appservice-rg");

            var storageAccount = new Account("sa", new AccountArgs
            {
                ResourceGroupName = resourceGroup.Name,
                AccountReplicationType = "LRS",
                AccountTier = "Standard",
            });

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

            var container = new Container("zips", new ContainerArgs
            {
                StorageAccountName = storageAccount.Name,
                ContainerAccessType = "private",
            });

            var blob = new ZipBlob("zip", new ZipBlobArgs
            {
                StorageAccountName = storageAccount.Name,
                StorageContainerName = container.Name,
                Type = "block",
                Content = new FileArchive("wwwroot"),
            });

            var codeBlobUrl = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount);

            var config = new Config();
            var username = config.Get("sqlAdmin") ?? "pulumi";
            var password = config.RequireSecret("sqlPassword");
            var sqlServer = new SqlServer("sql", new SqlServerArgs
            {
                ResourceGroupName = resourceGroup.Name,
                AdministratorLogin = username,
                AdministratorLoginPassword = password,
                Version = "12.0",
            });

            var database = new Database("db", new DatabaseArgs
            {
                ResourceGroupName = resourceGroup.Name,
                ServerName = sqlServer.Name,
                RequestedServiceObjectiveName = "S0",
            });

            var app = new AppService("app", new AppServiceArgs
            {
                ResourceGroupName = resourceGroup.Name,
                AppServicePlanId = appServicePlan.Id,
                AppSettings =
                {
                    { "WEBSITE_RUN_FROM_PACKAGE", codeBlobUrl },
                },
                ConnectionStrings =
                {
                    new AppServiceConnectionStringsArgs
                    {
                        Name = "db",
                        Type = "SQLAzure",
                        Value = Output.Tuple <string, string, string>(sqlServer.Name, database.Name, password).Apply(t =>
                        {
                            (string server, string database, string pwd) = t;
                            return $"Server= tcp:{server}.database.windows.net;initial catalog={database};userID={username};password={pwd};Min Pool Size=0;Max Pool Size=30;Persist Security Info=true;";
                        }),
                    },
                },
            });
Пример #22
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="TrackOneSharedAccessSignatureToken"/> class.
 /// </summary>
 ///
 /// <param name="sharedAccessSignature">The shared access signature on which to base the token.</param>
 ///
 public TrackOneSharedAccessSignatureToken(SharedAccessSignature sharedAccessSignature) :
     base(sharedAccessSignature?.Value, (sharedAccessSignature?.ExpirationUtc ?? default), sharedAccessSignature?.Resource, ClientConstants.SasTokenType)
        public void ExtendValidityValidatesTheKey()
        {
            var signature = new SharedAccessSignature("SharedAccessSignature sr=amqps%3A%2F%2Fmy.eh.com%2Fsomepath%2F&sig=%2BLsuqDlN8Us5lp%2FGdyEUMnU1XA4HdXx%2BJUdtkRNr7qI%3D&se=1562258488&skn=keykeykey&notreal=123");

            Assert.That(() => signature.ExtendExpiration(TimeSpan.FromMilliseconds(21)), Throws.InvalidOperationException);
        }
Пример #24
0
        public void ConstructorValidatesTheSignatureValue()
        {
            var signature = new SharedAccessSignature("audience", "keyName", "key", null, DateTimeOffset.UtcNow);

            Assert.That(() => new TrackOneSharedAccessSignatureToken(signature), Throws.InstanceOf <ArgumentException>());
        }
Пример #25
0
    public FunctionsStack()
    {
        var resourceGroup = new ResourceGroup("functions-rg");

        var storageAccount = new Account("sa", new AccountArgs
        {
            ResourceGroupName      = resourceGroup.Name,
            AccountReplicationType = "LRS",
            AccountTier            = "Standard"
        });

        var appServicePlan = new Plan("functions-linux-asp", new PlanArgs
        {
            ResourceGroupName = resourceGroup.Name,

            // Run on Linux
            Kind = "Linux",

            // Premium SKU
            Sku = new PlanSkuArgs
            {
                Tier = "PremiumV2",
                Size = "P1v2"
            },

            // For Linux, you need to change the plan to have Reserved = true property.
            Reserved = true
        });

        var container = new Container("zips", new ContainerArgs
        {
            StorageAccountName  = storageAccount.Name,
            ContainerAccessType = "private"
        });

        var blob = new Blob("zip", new BlobArgs
        {
            StorageAccountName   = storageAccount.Name,
            StorageContainerName = container.Name,
            Type   = "Block",
            Source = new FileArchive("./functions")
        });

        var codeBlobUrl = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount);

        // Application insights
        var insights = new Insights("functions-ai", new InsightsArgs
        {
            ResourceGroupName = resourceGroup.Name,
            ApplicationType   = "web"
        });

        var app = new FunctionApp("app", new FunctionAppArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AppServicePlanId  = appServicePlan.Id,
            AppSettings       =
            {
                { "runtime",                               "python"                                                           },
                { "FUNCTIONS_WORKER_RUNTIME",              "python"                                                           },
                { "WEBSITE_RUN_FROM_PACKAGE",              codeBlobUrl                                                        },
                { "APPLICATIONINSIGHTS_CONNECTION_STRING", Output.Format($"InstrumentationKey={insights.InstrumentationKey}") }
            },
            StorageAccountName      = storageAccount.Name,
            StorageAccountAccessKey = storageAccount.PrimaryAccessKey,
            Version    = "~3",
            OsType     = "linux",
            SiteConfig = new FunctionAppSiteConfigArgs
            {
                AlwaysOn       = true,
                LinuxFxVersion = "DOCKER|mcr.microsoft.com/azure-functions/python:2.0"
            }
        });

        this.Endpoint = Output.Format($"https://{app.DefaultHostname}/api/Hello?name=Pulumi");
    }
 bool ValidateCredentials(SharedAccessSignature sharedAccessSignature, ServiceIdentity serviceIdentity, IIdentity identity) =>
 this.ValidateTokenWithSecurityIdentity(sharedAccessSignature, serviceIdentity) &&
 this.ValidateAudience(sharedAccessSignature.Audience, identity) &&
 this.ValidateExpiry(sharedAccessSignature, identity);
Пример #27
0
    static Task <int> Main(string[] args)
    {
        return(Deployment.RunAsync(() =>
        {
            var config = new Config();
            var botName = config.Require("botName");

            var resourceGroup = new ResourceGroup("botservice-rg");

            var storageAccount = new Storage.Account("sa", new Storage.AccountArgs
            {
                ResourceGroupName = resourceGroup.Name,
                AccountReplicationType = "LRS",
                AccountTier = "Standard"
            });

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

            var container = new Storage.Container("zips", new Storage.ContainerArgs
            {
                StorageAccountName = storageAccount.Name,
                ContainerAccessType = "private",
            });

            var blob = new Storage.ZipBlob("zip", new Storage.ZipBlobArgs
            {
                StorageAccountName = storageAccount.Name,
                StorageContainerName = container.Name,
                Type = "block",
                Content = new FileArchive("bot/publish")
            });

            var codeBlobUrl = SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount);

            var appInsights = new Insights("ai", new InsightsArgs
            {
                ApplicationType = "web",
                ResourceGroupName = resourceGroup.Name
            });

            var appInsightApiKey = new ApiKey("ai", new ApiKeyArgs
            {
                ApplicationInsightsId = appInsights.Id,
                ReadPermissions = "api",
            });

            var luis = new Cognitive.Account("cs", new Cognitive.AccountArgs
            {
                Kind = "CognitiveServices", // includes LUIS
                ResourceGroupName = resourceGroup.Name,
                Sku = new AccountSkuArgs {
                    Name = "S0", Tier = "Standard"
                }
            });

            var msa = new Application("msapp", new ApplicationArgs
            {
                Oauth2AllowImplicitFlow = false,
                AvailableToOtherTenants = true,
                PublicClient = true
            });

            var pwd = new RandomPassword("password", new RandomPasswordArgs
            {
                Length = 16,
                MinNumeric = 1,
                MinSpecial = 1,
                MinUpper = 1,
                MinLower = 1
            });

            var msaSecret = new ApplicationPassword("msasecret", new ApplicationPasswordArgs
            {
                ApplicationObjectId = msa.ObjectId,
                EndDateRelative = "8640h",
                Value = pwd.Result
            });

            var app = new AppService("app", new AppServiceArgs
            {
                ResourceGroupName = resourceGroup.Name,
                AppServicePlanId = appServicePlan.Id,
                AppSettings =
                {
                    { "WEBSITE_RUN_FROM_PACKAGE", codeBlobUrl           },
                    { "MicrosoftAppId",           msa.ApplicationId     },
                    { "MicrosoftAppPassword",     msaSecret.Value       },
                    { "LuisApiKey",               luis.PrimaryAccessKey },
                },
                HttpsOnly = true
            });

            var bot = new WebApp(botName, new WebAppArgs
            {
                DisplayName = botName,
                MicrosoftAppId = msa.ApplicationId,
                ResourceGroupName = resourceGroup.Name,
                Sku = "F0",
                Location = "global",
                Endpoint = Output.Format($"https://{app.DefaultSiteHostname}/api/messages"),
                DeveloperAppInsightsApiKey = appInsightApiKey.Key,
                DeveloperAppInsightsApplicationId = appInsights.AppId,
                DeveloperAppInsightsKey = appInsights.InstrumentationKey
            });

            return new Dictionary <string, object>
            {
                { "Bot Endpoint", bot.Endpoint },
                { "MicrosoftAppId", msa.ApplicationId },
                { "MicrosoftAppPassword", msaSecret.Value }
            };
        }));
    }
        public void SignatureOnlyConstructorDoesNotSetTheKey()
        {
            var signature = new SharedAccessSignature("SharedAccessSignature sr=amqps%3A%2F%2Fmy.eh.com%2Fsomepath%2F&sig=%2BLsuqDlN8Us5lp%2FGdyEUMnU1XA4HdXx%2BJUdtkRNr7qI%3D&se=1562258488&skn=keykeykey&notreal=123");

            Assert.That(signature.SharedAccessKey, Is.Null);
        }
Пример #29
0
    public AzureStack()
    {
        var config   = new Pulumi.Config();
        var deployTo = config.Require("DeployTo");

        // Create an Azure Resource Group
        var resourceGroupName = $"rg-ne-rpc-demo-{deployTo}";
        var resourceGroup     = new ResourceGroup(resourceGroupName, new ResourceGroupArgs
        {
            Name = resourceGroupName
        });

        // Create an Azure Storage Account
        var storageAccount = new Account($"nerpcdemo{deployTo}", new AccountArgs
        {
            ResourceGroupName      = resourceGroup.Name,
            AccountReplicationType = "LRS",
            AccountTier            = "Standard"
        });

        // Container for deployment artefacts
        var zipContainer = new Container("zips", new ContainerArgs
        {
            StorageAccountName  = storageAccount.Name,
            ContainerAccessType = "private"
        });

        var dataContainer = new Container("data", new ContainerArgs
        {
            StorageAccountName  = storageAccount.Name,
            ContainerAccessType = "private",
            Name = "data"
        });

        var appServicePlan = new Plan($"plan-{deployTo}", new PlanArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Kind = "FunctionApp",
            Sku  = new PlanSkuArgs
            {
                Tier = "Dynamic",
                Size = "Y1",
            }
        });

        var blob = new Blob("azure-func", new BlobArgs
        {
            StorageAccountName   = storageAccount.Name,
            StorageContainerName = zipContainer.Name,
            Type   = "Block",
            Source = new FileArchive("../azure-func/publish")
        });

        var codeBlobUrl =
            SharedAccessSignature.SignedBlobReadUrl(blob, storageAccount);

        var app = new FunctionApp("app", new FunctionAppArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AppServicePlanId  = appServicePlan.Id,
            AppSettings       =
            {
                { "runtime",                  "dotnet"                                                      },
                { "WEBSITE_RUN_FROM_PACKAGE", codeBlobUrl                                                   },
                { "QuoteServerHost",          "https://vn651r8t22.execute-api.eu-west-2.amazonaws.com/Prod" },
                { "DataConnectionString",     storageAccount.PrimaryBlobConnectionString                    },
                { "DataContainer",            dataContainer.Name                                            }
            },
            StorageAccountName      = storageAccount.Name,
            StorageAccountAccessKey = storageAccount.PrimaryAccessKey,
            Version = "~3"
        });

        this.StorageAccountName = storageAccount.Name;
        this.Endpoint           = Output.Format($"https://{app.DefaultHostname}/api/lookup");
        this.DataContainer      = dataContainer.Name;
    }
Пример #30
0
    public WebAppStack()
    {
        var resourceGroup = new ResourceGroup("rg-easy-azure-webapp");

        var clientConfig = Output.Create(GetClientConfig.InvokeAsync());

        var tenantId         = clientConfig.Apply(config => config.TenantId);
        var currentPrincipal = clientConfig.Apply(config => config.ObjectId);

        var solutionRoot = System.Environment.GetEnvironmentVariable("SOLUTION_ROOT_DIRECTORY");

        var storageAccount = new Account("storage", new AccountArgs
        {
            ResourceGroupName      = resourceGroup.Name,
            AccountReplicationType = "LRS",
            AccountTier            = "Standard",
        });

        var storageContainer = new Container("files", new ContainerArgs
        {
            StorageAccountName  = storageAccount.Name,
            ContainerAccessType = "private",
        });

        var codeBlob = new Blob("zip", new BlobArgs
        {
            StorageAccountName   = storageAccount.Name,
            StorageContainerName = storageContainer.Name,
            Type = "Block",

            Source = new FileArchive(Path.Join(solutionRoot, "src/Services/EasyAzureWebApp/bin/Debug/netcoreapp3.1/publish"))
        });

        var keyVault = new KeyVault("key-vault", new KeyVaultArgs
        {
            ResourceGroupName = resourceGroup.Name,
            SkuName           = "standard",
            TenantId          = tenantId,
            SoftDeleteEnabled = true,
        });

        var keyVaultPolicy = new AccessPolicy("key-vault-policy", new AccessPolicyArgs
        {
            KeyVaultId        = keyVault.Id,
            TenantId          = tenantId,
            ObjectId          = currentPrincipal,
            SecretPermissions = new[] { "delete", "get", "list", "set" },
        });

        var codeBlobSecret = new Secret("zip-secret", new SecretArgs
        {
            KeyVaultId = keyVault.Id,
            Value      = SharedAccessSignature.SignedBlobReadUrl(codeBlob, storageAccount),
        });

        var codeBlobSecretUrl = Output.All(keyVault.VaultUri, codeBlobSecret.Name, codeBlobSecret.Version)
                                .Apply(d => $"{d[0]}secrets/{d[1]}/{d[2]}");

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

        var appService = new AppService("easy-azure-webapp", new AppServiceArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AppServicePlanId  = appServicePlan.Id,
            Identity          = new AppServiceIdentityArgs
            {
                Type = "SystemAssigned",
            },
            AppSettings = new InputMap <string>
            {
                { "WEBSITE_RUN_FROM_ZIP", codeBlobSecretUrl.Apply(url => $"@Microsoft.KeyVault(SecretUri={url})") },
            }
        });

        var appServiceGet = AppService.Get("easy-azure-webapp-get", appService.Id,
                                           new AppServiceState
        {
            ResourceGroupName = resourceGroup.Name,
            AppServicePlanId  = appServicePlan.Id,
        },
                                           new CustomResourceOptions
        {
            DependsOn = appService,
        }
                                           );

        var principalId = appServiceGet.Identity.Apply(id => id.PrincipalId !);

        var policy = new AccessPolicy("app-policy", new AccessPolicyArgs
        {
            KeyVaultId        = keyVault.Id,
            TenantId          = tenantId,
            ObjectId          = principalId,
            SecretPermissions = "get",
        });

        var subscriptionOutput = Output.Create(GetSubscription.InvokeAsync());
        var scope = Output.All(
            subscriptionOutput.Apply(s => s.SubscriptionId),
            resourceGroup.Name,
            storageAccount.Name,
            storageContainer.Name
            ).Apply(s => $"/subscriptions/{s[0]}/resourcegroups/{s[1]}/providers/Microsoft.Storage/storageAccounts/{s[2]}/blobServices/default/containers/{s[3]}");

        var codeBlobPermission = new Assignment("read-code-blob", new AssignmentArgs
        {
            PrincipalId        = principalId !,
            Scope              = scope,
            RoleDefinitionName = "Storage Blob Data Reader",
        },
Пример #31
0
 public void UpdateContainerACL(
     ITPCfSQL.Azure.Enumerations.ContainerPublicReadAccess containerPublicAccess,
     SharedAccessSignature.SharedAccessSignatureACL sasACL,
     Guid? LeaseId = null,
     int timeoutSeconds = 0,
     Guid? xmsclientrequestId = null
 )
 {
     Internal.InternalMethods.SetContainerACL(
         this.AzureBlobService.AccountName, this.AzureBlobService.SharedKey, this.AzureBlobService.UseHTTPS,
         this.Name, LeaseId, sasACL, containerPublicAccess,
         timeoutSeconds, xmsclientrequestId);
 }