Category: Uncategorized

  • Forward request

    The forward-request policy forwards the incoming request to the backend service specified in the request context. The backend service URL is specified in the API settings and can be changed using the set backend service policy.

    Removing this policy results in the request not being forwarded to the backend service. The policies in the outbound section are evaluated immediately upon the successful completion of the policies in the inbound section.

    XMLCopy

    <forward-request timeout="time in seconds" follow-redirects="true | false"/>
    

    Limit concurrency

    The limit-concurrency policy prevents enclosed policies from executing by more than the specified number of requests at any time. When requests exceed that number, new requests fail immediately with a 429 Too Many Requests status code.

    XMLCopy

    <limit-concurrency key="expression" max-count="number">
            <!— nested policy statements -->
    </limit-concurrency>
    

    Log to Event Hubs

    The log-to-eventhub policy sends messages in the specified format to an event hub defined by a Logger entity. As its name implies, the policy is used for saving selected request or response context information for online or offline analysis.

    XMLCopy

    <log-to-eventhub logger-id="id of the logger entity" partition-id="index of the partition where messages are sent" partition-key="value used for partition assignment">
      Expression returning a string to be logged
    </log-to-eventhub>
    

    Mock response

    The mock-response, as the name implies, is used to mock APIs and operations. It aborts normal pipeline execution and returns a mocked response to the caller. The policy always tries to return responses of highest fidelity. It prefers response content examples, whenever available. It generates sample responses from schemas, when schemas are provided and examples aren’t. If examples or schemas aren’t found, responses with no content are returned.

    XMLCopy

    <mock-response status-code="code" content-type="media type"/>
    

    Retry

    The retry policy executes its child policies once and then retries their execution until the retry condition becomes false or retry count is exhausted.

    XMLCopy

    <retry
        condition="boolean expression or literal"
        count="number of retry attempts"
        interval="retry interval in seconds"
        max-interval="maximum retry interval in seconds"
        delta="retry interval delta in seconds"
        first-fast-retry="boolean expression or literal">
            <!-- One or more child policies. No restrictions -->
    </retry>
  • Create advanced policies

    This unit provides a reference for the following API Management policies:

    • Control flow – Conditionally applies policy statements based on the results of the evaluation of Boolean expressions.
    • Forward request – Forwards the request to the backend service.
    • Limit concurrency – Prevents enclosed policies from executing by more than the specified number of requests at a time.
    • Log to Event Hubs – Sends messages in the specified format to an event hub defined by a Logger entity.
    • Mock response – Aborts pipeline execution and returns a mocked response directly to the caller.
    • Retry – Retries execution of the enclosed policy statements, if and until the condition is met. Execution repeats at the specified time intervals and up to the specified retry count.

    Control flow

    The choose policy applies enclosed policy statements based on the outcome of evaluation of boolean expressions, similar to an if-then-else or a switch construct in a programming language.

    XMLCopy

    <choose>
        <when condition="Boolean expression | Boolean constant">
            <!— one or more policy statements to be applied if the above condition is true  -->
        </when>
        <when condition="Boolean expression | Boolean constant">
            <!— one or more policy statements to be applied if the above condition is true  -->
        </when>
        <otherwise>
            <!— one or more policy statements to be applied if none of the above conditions are true  -->
    </otherwise>
    </choose>
    

    The control flow policy must contain at least one <when/> element. The <otherwise/> element is optional. Conditions in <when/> elements are evaluated in order of their appearance within the policy. Policy statements enclosed within the first <when/> element are applied when the condition attribute is true. Policies enclosed within the <otherwise/> element, if present, are applied if all of the <when/> element condition attributes are false.

  • Discover the API Management service

    API Management provides the core functionality to ensure a successful API program through developer engagement, business insights, analytics, security, and protection. Each API consists of one or more operations, and each API can be added to one or more products. To use an API, developers subscribe to a product that contains that API, and then they can call the API’s operation, subject to any usage policies.

  • Azure OpenAI Emit Token Metric Policy

    This policy addresses the need for detailed monitoring and analysis of token usage in applications using Azure OpenAI models.

    By providing comprehensive metrics, it helps organizations:

    • Optimize Resource Allocation: Understand and manage token consumption effectively.
    • Improve Decision-Making: Gain insights into usage patterns to make informed decisions about scaling and resource management.
    • Enhance Performance Monitoring: Track and analyze token usage to identify and address potential issues proactively

    How to use Emit Token Metric Policy

    To use this policy, you need to add it to the inbound processing pipeline of the API operation. Here’s how you encode it in XML:

    XMLCopy

    <azure-openai-emit-token-metric
            namespace="metric namespace" >      
            <dimension name="dimension name" value="dimension value" />
            ...additional dimensions...
    </azure-openai-emit-token-metric>
    

    Here’s an example using several dimensions:

    XMLCopy

    <policies>
      <inbound>
          <azure-openai-emit-token-metric
                namespace="AzureOpenAI">   
                <dimension name="User ID" />
                <dimension name="Client IP" value="@(context.Request.IpAddress)" />
                <dimension name="API ID" />
            </azure-openai-emit-token-metric> 
      </inbound>
      <outbound>
      </outbound>
    </policies>
    

    In the preceding example:

    • the policy is configured to emit token metrics to the AzureOpenAI namespace with dimensions for User ID, Client IP, and API ID.
    • The value of the Client IP dimension is set to the IP address of the client making the request.

    Imagine now that you can show these metrics in a dashboard and you can monitor the usage of your API in real time. For example, you can see how many tokens are being used by a specific user or how many tokens are being used by a specific API. This powerful feature that can help you optimize your resources and make informed decisions about scaling and resource management.

  • Token management

    Imagine you get a sudden spike in traffic towards your API, maybe there’s a sale or some other reason. To avoid over consumption and possible service disruption, you need to figure out how to manage that.

    Azure OpenAI Token Limit policy

    As mentioned in the beginning of this unit, sudden spike is something, you need to handle. The good news is that Azure API Management has something called Token Limit Policy.

    This policy allows customers to set limits on token consumption, expressed in tokens-per-minute (TPM) and ensures fair and efficient utilization of OpenAI resources.

    Key features

    The key features of this policy are:

    • Precise Control: Customers can assign token-based limits on various counter keys, such as Subscription key or IP Address, tailoring the enforcement to specific use cases.
    • Real-Time Monitoring: The policy relies on token usage metrics returned from the OpenAI endpoint, allowing for accurate monitoring and enforcement of limits in real-time.
    • Pre-Calculation of Tokens: It enables precalculation of prompt tokens on the Azure API Management side, minimizing unnecessary requests to the OpenAI backend if the limit is already exceeded.
    • Enhanced Customization: Customers can apply headers and variables such as tokens-consumed and remaining-tokens within policies for better control and customization.

    Ss you can see, there’s quite a few features that help you manage costs and thanks to the real-time monitoring you can make sure that you’re not exceeding the limits.

    How to use it

    To use this policy, you need to add it to the inbound processing pipeline of the API operation. Here’s how you can do it:

    XMLCopy

    <azure-openai-token-limit counter-key="key value"
            tokens-per-minute="number"
            estimate-prompt-tokens="true | false"    
            retry-after-header-name="custom header name, replaces default 'Retry-After'" 
            retry-after-variable-name="policy expression variable name"
            remaining-tokens-header-name="header name"  
            remaining-tokens-variable-name="policy expression variable name"
            tokens-consumed-header-name="header name"
            tokens-consumed-variable-name="policy expression variable name" />
    

    There’s quite a few attributes you can set, but the most important ones are:

    • counter-key: The key to use for counting tokens. This value can be a subscription key or an IP address.
    • tokens-per-minute: The number of tokens allowed per minute.
    • estimate-prompt-tokens: Whether to estimate prompt tokens or not.
  • API management

    So what’s the problem I’m having that makes me want to seek out an API management solution? You most likely have the following challenges:

    • Scaling, your API or APIs is used by many clients in different regions of the world and you need to ensure that it’s available and responsive.
    • Security, you need to ensure that your API is secure and that only authorized clients can access it.
    • Error management, you need to ensure that your API can handle errors gracefully.
    • Monitoring, you need to monitor your APIs to ensure that it’s performing as expected.
    • Resilience, you need to ensure that your API is resilient and can handle failures gracefully.

    For each of these challenges you could opt for a point solution, but that could be challenging to manage. Consider also that your APIs could be built in different tech stacks, which means the solutions to above challenges could mean you need different solutions for each API. If you’re having all these challenges, then you should consider a centralized API management solution like Azure API Management.

    Let’s dive deeper into some challenges and see how a centralized API management solution like Azure API Management can help you address them.

    Infrastructure as code, IaC

    It’s perfectly fine by creating your Azure resources using the Azure portal, but as your infrastructure grows, it becomes harder to manage. One of the problems you face is that you can’t easily replicate your infrastructure in another environment.

    It’s also hard to trace all the changes that are made to your infrastructure. This situation is where Infrastructure as Code (IaC) comes in. IaC is the practice of managing your infrastructure using code. To apply IaC on Azure, you have several options, one of which is Bicep. Bicep is a Domain Specific Language (DSL) for deploying Azure resources declaratively. It’s a great way to manage your cloud resources. Here’s a simple example of what Bicep looks like:

    BicepCopy

    param location string = 'eastus'
    
    resource storageAccount 'Microsoft.Storage/storageAccounts@2021-06-01' = {
      name: 'mystorageaccount'
      location: location
      kind: 'StorageV2'
      sku: {
        name: 'Standard_LRS'
      }
    }
    

    In the preceding example, we defined a storage account using Bicep. We defined the location of the storage account, the kind of storage account, and the SKU (stock-keeping unit). Location is a parameter that we can pass in when we deploy the Bicep file. To deploy the file presented, we would use the Azure CLI like so:

    BashCopy

    az deployment group create --resource-group myResourceGroup --template-file main.bicep
    

    The preceding command deploys the storage account to the resource group myResourceGroup and use the Bicep file main.bicep to create the resources in the file.

  • Secure your recovery strategy

    Make sure your backup and recovery setup is just as secure as your main environment, including security controls and frequency of backup.

    You should always have a clean, safe version of your system ready to go in case something goes wrong. That way, you can switch over to a secure backup system and restore data without introducing any threats.

    An ineffecient recovery process can slow down recovery, which can cause you to miss recovery targets. For example, a security problem like encrypted backup data that you can’t decipher or corrupted backup data might slow down recovery.

    Contoso’s challenge

    • The system runs in active-active mode across regions, and the team has a disaster recovery plan to help restore operations in worst case scenarios.
    • Part of this plan involves sending backups to a third region in the United States.
    • During a recent drill, they found out those backups were being stored in a system that wasn’t checked often and didn’t have strong security.
    • All the backups have been infected with malware. If they had a real disaster at that time, they wouldn’t have been able to recover successfully.

    Applying the approach and outcomes

    • The team invested time and effort to secure the backup location. They added stronger network and identity protections, and now backups are stored in a way that can’t be changed or tampered with.
    • After reviewing their security controls, the team finds that during the recovery process, the application runs without a WAF for a period of time. They change the order of operations to close that gap.
    • The team is confident that the backups and the recovery process are much more secure and not easy targets anymore.
  • Enhance reliability through robust security

    Use security controls and design patterns to stop attacks and bugs from overloading the system or locking people out.

    This approach helps keep the system up and running, even if someone tries to take it down with something like a distributed denial of service (DDoS) attack.

    Contoso’s challenge

    • The workload team and the workload’s stakeholders know that this system must be extremely reliable because hotel guests rely on it for both business and leisure travel. If it goes down, hotels can’t run properly.
    • The team has put a lot of effort into testing functional and nonfunctional requirements to make sure the system works well and stays operational, including using safe ways to roll out updates.
    • They’ve focused on keeping things reliable, but they haven’t paid as much attention to security. A recent update had a bug that hackers took advantage of, crashing the system for several hotels. The attack overloaded servers in one region for over four hours, causing major problems for guests and staff.
    • The attacker used the app’s servers to sneak in requests to a regional storage system and pull up fake folio data. One of those fake folios was huge and caused the servers to run out of memory. Then, when users tried again, it spread the problem to all the servers.

    Applying the approach and outcomes

    • The team changed the design so the app servers no longer handle folio requests directly. Instead, they’re using a Valet Key approach to limit access. This approach wouldn’t have stopped the attack completely, but it would have kept the damage contained.
    • They also added better input checks to clean up anything suspicious before it reaches the system.
    • With stronger input filtering and a smarter design, they’ve reduced the risk of this kind of attack happening again.

    Proactively limit attack vectors

    Set up controls ahead of time to block common ways that attackers try to break in, like bugs in your code, weak network setups, or missing antivirus.

    Regularly scan your code, install security updates, keep software current, and run antivirus tools. These practices help reduce the ways that attackers can get in, and they help keep things running smoothly.

    Contoso’s challenge

    • The system runs on Azure VMs (virtual machines) that use the latest Ubuntu images from Azure Marketplace. When each VM starts up, it installs some certificates, adjusts a few SSH settings, and loads the app code. But it doesn’t use any antivirus or anti-malware tools.
    • Azure Application Gateway fronts the solution, but it’s only used as an internet gateway. The web application firewall (WAF) function isn’t enabled currently.
    • These choices leave the system exposed to potential risks, like vulnerabilities in the code or accidental malware installs.

    Applying the approach and outcomes

    • After talking with the security team in Contoso, the VMs are now enrolled in an enterprise-managed antivirus solution.
    • The team also enables and fine-tunes the WAF function to block risky traffic, like SQL injection attempts, before it even reaches the app.
    • Both the app and its platform now have stronger layered defenses to help keep the system stable and secure.
  • Do threat modeling to find and resolve potential threats

    Analyze each part of your workflow and consider what could go wrong. Use an industry-standard methodology to classify the identified threats.

    Threat modeling helps you find and fix security threats before they become real problems. Analyzing your workload helps you put together a report that shows which attack paths are the most serious and helps you quickly find weak spots.

    Contoso’s challenge

    • Even though they haven’t had a security problem yet, the workload team doesn’t have a clear way to check if all possible threats are covered by their current security setup.
    • They realize that there’s a gap in their security, and if something goes wrong, they might not be ready.

    Applying the approach and outcomes

    • The team brings in a security consulting specialist to learn how to do threat modeling.
    • After their first exercise, they find that they have well-designed controls for most threat vectors, but there are some gaps:
      • One problem was in a data cleanup task that runs after Apache Spark jobs. It had two insider threat risks for data leaks.
      • An old system used by a race team that’s no longer active still had access to sensitive race data.
    • They’ve scheduled fixes for the next development cycle, including shutting down the old system.
  • Test controls yourself

    Have security experts try to ethically hack your system occasionally to find weak spots. Regularly scan your infrastructure, code, and tools to catch any vulnerabilities before they become real problems.

    Running security tests that mimic real-world attacks, like penetration testing, helps you see if your defenses actually work.

    Threats can sneak in during updates or changes, so it’s smart to build vulnerability scanners right into your deployment process. That way, you can catch problems early and even block risky code from going live until it’s fixed.

    Contoso’s challenge

    • The threat modeling exercise helped the team find some gaps in their security setup. Now they want to make sure their fixes are strong and that nothing was missed.
    • They’ve used open-source tools to test security and found it fun and useful. However, the team and stakeholders want to bring in security professionals to do thorough and rigorous testing regularly.

    Applying the approach and outcomes

    • The team contacts a well-known Microsoft partner that specializes in cloud security to talk about penetration testing.
    • The workload team signs a Statement of Work for quarterly penetration testing, including one white-box test each year for extra confidence.
    • The consulting team also helps the development team install anti-malware on dev boxes and the self-hosted build agents.
    • Now, both the team and stakeholders feel a lot more confident that they’re ready for potential threats.