├── .devcontainer └── devcontainer.json ├── .editorconfig ├── .gitattributes ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── 1-feature.yml │ ├── 2-bug.yml │ └── config.yml ├── dependabot.yml └── workflows │ └── dotnet.yml ├── .gitignore ├── .pipeline └── release.yml ├── .vscode └── extensions.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── SUPPORT.md ├── apim-policy-toolkit.sln ├── docs ├── AvailablePolicies.md ├── DevEnvironmentSetup.md ├── IntegratePolicySolution.md ├── IntegratePolicySolutionWithApiOps.md ├── QuickStart.md ├── SolutionStructureRecommendation.md └── images │ └── pkgicon.png ├── example ├── .config │ └── dotnet-tools.json ├── .gitIgnore ├── Example.sln ├── README.md ├── ci-pipeline.cmd ├── deployment.bicep ├── nuget.config ├── source │ ├── ApiOperationPolicy.cs │ ├── RequestOAuth2FromSAPUsingAAD.cs │ └── Source.Example.csproj ├── target │ └── echo-api.retrieve-resource.xml.example └── test │ ├── ApiOperationPolicyTest.cs │ ├── Test.Example.csproj │ └── Usings.cs ├── output └── README.md ├── rm-obj.ps1 ├── setup-example.cmd ├── setup-example.sh ├── src ├── Analyzers │ ├── Analyzers.csproj │ ├── ExpressionDefinition.Analyzer.cs │ ├── ExpressionDefinition.Rules.cs │ ├── ExpressionTypeUsed.Analyzer.cs │ ├── ExpressionTypeUsed.Rules.cs │ └── Extensions │ │ ├── SymbolExtensions.cs │ │ └── SyntaxExtensions.cs ├── Authoring │ ├── Attributes │ │ ├── DocumentAttribute.cs │ │ ├── ExpressionAllowedAttribute.cs │ │ └── ExpressionAttribute.cs │ ├── Authoring.csproj │ ├── Configs │ │ ├── BasicAuthenticationConfig.cs │ │ ├── BodyConfig.cs │ │ ├── CacheLookupConfig.cs │ │ ├── CacheLookupValueConfig.cs │ │ ├── CacheRemoveValueConfig.cs │ │ ├── CacheStoreValueConfig.cs │ │ ├── CertificateAuthenticationConfig.cs │ │ ├── CheckHeaderConfig.cs │ │ ├── ClaimConfig.cs │ │ ├── CorsConfig.cs │ │ ├── EmitMetricConfig.cs │ │ ├── EmitTokenMetricConfig.cs │ │ ├── ForwardRequestConfig.cs │ │ ├── GetAuthorizationContextConfig.cs │ │ ├── HeaderConfig.cs │ │ ├── IAuthenticationConfig.cs │ │ ├── InvokeDarpBindingConfig.cs │ │ ├── IpFilterConfig.cs │ │ ├── JsonToXmlConfig.cs │ │ ├── LimitConcurrencyConfig.cs │ │ ├── LlmContentSafetyConfig.cs │ │ ├── LogToEventHubConfig.cs │ │ ├── ManagedIdentityAuthenticationConfig.cs │ │ ├── MetricDimensionConfig.cs │ │ ├── MockResponseConfig.cs │ │ ├── ProxyConfig.cs │ │ ├── PublishToDarpConfig.cs │ │ ├── QuotaByKeyConfig.cs │ │ ├── QuotaConfig.cs │ │ ├── RateLimitByKeyConfig.cs │ │ ├── RateLimitConfig.cs │ │ ├── RetryConfig.cs │ │ ├── ReturnResponseConfig.cs │ │ ├── SemanticCacheLookupConfig.cs │ │ ├── SendOneWayRequestConfig.cs │ │ ├── SendRequestConfig.cs │ │ ├── SetBackendServiceConfig.cs │ │ ├── SetBodyConfig.cs │ │ ├── StatusConfig.cs │ │ ├── TokenLimitConfig.cs │ │ ├── TraceConfig.cs │ │ ├── ValidateAzureAdTokenConfig.cs │ │ ├── ValidateClientCertificateConfig.cs │ │ ├── ValidateContentConfig.cs │ │ ├── ValidateHeadersConfig.cs │ │ ├── ValidateJwtConfig.cs │ │ ├── ValidateOdataRequestConfig.cs │ │ ├── ValidateParametersConfig.cs │ │ ├── ValidateStatusCodeConfig.cs │ │ ├── XmlToJsonConfig.cs │ │ └── XslTransformConfig.cs │ ├── DocumentScope.cs │ ├── Expression.cs │ ├── Expressions │ │ ├── Authorization.cs │ │ ├── BasicAuthCredentials.cs │ │ ├── DictionaryExtensions.cs │ │ ├── IApi.cs │ │ ├── IContextApi.cs │ │ ├── IDeployment.cs │ │ ├── IExpressionContext.cs │ │ ├── IGroup.cs │ │ ├── ILastError.cs │ │ ├── IMessageBody.cs │ │ ├── IOperation.cs │ │ ├── IPrivateEndpointConnection.cs │ │ ├── IProduct.cs │ │ ├── IRequest.cs │ │ ├── IResponse.cs │ │ ├── ISubscription.cs │ │ ├── ISubscriptionKeyParameterNames.cs │ │ ├── IUrl.cs │ │ ├── IUser.cs │ │ ├── IUserIdentity.cs │ │ ├── Jwt.cs │ │ └── StringExtensions.cs │ ├── IBackendContext.cs │ ├── IDocument.cs │ ├── IHaveExpressionContext.cs │ ├── IInboundContext.cs │ ├── IOnErrorContext.cs │ ├── IOutboundContext.cs │ ├── Implementations │ │ ├── IBasicAuthCredentialsParser.cs │ │ ├── IJwtParser.cs │ │ ├── IUrlContentEncoder.cs │ │ └── ImplementationContext.cs │ ├── README.md │ └── tools │ │ ├── install.ps1 │ │ └── uninstall.ps1 ├── Compiling │ ├── CompilerOptions.cs │ ├── Compiling.csproj │ ├── Program.cs │ └── README.md ├── Core │ ├── Compiling │ │ ├── CompilerUtils.cs │ │ ├── Diagnostics │ │ │ └── CompilationErrors.cs │ │ ├── DirectoryCompiler.cs │ │ ├── DirectoryCompilerOptions.cs │ │ ├── DirectoryCompilerResult.cs │ │ ├── DocumentCompilationContext.cs │ │ ├── DocumentCompiler.cs │ │ ├── IDocumentCompilationContext.cs │ │ ├── IDocumentCompilationResult.cs │ │ ├── IMethodPolicyHandler.cs │ │ ├── IReturnValueMethodPolicyHandler.cs │ │ ├── ISyntaxCompiler.cs │ │ ├── Policy │ │ │ ├── AuthenticationBasicCompiler.cs │ │ │ ├── AuthenticationCertificateCompiler.cs │ │ │ ├── AuthenticationManageIdentityReturnValueCompiler.cs │ │ │ ├── AuthenticationManagedIdentityCompiler.cs │ │ │ ├── BaseCompiler.cs │ │ │ ├── CacheLookupCompiler.cs │ │ │ ├── CacheLookupValueCompiler.cs │ │ │ ├── CacheRemoveValueCompiler.cs │ │ │ ├── CacheStoreCompiler.cs │ │ │ ├── CacheStoreValueCompiler.cs │ │ │ ├── CheckHeaderCompiler.cs │ │ │ ├── ClaimsConfigCompiler.cs │ │ │ ├── CorsCompiler.cs │ │ │ ├── CrossDomainCompiler.cs │ │ │ ├── EmitMetricCompiler.cs │ │ │ ├── EmitTokenMetricCompiler.cs │ │ │ ├── FindAndReplaceCompiler.cs │ │ │ ├── ForwardRequestCompiler.cs │ │ │ ├── GenericCompiler.cs │ │ │ ├── GetAuthorizationContextCompiler.cs │ │ │ ├── IncludeFragmentCompiler.cs │ │ │ ├── InlinePolicyCompiler.cs │ │ │ ├── InvokeDarpBindingCompiler.cs │ │ │ ├── IpFilterCompiler.cs │ │ │ ├── JsonPCompiler.cs │ │ │ ├── JsonToXmlCompiler.cs │ │ │ ├── LimitConcurrencyCompiler.cs │ │ │ ├── LlmContentSafetyCompiler.cs │ │ │ ├── LogToEventHubCompiler.cs │ │ │ ├── MockResponseCompiler.cs │ │ │ ├── ProxyCompiler.cs │ │ │ ├── PublishToDarpCompiler.cs │ │ │ ├── QuotaByKeyCompiler.cs │ │ │ ├── QuotaCompiler.cs │ │ │ ├── RateLimitByKeyCompiler.cs │ │ │ ├── RateLimitCompiler.cs │ │ │ ├── RedirectContentUrlsCompiler.cs │ │ │ ├── RetryCompiler.cs │ │ │ ├── ReturnResponseCompiler.cs │ │ │ ├── RewriteUriCompiler.cs │ │ │ ├── SemanticCacheLookupCompiler.cs │ │ │ ├── SemanticCacheStoreCompiler.cs │ │ │ ├── SendOneWayRequestCompiler.cs │ │ │ ├── SendRequestCompiler.cs │ │ │ ├── SetBackendServiceCompiler.cs │ │ │ ├── SetBodyCompiler.cs │ │ │ ├── SetHeaderCompiler.cs │ │ │ ├── SetMethodCompiler.cs │ │ │ ├── SetQueryParameterCompiler.cs │ │ │ ├── SetStatusCompiler.cs │ │ │ ├── SetVariableCompiler.cs │ │ │ ├── TokenLimitCompiler.cs │ │ │ ├── TraceCompiler.cs │ │ │ ├── ValidateAzureAdTokenCompiler.cs │ │ │ ├── ValidateClientCertificateCompiler.cs │ │ │ ├── ValidateContentCompiler.cs │ │ │ ├── ValidateHeadersCompiler.cs │ │ │ ├── ValidateJwtCompiler.cs │ │ │ ├── ValidateOdataRequestCompiler.cs │ │ │ ├── ValidateParametersCompiler.cs │ │ │ ├── ValidateStatusCodeCompiler.cs │ │ │ ├── WaitCompiler.cs │ │ │ ├── XmlToJsonCompiler.cs │ │ │ └── XslTransformCompiler.cs │ │ ├── ProjectCompiler.cs │ │ ├── ProjectCompilerOptions.cs │ │ ├── ProjectCompilerResult.cs │ │ ├── Syntax │ │ │ ├── BlockCompiler.cs │ │ │ ├── ExpressionStatementCompiler.cs │ │ │ ├── IfStatementCompiler.cs │ │ │ └── LocalDeclarationStatementCompiler.cs │ │ ├── SyntaxExtensions.cs │ │ └── TriviaRemoverRewriter.cs │ ├── Core.csproj │ ├── IO │ │ ├── FileUtils.cs │ │ └── PathUtils.cs │ ├── IoC │ │ ├── CompilerModule.cs │ │ └── LazilyResolutionModule.cs │ └── Serialization │ │ ├── CustomXmlWriter.cs │ │ └── RazorCodeFormatter.cs ├── Templates │ ├── README.md │ ├── Templates.csproj │ └── content │ │ ├── create-policy-document │ │ ├── .template.config │ │ │ └── template.json │ │ └── PolicyDocument1.cs │ │ └── create-solution │ │ ├── .config │ │ └── dotnet-tools.json │ │ ├── .template.config │ │ └── template.json │ │ ├── Project.Solution.sln │ │ ├── src │ │ └── Project.Source.csproj │ │ └── test │ │ └── Project.Test.csproj └── Testing │ ├── Document │ ├── MockAppendHeaderProvider.cs │ ├── MockAppendQueryParameterProvider.cs │ ├── MockAuthenticationBasicProvider.cs │ ├── MockAuthenticationCertificateProvider.cs │ ├── MockAuthenticationManagedIdentityProvider.cs │ ├── MockAzureOpenAiEmitTokenMetricProvider.cs │ ├── MockAzureOpenAiSemanticCacheLookupProvider.cs │ ├── MockAzureOpenAiSemanticCacheStoreProvider.cs │ ├── MockBaseProvider.cs │ ├── MockCacheLookupProvider.cs │ ├── MockCacheLookupValueProvider.cs │ ├── MockCacheRemoveValueProvider.cs │ ├── MockCacheStoreProvider.cs │ ├── MockCacheStoreValueProvider.cs │ ├── MockCheckHeaderProvider.cs │ ├── MockCorsProvider.cs │ ├── MockEmitMetricProvider.cs │ ├── MockForwardRequestProvider.cs │ ├── MockInlineProvider.cs │ ├── MockIpFilterProvider.cs │ ├── MockJsonPProvider.cs │ ├── MockJsonToXmlProvider.cs │ ├── MockLlmEmitTokenMetricProvider.cs │ ├── MockLlmSemanticCacheLookupProvider.cs │ ├── MockLlmSemanticCacheStoreProvider.cs │ ├── MockLogToEventHubProvider.cs │ ├── MockMockResponseProvider.cs │ ├── MockPoliciesProvider.cs │ ├── MockQuotaProvider.cs │ ├── MockRateLimitByKeyProvider.cs │ ├── MockRateLimitProvider.cs │ ├── MockRemoveHeaderProvider.cs │ ├── MockRemoveQueryParameterProvider.cs │ ├── MockReturnResponseProvider.cs │ ├── MockRewriteUriProvider.cs │ ├── MockSendRequestProvider.cs │ ├── MockSetBackendServiceProvider.cs │ ├── MockSetBodyProvider.cs │ ├── MockSetHeaderIfNotExistProvider.cs │ ├── MockSetHeaderProvider.cs │ ├── MockSetMethodProvider.cs │ ├── MockSetQueryParameterIfNotExistProvider.cs │ ├── MockSetQueryParameterProvider.cs │ ├── MockSetStatusProvider.cs │ ├── MockSetVariableProvider.cs │ ├── MockValidateJwtProvider.cs │ └── TestDocumentExtensions.cs │ ├── Emulator │ ├── Data │ │ ├── CacheStore.cs │ │ ├── CacheValue.cs │ │ ├── CertificateStore.cs │ │ ├── EventHubEvent.cs │ │ ├── Logger.cs │ │ ├── LoggerStore.cs │ │ ├── ResponseExample.cs │ │ └── ResponseExampleStore.cs │ ├── FinishSectionProcessingException.cs │ ├── IPAddressExtentions.cs │ ├── IPolicyHandler.cs │ ├── Policies │ │ ├── AppendHeaderHandler.cs │ │ ├── AppendQueryParameterHandler.cs │ │ ├── ArgumentsExtensions.cs │ │ ├── AuthenticationBasicHandler.cs │ │ ├── AuthenticationCertificateHandler.cs │ │ ├── AuthenticationManagedIdentityHandler.cs │ │ ├── AzureOpenAiEmitTokenMetricHandler.cs │ │ ├── AzureOpenAiSemanticCacheLookupHandler.cs │ │ ├── AzureOpenAiSemanticCacheStoreHandler.cs │ │ ├── BaseHandler.cs │ │ ├── CacheLookupHandler.cs │ │ ├── CacheLookupValueHandler.cs │ │ ├── CacheRemoveValueHandler.cs │ │ ├── CacheStoreHandler.cs │ │ ├── CacheStoreValueHandler.cs │ │ ├── CheckHeaderHandler.cs │ │ ├── CorsHandler.cs │ │ ├── EmitMetricHandler.cs │ │ ├── ExpressionContextHandler.cs │ │ ├── ForwardRequestHandler.cs │ │ ├── InlinePolicyHandler.cs │ │ ├── IpFilterHandler.cs │ │ ├── JsonPHandler.cs │ │ ├── JsonToXmlHandle.cs │ │ ├── LlmEmitTokenMetricHandler.cs │ │ ├── LlmSemanticCacheLookupHandler.cs │ │ ├── LlmSemanticCacheStoreHandler.cs │ │ ├── LogToEventHubHandler.cs │ │ ├── MockResponseHandler.cs │ │ ├── QuotaHandler.cs │ │ ├── RateLimitByKeyHandler.cs │ │ ├── RateLimitHandler.cs │ │ ├── RemoveHeaderHandler.cs │ │ ├── RemoveQueryParameterHandler.cs │ │ ├── ReturnResponseHandler.cs │ │ ├── RewriteUriHandler.cs │ │ ├── SendRequestHandler.cs │ │ ├── SetBackendServiceHandler.cs │ │ ├── SetBodyHandler.cs │ │ ├── SetHeaderHandler.cs │ │ ├── SetHeaderIfNotExistHandler.cs │ │ ├── SetMethodHandler.cs │ │ ├── SetQueryParameterHandler.cs │ │ ├── SetQueryParameterIfNotExistHandler.cs │ │ ├── SetStatusHandler.cs │ │ ├── SetVariableHandler.cs │ │ └── ValidateJwtHandler.cs │ ├── PolicyExeption.cs │ ├── PolicyHandler.cs │ ├── SectionAttribute.cs │ └── SectionContextProxy.cs │ ├── Expressions │ ├── Extensions │ │ ├── BasicAuthCredentialsParser.cs │ │ ├── JwtParser.cs │ │ ├── MockBasicAuthCredentials.cs │ │ ├── MockExtensions.cs │ │ ├── MockJwt.cs │ │ └── UrlContentEncoder.cs │ ├── MockApi.cs │ ├── MockBody.cs │ ├── MockContextApi.cs │ ├── MockDeployment.cs │ ├── MockExpressionContext.cs │ ├── MockGroup.cs │ ├── MockLastError.cs │ ├── MockMessage.cs │ ├── MockOperation.cs │ ├── MockPrivateEndpointConnection.cs │ ├── MockProduct.cs │ ├── MockRequest.cs │ ├── MockResponse.cs │ ├── MockSubscription.cs │ ├── MockSubscriptionKeyParameterNames.cs │ ├── MockUrl.cs │ ├── MockUser.cs │ └── MockUserIdentity.cs │ ├── GatewayContext.cs │ ├── IDocumentExtensions.cs │ ├── README.md │ ├── TestDocument.cs │ └── Testing.csproj └── test ├── Test.Analyzers ├── BaseAnalyzerTest.cs ├── ExpressionMethodTests.cs ├── Test.Analyzers.csproj ├── TypeUsedTests.cs └── Usings.cs ├── Test.Core ├── Assertions │ ├── AssertionExtensions.cs │ ├── CompilationResultAssertion.cs │ └── XElementAssertionsExtensions.cs ├── CompilerTestInitialize.cs ├── Compiling │ ├── AuthenticatiionBasicTests.cs │ ├── AuthenticatiionManagedIdentityTests.cs │ ├── AuthenticationCertificateTests.cs │ ├── AzureOpenAiEmitTokenMetricTests.cs │ ├── AzureOpenAiSemanticCacheLookupTests.cs │ ├── AzureOpenAiSemanticCacheStoreTests.cs │ ├── AzureOpenAiTokenLimitTests.cs │ ├── BaseTests.cs │ ├── CacheLookupTests.cs │ ├── CacheLookupValueTests.cs │ ├── CacheRemoveValueTests.cs │ ├── CacheStoreTests.cs │ ├── CacheStoreValueTests.cs │ ├── CheckHeaderTests.cs │ ├── ChooseTests.cs │ ├── CorsTests.cs │ ├── CrossDomainTests.cs │ ├── EmitMetricTests.cs │ ├── FindAndReplaceTests.cs │ ├── ForwardRequestTests.cs │ ├── GetAuthorizationContextTests.cs │ ├── IncludeFragmentTests.cs │ ├── InlinePolicyTests.cs │ ├── InvokeDarpBindingTests.cs │ ├── IpFilterTests.cs │ ├── JsonPTests.cs │ ├── JsonToXmlTests.cs │ ├── LimitConcurrencyTests.cs │ ├── LlmContentSafetyTests.cs │ ├── LlmEmitTokenMetricTests.cs │ ├── LlmSemanticCacheLookupTests.cs │ ├── LlmSemanticCacheStoreTests.cs │ ├── LlmTokenLimitTests.cs │ ├── LogToEventHubTests.cs │ ├── MockResponseTests.cs │ ├── ProxyTests.cs │ ├── PublishToDarpTests.cs │ ├── QuotaByKeyTests.cs │ ├── QuotaTests.cs │ ├── RateLimitByKeyTests.cs │ ├── RateLimitTests.cs │ ├── RedirectContentUrlsTests.cs │ ├── RetryTests.cs │ ├── ReturnResponseTests.cs │ ├── RewriteUriTests.cs │ ├── SendOneWayRequestTests.cs │ ├── SendRequestTests.cs │ ├── SetBackendServiceTests.cs │ ├── SetBodyTests.cs │ ├── SetHeaderTests.cs │ ├── SetMethodTests.cs │ ├── SetQueryParameterTests.cs │ ├── SetStatusTests.cs │ ├── SetVariableTests.cs │ ├── TraceTests.cs │ ├── ValidateAzureAdTokenTests.cs │ ├── ValidateClientCertificateTests.cs │ ├── ValidateContentTests.cs │ ├── ValidateHeadersTests.cs │ ├── ValidateJwtTests.cs │ ├── ValidateOdataRequestTests.cs │ ├── ValidateParametersTests.cs │ ├── ValidateStatusCodeTests.cs │ ├── WaitTests.cs │ ├── XmlToJsonTests.cs │ └── XslTransformTests.cs ├── IO │ └── PathUtilsTests.cs ├── Serialization │ ├── CustomXmlWriterTests.cs │ └── RazorCodeFormatterTests.cs ├── Test.Core.csproj ├── TestingDocument.cs └── Usings.cs └── Test.Testing ├── BasicAuthCredentialsParserTests.cs ├── Emulator ├── IPAddressExtensionsTests.cs └── Policies │ ├── AppendHeaderTests.cs │ ├── AppendQueryParameterTests.cs │ ├── AuthenticationBasicTests.cs │ ├── AuthenticationCertificateTests.cs │ ├── AuthenticationManagedIdentityHandlerTests.cs │ ├── AzureOpenAiEmitTokenMetricTests.cs │ ├── AzureOpenAiSemanticCacheLookupTests.cs │ ├── BaseTests.cs │ ├── CacheLookupValueTests.cs │ ├── CacheRemoveValueTests.cs │ ├── CacheStoreValueTests.cs │ ├── CheckHeaderTests.cs │ ├── ForwardRequestTests.cs │ ├── IpFilterTests.cs │ ├── LogToEventHubTests.cs │ ├── MockResponseTests.cs │ ├── SetHeaderTests.cs │ └── SetStatusTests.cs ├── JwtParserTests.cs ├── Test.Testing.csproj ├── TestDocumentTests.cs ├── UrlContentEncoderTests.cs └── Usings.cs /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 2 | // README at: https://github.com/devcontainers/templates/tree/main/src/dotnet 3 | { 4 | "name": "C# (.NET)", 5 | // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile 6 | "image": "mcr.microsoft.com/devcontainers/dotnet:1-8.0-bookworm", 7 | "features": { 8 | "ghcr.io/stuartleeks/dev-container-features/shell-history:0": {} 9 | }, 10 | "customizations": { 11 | "vscode": { 12 | "extensions": [ 13 | "ms-dotnettools.csdevkit", 14 | "EditorConfig.EditorConfig", 15 | "streetsidesoftware.code-spell-checker" 16 | ] 17 | } 18 | } 19 | // Features to add to the dev container. More info: https://containers.dev/features. 20 | // "features": {}, 21 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 22 | // "forwardPorts": [5000, 5001], 23 | // "portsAttributes": { 24 | // "5001": { 25 | // "protocol": "https" 26 | // } 27 | // } 28 | // Use 'postCreateCommand' to run commands after the container is created. 29 | // "postCreateCommand": "dotnet restore", 30 | // Configure tool-specific properties. 31 | // "customizations": {}, 32 | // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. 33 | // "remoteUser": "root" 34 | } -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | *.cs text diff=csharp 5 | *.cshtml text diff=html 6 | *.csx text diff=csharp 7 | *.sln text eol=crlf 8 | *.csproj text eol=crlf -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # These owners will be the default owners for everything in 2 | # the repo. Unless a later match takes precedence 3 | * @Mielek @tomkerkhove @maciejtreder 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/1-feature.yml: -------------------------------------------------------------------------------- 1 | name: Feature request 2 | description: Suggest an idea for this project 3 | labels: "feature-request" 4 | assignees: mielek 5 | body: 6 | - type: textarea 7 | attributes: 8 | label: Proposal 9 | description: "What would you like to have as a feature" 10 | placeholder: "A clear and concise description of what you want to happen." 11 | - type: dropdown 12 | attributes: 13 | label: Component 14 | description: Which part of the project is affected? 15 | multiple: true 16 | options: 17 | - Authoring library 18 | - Compiler 19 | - Emulator library 20 | validations: 21 | required: true 22 | - type: input 23 | attributes: 24 | label: Contact Details 25 | description: How can we get in touch with you if we need more info? 26 | placeholder: ex. email@example.com 27 | validations: 28 | required: false 29 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | contact_links: 3 | - name: Ask a question on Stack Overflow 💬 4 | url: https://stackoverflow.com/questions/tagged/azure-api-management 5 | about: Ask a question or request support for using Azure API Management policy toolkit. 6 | - name: Open a discussion 🗣 7 | url: https://github.com/Azure/azure-api-management-policy-toolkit/discussions 8 | about: Start a discussion about the project or its policies. 9 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "nuget" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-dotnettools.vscode-dotnet-runtime", 4 | "ms-dotnettools.csharp", 5 | "ms-dotnettools.csdevkit", 6 | "ms-dotnettools.vscodeintellicode-csharp", 7 | "editorconfig.editorconfig", 8 | "streetsidesoftware.code-spell-checker" 9 | ] 10 | } -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | - Employees can reach out at [aka.ms/opensource/moderation-support](https://aka.ms/opensource/moderation-support) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) Microsoft Corporation. 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /SUPPORT.md: -------------------------------------------------------------------------------- 1 | # Support 2 | 3 | ## How to get help and support 4 | 5 | For help and questions about using this project, please use (in order of preference): 6 | * The GitHub discussions in this repository 7 | * Stack Overflow with the tag `azure-api-management` 8 | 9 | ## How to file issues 10 | 11 | This project uses GitHub Issues to track bugs and feature requests. 12 | Please search the existing issues before filing new issues to avoid duplicates. 13 | For new issues, file your bug or feature request as a new Issue. 14 | For more information see the [CONTRIBUTING](CONTRIBUTING.md) file. 15 | 16 | ## Microsoft Support Policy 17 | 18 | Support for this **PROJECT** is limited to the resources listed above. 19 | Support from Azure Support is not available. -------------------------------------------------------------------------------- /docs/images/pkgicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure/azure-api-management-policy-toolkit/1572a01533473e1aa8f9806988a569f17b749a15/docs/images/pkgicon.png -------------------------------------------------------------------------------- /example/.config/dotnet-tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "isRoot": true, 4 | "tools": { 5 | "Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling": { 6 | "version": "1.0.0", 7 | "commands": [ 8 | "azure-apim-policy-compiler" 9 | ] 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /example/.gitIgnore: -------------------------------------------------------------------------------- 1 | bin 2 | obj 3 | TestResults 4 | target/*.xml -------------------------------------------------------------------------------- /example/Example.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\Test.Example.csproj", "{E119F8C2-6ACB-4502-B71E-6CB061E96AA5}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "source", "source\Source.Example.csproj", "{C1EF6FE8-D44D-4CE6-BE38-CE92CE4112DA}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(SolutionProperties) = preSolution 16 | HideSolutionNode = FALSE 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {E119F8C2-6ACB-4502-B71E-6CB061E96AA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {E119F8C2-6ACB-4502-B71E-6CB061E96AA5}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {E119F8C2-6ACB-4502-B71E-6CB061E96AA5}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {E119F8C2-6ACB-4502-B71E-6CB061E96AA5}.Release|Any CPU.Build.0 = Release|Any CPU 23 | {C1EF6FE8-D44D-4CE6-BE38-CE92CE4112DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {C1EF6FE8-D44D-4CE6-BE38-CE92CE4112DA}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {C1EF6FE8-D44D-4CE6-BE38-CE92CE4112DA}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {C1EF6FE8-D44D-4CE6-BE38-CE92CE4112DA}.Release|Any CPU.Build.0 = Release|Any CPU 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # Example project 2 | 3 | This is an example of repository which is using the policy toolkit. 4 | 5 | ## Testing 6 | The test folder contains tests for expressions. 7 | -------------------------------------------------------------------------------- /example/ci-pipeline.cmd: -------------------------------------------------------------------------------- 1 | dotnet build || exit -1 2 | dotnet test || exit -2 3 | dotnet azure-apim-policy-compiler --s .\source\ --o .\target\ --format true || exit -3 4 | az deployment group create --resource-group YOUR_RESOURCE_GROUP --template-file .\deployment.bicep --parameters servicename=YOUR_SERVICE_NAME --name deploy-1 || exit -4 5 | -------------------------------------------------------------------------------- /example/deployment.bicep: -------------------------------------------------------------------------------- 1 | param servicename string 2 | 3 | resource service 'Microsoft.ApiManagement/service@2023-03-01-preview' existing = { 4 | name: servicename 5 | scope: resourceGroup() 6 | } 7 | 8 | resource echoApi 'Microsoft.ApiManagement/service/apis@2023-03-01-preview' existing = { 9 | parent: service 10 | name: 'echo-api' 11 | } 12 | 13 | resource retrieveResource 'Microsoft.ApiManagement/service/apis/operations@2023-03-01-preview' existing = { 14 | parent: echoApi 15 | name: 'retrieve-resource' 16 | } 17 | 18 | resource retrieveResourcePolicy 'Microsoft.ApiManagement/service/apis/operations/policies@2023-03-01-preview' = { 19 | parent: retrieveResource 20 | name: 'policy' 21 | properties: { 22 | format: 'rawxml' 23 | value: loadTextContent('./target/${echoApi.name}.${retrieveResource.name}.xml', 'utf-8') 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /example/nuget.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /example/source/Source.Example.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Contoso.Apis 5 | 1.0.0 6 | 7 | 8 | 9 | .net8 10 | enable 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /example/target/echo-api.retrieve-resource.xml.example: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | true 8 | 9 | 10 | 11 | 12 | 13 | 14 | @($"Bearer {context.Variables["token"]}") 15 | 16 | 17 | 18 | 19 | 20 | 21 | @{ 22 | var body = context.Response.Body.As(); 23 | foreach (var internalProperty in new string[]{"location", "secret"}) 24 | { 25 | if (body.ContainsKey(internalProperty)) 26 | { 27 | body.Remove(internalProperty); 28 | } 29 | } 30 | 31 | return body.ToString(); 32 | } 33 | 34 | 35 | -------------------------------------------------------------------------------- /example/test/Test.Example.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Contoso.Apis.Tests 5 | 1.0.0 6 | Mielek 7 | 8 | 9 | 10 | .net8 11 | enable 12 | disable 13 | 14 | false 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /example/test/Usings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | global using FluentAssertions; -------------------------------------------------------------------------------- /output/README.md: -------------------------------------------------------------------------------- 1 | # DO NOT PLACE ANY FILE HERE # 2 | 3 | Folder is intended to be a local feed for an example project. 4 | It will be automatically populated by the `dotnet pack` command. 5 | -------------------------------------------------------------------------------- /rm-obj.ps1: -------------------------------------------------------------------------------- 1 | Get-ChildItem .\ -include bin,obj -Recurse | ForEach-Object ($_) { Remove-Item $_.FullName -Force -Recurse } -------------------------------------------------------------------------------- /setup-example.cmd: -------------------------------------------------------------------------------- 1 | dotnet build 2 | dotnet pack 3 | cd ./example 4 | dotnet tool restore 5 | -------------------------------------------------------------------------------- /setup-example.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | set -e 3 | 4 | dotnet build 5 | dotnet pack 6 | cd ./example 7 | dotnet tool restore 8 | -------------------------------------------------------------------------------- /src/Analyzers/Analyzers.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | .net8 5 | enable 6 | enable 7 | true 8 | Microsoft.Azure.ApiManagement.PolicyToolkit.Analyzers 9 | 10 | false 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/Analyzers/ExpressionTypeUsed.Rules.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Collections.Immutable; 5 | 6 | using Microsoft.CodeAnalysis; 7 | 8 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Analyzers; 9 | 10 | public static partial class Rules 11 | { 12 | public static class TypeUsed 13 | { 14 | public readonly static DiagnosticDescriptor DisallowedType = new DiagnosticDescriptor( 15 | "APIM001", 16 | "Disallowed type used", 17 | "Type '{0}' is not allowed", 18 | "Type", 19 | DiagnosticSeverity.Error, 20 | isEnabledByDefault: true, 21 | description: "Description.", 22 | helpLinkUri: "TODO", 23 | customTags: new[] { "APIM", "ApiManagement" }); 24 | 25 | public readonly static DiagnosticDescriptor DisallowedMember = new DiagnosticDescriptor( 26 | "APIM002", 27 | "Disallowed member used", 28 | "Member '{0}' is not allowed", 29 | "Type", 30 | DiagnosticSeverity.Error, 31 | isEnabledByDefault: true, 32 | description: "Description.", 33 | helpLinkUri: "TODO", 34 | customTags: new[] { "APIM", "ApiManagement" }); 35 | 36 | 37 | public readonly static ImmutableArray All = ImmutableArray.Create( 38 | DisallowedType, DisallowedMember 39 | ); 40 | } 41 | } -------------------------------------------------------------------------------- /src/Analyzers/Extensions/SymbolExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.CodeAnalysis; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Analyzers; 7 | 8 | public static class SymbolExtensions 9 | { 10 | private readonly static SymbolDisplayFormat Format = new SymbolDisplayFormat( 11 | globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, 12 | typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, 13 | genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, 14 | miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers 15 | ); 16 | 17 | public static string ToFullyQualifiedString(this ISymbol symbol) => symbol.ToDisplayString(Format); 18 | } -------------------------------------------------------------------------------- /src/Authoring/Attributes/DocumentAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | [AttributeUsage(AttributeTargets.Class)] 7 | public class DocumentAttribute(string? name = null, DocumentScope scope = DocumentScope.Any) : Attribute 8 | { 9 | public string? Name { get; } = name; 10 | } -------------------------------------------------------------------------------- /src/Authoring/Attributes/ExpressionAllowedAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter)] 7 | public class ExpressionAllowedAttribute : Attribute 8 | { 9 | } -------------------------------------------------------------------------------- /src/Authoring/Attributes/ExpressionAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Runtime.CompilerServices; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | 8 | [AttributeUsage(AttributeTargets.Method)] 9 | public class ExpressionAttribute([CallerFilePath] string sourceFilePath = "") : Attribute 10 | { 11 | public string SourceFilePath { get; } = sourceFilePath; 12 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/BasicAuthenticationConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for Basic Authentication policy.
8 | /// Used with authentication-basic policy. 9 | ///
10 | public record BasicAuthenticationConfig : IAuthenticationConfig 11 | { 12 | /// 13 | /// Username used for authentication. 14 | /// 15 | [ExpressionAllowed] 16 | public required string Username { get; init; } 17 | 18 | /// 19 | /// Password used for authentication. 20 | /// 21 | [ExpressionAllowed] 22 | public required string Password { get; init; } 23 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/BodyConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the set-body policy with content.
8 | /// Inherits from SetBodyConfig. 9 | ///
10 | public record BodyConfig : SetBodyConfig 11 | { 12 | /// 13 | /// Required. Specifies the content to set as the body. 14 | /// 15 | [ExpressionAllowed] 16 | public required object? Content { get; init; } 17 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/CacheLookupValueConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the cache-lookup-value policy which retrieves a cached value and stores it in a variable. 8 | /// 9 | public record CacheLookupValueConfig 10 | { 11 | /// 12 | /// The key to use when looking up a value in the cache. 13 | /// Policy expressions are allowed. 14 | /// 15 | [ExpressionAllowed] 16 | public required string Key { get; init; } 17 | 18 | /// 19 | /// Name of the variable that will contain the cached value if the lookup is successful. 20 | /// 21 | public required string VariableName { get; init; } 22 | 23 | /// 24 | /// Value to assign to the named variable if the key isn't found in the cache or is expired. 25 | /// If not specified, the variable will contain null when the lookup fails. 26 | /// Policy expressions are allowed. 27 | /// 28 | [ExpressionAllowed] 29 | public object? DefaultValue { get; init; } 30 | 31 | /// 32 | /// Type of cache to use. Valid values are "internal" (per-gateway private cache) 33 | /// or "external" (shared cache as configured in the policy). 34 | /// If not specified, "external" is used. 35 | /// 36 | public string? CachingType { get; init; } 37 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/CacheRemoveValueConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the cache-remove-value policy, which removes a value from the cache.
8 | /// This policy is used to remove an item from the cache using a specified key.
9 | /// Learn more: cache-remove-value policy 10 | ///
11 | public record CacheRemoveValueConfig 12 | { 13 | /// 14 | /// Required. Specifies the key for which to remove the value from the cache.
15 | /// Policy expressions are allowed. 16 | ///
17 | [ExpressionAllowed] 18 | public required string Key { get; init; } 19 | 20 | /// 21 | /// Optional. One of the following values: prefer-external, external, internal.
22 | /// Default is prefer-external.
23 | /// Policy expressions are not allowed. 24 | ///
25 | public string? CachingType { get; init; } 26 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/CheckHeaderConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the check-header policy, which checks for the existence and value of an HTTP header in the request. 8 | /// 9 | public record CheckHeaderConfig 10 | { 11 | /// 12 | /// Specifies the name of the header to check. 13 | /// 14 | [ExpressionAllowed] 15 | public required string Name { get; init; } 16 | 17 | /// 18 | /// HTTP status code to return if the header check fails. Policy expressions are allowed. 19 | /// 20 | [ExpressionAllowed] 21 | public required int FailCheckHttpCode { get; init; } 22 | 23 | /// 24 | /// Error message to return if the header check fails. Policy expressions are allowed. 25 | /// 26 | [ExpressionAllowed] 27 | public required string FailCheckErrorMessage { get; init; } 28 | 29 | /// 30 | /// Indicates whether the header value comparison should ignore case. Policy expressions are allowed. 31 | /// 32 | [ExpressionAllowed] 33 | public required bool IgnoreCase { get; init; } 34 | 35 | /// 36 | /// Array of expected header values. Policy expressions are allowed. 37 | /// 38 | [ExpressionAllowed] 39 | public required string[] Values { get; init; } 40 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/ClaimConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for a required claim in the JWT. 8 | /// 9 | public record ClaimConfig 10 | { 11 | /// 12 | /// Specifies the name of the claim. 13 | /// 14 | public required string Name { get; init; } 15 | 16 | /// 17 | /// Specifies the match expression for the claim value. Policy expressions are allowed. 18 | /// 19 | [ExpressionAllowed] 20 | public string? Match { get; init; } 21 | 22 | /// 23 | /// Specifies the separator for multiple claim values. 24 | /// 25 | public string? Separator { get; init; } 26 | 27 | /// 28 | /// Specifies the allowed values for the claim. 29 | /// 30 | public string[]? Values { get; init; } 31 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/EmitMetricConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the emit-metric policy which emits custom metrics to Azure Monitor. 8 | /// This policy allows monitoring API usage patterns and performance data. 9 | /// 10 | public record EmitMetricConfig 11 | { 12 | /// 13 | /// Required. Specifies the name of the metric. 14 | /// The metric appears in Azure Monitor with this name. 15 | /// 16 | public required string Name { get; init; } 17 | 18 | /// 19 | /// Required. Specifies dimensions to include with the metric. 20 | /// Dimensions provide additional context and filtering capabilities for the metric in Azure Monitor. 21 | /// 22 | public required MetricDimensionConfig[] Dimensions { get; init; } 23 | 24 | /// 25 | /// Optional. Specifies the metric namespace. 26 | /// Defaults to "apim" if not specified. 27 | /// 28 | public string? Namespace { get; init; } 29 | 30 | /// 31 | /// Optional. Specifies the metric value. 32 | /// Defaults to 1 if not specified. 33 | /// 34 | [ExpressionAllowed] 35 | public double? Value { get; init; } 36 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/EmitTokenMetricConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the LLM and Azure OpenAI emit token metric policies to emit metrics about token usage. 8 | /// 9 | public record EmitTokenMetricConfig 10 | { 11 | /// 12 | /// Required. The dimensions to include with the metric.
13 | /// These dimensions can be used to filter and group the metrics in monitoring systems. 14 | ///
15 | [ExpressionAllowed] 16 | public required MetricDimensionConfig[] Dimensions { get; init; } 17 | 18 | /// 19 | /// Optional. The namespace to use for the metrics.
20 | /// If not specified, the default namespace is used. 21 | ///
22 | [ExpressionAllowed] 23 | public string? Namespace { get; init; } 24 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/HeaderConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | public record HeaderConfig 7 | { 8 | /// 9 | /// Specifies the name of the header. Policy expressions are allowed. 10 | /// 11 | [ExpressionAllowed] 12 | public required string Name { get; init; } 13 | 14 | /// 15 | /// Specifies the action to take if the header already exists. Possible values are "override" and "skip". Policy expressions are allowed. 16 | /// 17 | [ExpressionAllowed] 18 | public string? ExistsAction { get; init; } 19 | 20 | /// 21 | /// Specifies the values of the header to be set. Policy expressions are allowed. 22 | /// 23 | [ExpressionAllowed] 24 | public string[]? Values { get; init; } 25 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/IAuthenticationConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | public interface IAuthenticationConfig 7 | { 8 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/IpFilterConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the IpFilter policy.
8 | /// Specifies the action to take (allow or deny), IP addresses, and/or IP address ranges. 9 | ///
10 | public record IpFilterConfig 11 | { 12 | /// 13 | /// Specifies the action to take (allow or deny). Policy expressions are allowed. 14 | /// 15 | [ExpressionAllowed] 16 | public required string Action { get; init; } 17 | 18 | /// 19 | /// Specifies the IP addresses to filter. Policy expressions are allowed. 20 | /// 21 | [ExpressionAllowed] 22 | public string[]? Addresses { get; init; } 23 | 24 | /// 25 | /// Specifies the IP address ranges to filter. 26 | /// 27 | public AddressRange[]? AddressRanges { get; init; } 28 | } 29 | 30 | /// 31 | /// Represents an IP address range. 32 | /// 33 | public record AddressRange 34 | { 35 | /// 36 | /// Specifies the starting IP address of the range. Policy expressions are allowed. 37 | /// 38 | [ExpressionAllowed] 39 | public required string From { get; init; } 40 | 41 | /// 42 | /// Specifies the ending IP address of the range. Policy expressions are allowed. 43 | /// 44 | [ExpressionAllowed] 45 | public required string To { get; init; } 46 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/LimitConcurrencyConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the limit-concurrency policy.
8 | /// Specifies the maximum number of concurrent calls allowed and the behavior when the limit is reached. 9 | ///
10 | public record LimitConcurrencyConfig 11 | { 12 | /// 13 | /// Specifies the key used to identify the concurrency limit. Policy expressions are allowed. 14 | /// 15 | [ExpressionAllowed] 16 | public required string Key { get; init; } 17 | 18 | /// 19 | /// Specifies the maximum number of concurrent calls allowed. Policy expressions are not allowed. 20 | /// 21 | public required int MaxCount { get; init; } 22 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/LogToEventHubConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | public record LogToEventHubConfig 7 | { 8 | /// 9 | /// Name of a logger entity that has been configured in API Management. Policy expressions are allowed. 10 | /// 11 | [ExpressionAllowed] 12 | public required string LoggerId { get; init; } 13 | 14 | /// 15 | /// The message to be logged to the event hub. Policy expressions are allowed. 16 | /// 17 | [ExpressionAllowed] 18 | public required string Value { get; init; } 19 | 20 | /// 21 | /// Optional. Routes messages into specific partitions in the event hub. Policy expressions aren't allowed. 22 | /// 23 | public string? PartitionId { get; init; } 24 | 25 | /// 26 | /// Optional. Used to compute a hash to map to a partition. Policy expressions are allowed. 27 | /// 28 | [ExpressionAllowed] 29 | public string? PartitionKey { get; init; } 30 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/ManagedIdentityAuthenticationConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | public record ManagedIdentityAuthenticationConfig : IAuthenticationConfig 7 | { 8 | /// 9 | /// Required. The resource for which the token is requested. This is the resource ID or URL used when requesting a token from Azure AD.
10 | /// Example: https://management.azure.com/ or https://graph.microsoft.com/ 11 | ///
12 | [ExpressionAllowed] 13 | public required string Resource { get; init; } 14 | 15 | /// 16 | /// Optional. The client ID of the user-assigned managed identity.
17 | /// If this property is not specified, the system-assigned managed identity is used. 18 | ///
19 | [ExpressionAllowed] 20 | public string? ClientId { get; init; } 21 | 22 | /// 23 | /// Optional. The name of the variable where the access token will be stored for later use in the policy.
24 | /// If this property is not specified, the token is not saved to a variable. 25 | ///
26 | public string? OutputTokenVariableName { get; init; } 27 | 28 | /// 29 | /// Optional. When set to true, failures to obtain a token are ignored and processing continues to the next policy.
30 | /// Default is false. 31 | ///
32 | public bool? IgnoreError { get; init; } 33 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/MetricDimensionConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Defines a dimension for token usage metrics. 8 | /// Each dimension is a key-value pair that adds context to the metric. 9 | /// 10 | public class MetricDimensionConfig 11 | { 12 | /// 13 | /// Required. The name of the dimension. 14 | /// 15 | public required string Name { get; init; } 16 | 17 | /// 18 | /// Required. The value for the dimension. Can be a static value or a policy expression. 19 | /// Examples: "gpt-4", "completions", or expressions like "@(context.Request.Headers.GetValueOrDefault("x-operation-id"))". 20 | /// 21 | [ExpressionAllowed] 22 | public string? Value { get; init; } 23 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/MockResponseConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the mock-response policy that returns a fabricated response directly to the caller. 8 | /// 9 | public record MockResponseConfig 10 | { 11 | /// 12 | /// HTTP status code to be returned. Default is 200 OK.
13 | /// Policy expressions aren't allowed. 14 | ///
15 | public int? StatusCode { get; init; } 16 | 17 | /// 18 | /// Value of Content-Type HTTP header to be returned. Default is application/json.
19 | /// Policy expressions aren't allowed. 20 | ///
21 | public string? ContentType { get; init; } 22 | 23 | /// 24 | /// Specifies which response, from an Examples entity defined in API Management, to return.
25 | /// When specified, the body of the example is used as the mocked response body.
26 | /// Policy expressions aren't allowed. 27 | ///
28 | public int? Index { get; init; } 29 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/ProxyConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the proxy policy.
8 | /// Specifies the proxy server URL, and optionally the username and password for authentication. 9 | ///
10 | public record ProxyConfig 11 | { 12 | /// 13 | /// The URL of the proxy server.
14 | /// Policy expressions are allowed. 15 | ///
16 | [ExpressionAllowed] 17 | public required string Url { get; init; } 18 | 19 | /// 20 | /// The username for proxy authentication.
21 | /// Policy expressions are allowed. 22 | ///
23 | [ExpressionAllowed] 24 | public string? Username { get; init; } 25 | 26 | /// 27 | /// The password for proxy authentication.
28 | /// Policy expressions are allowed. 29 | ///
30 | [ExpressionAllowed] 31 | public string? Password { get; init; } 32 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/ReturnResponseConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the return-response policy, specifying details of the response to return directly to the caller. 8 | /// 9 | public record ReturnResponseConfig 10 | { 11 | /// 12 | /// Name of the variable containing the response object to return. If specified, other properties are ignored. 13 | /// 14 | public string? ResponseVariableName { get; init; } 15 | 16 | /// 17 | /// Configuration specifying the HTTP status code and reason phrase to return. 18 | /// 19 | public StatusConfig? Status { get; init; } 20 | 21 | /// 22 | /// Collection of headers to include in the response. 23 | /// 24 | public HeaderConfig[]? Headers { get; init; } 25 | 26 | /// 27 | /// Configuration specifying the body content of the response. 28 | /// 29 | public BodyConfig? Body { get; init; } 30 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/SetBodyConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the set-body policy.
8 | /// Specifies template, xsi:nil, and parse date settings. 9 | ///
10 | public record SetBodyConfig 11 | { 12 | /// 13 | /// Optional. Specifies a template to use for the body content. 14 | /// 15 | public string? Template { get; init; } 16 | 17 | /// 18 | /// Optional. Specifies whether to include xsi:nil attribute in the XML output. 19 | /// 20 | public string? XsiNil { get; init; } 21 | 22 | /// 23 | /// Optional. Specifies whether to parse date values in the body content. 24 | /// 25 | public bool? ParseDate { get; init; } 26 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/StatusConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration to set the HTTP status code and reason to the specified value.
8 | /// Compiled to set-status policy. 9 | ///
10 | public record StatusConfig 11 | { 12 | /// 13 | /// The HTTP status code to return. Policy expressions are allowed. 14 | /// 15 | [ExpressionAllowed] 16 | public required int Code { get; init; } 17 | 18 | /// 19 | /// A description of the reason for returning the status code. Policy expressions are allowed. 20 | /// 21 | [ExpressionAllowed] 22 | public required string Reason { get; init; } 23 | }; -------------------------------------------------------------------------------- /src/Authoring/Configs/TraceConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the trace policy.
8 | /// Specifies the trace source, message, severity, and optional metadata. 9 | ///
10 | public record TraceConfig 11 | { 12 | /// 13 | /// The source of the trace message. 14 | /// 15 | public required string Source { get; init; } 16 | 17 | /// 18 | /// The trace message to be logged. Policy expressions are allowed. 19 | /// 20 | [ExpressionAllowed] 21 | public required string Message { get; init; } 22 | 23 | /// 24 | /// The severity of the trace message. Optional. 25 | /// 26 | public string? Severity { get; init; } 27 | 28 | /// 29 | /// Optional metadata to include with the trace message. 30 | /// 31 | public TraceMetadata[]? Metadata { get; init; } 32 | } 33 | 34 | /// 35 | /// Metadata for the trace policy. 36 | /// 37 | public record TraceMetadata 38 | { 39 | /// 40 | /// The name of the metadata item. 41 | /// 42 | public required string Name { get; init; } 43 | 44 | /// 45 | /// The value of the metadata item. 46 | /// 47 | public required string Value { get; init; } 48 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/ValidateOdataRequestConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the validate-odata-request policy. 8 | /// 9 | public record ValidateOdataRequestConfig 10 | { 11 | /// 12 | /// Specifies the name of the variable to store error details if validation fails. 13 | /// 14 | public string? ErrorVariableName { get; init; } 15 | 16 | /// 17 | /// Specifies the default OData version to use if not specified in the request. 18 | /// 19 | public string? DefaultOdataVersion { get; init; } 20 | 21 | /// 22 | /// Specifies the minimum OData version that the request must comply with. 23 | /// 24 | public string? MinOdataVersion { get; init; } 25 | 26 | /// 27 | /// Specifies the maximum OData version that the request can comply with. 28 | /// 29 | public string? MaxOdataVersion { get; init; } 30 | 31 | /// 32 | /// Specifies the maximum size of the request payload. 33 | /// 34 | public int? MaxSize { get; init; } 35 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/ValidateStatusCodeConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the validate-status-code policy.
8 | /// Specifies the validation rules for status codes, including actions for specified and unspecified status codes. 9 | ///
10 | public record ValidateStatusCodeConfig 11 | { 12 | /// 13 | /// Action to take for unspecified status codes. Possible values are "allow" or "deny". 14 | /// 15 | [ExpressionAllowed] 16 | public required string UnspecifiedStatusCodeAction { get; init; } 17 | 18 | /// 19 | /// Optional variable name to store validation errors. 20 | /// 21 | public string? ErrorVariableName { get; init; } 22 | 23 | /// 24 | /// List of status codes to validate. 25 | /// 26 | public ValidateStatusCode[]? StatusCodes { get; init; } 27 | } 28 | 29 | /// 30 | /// Represents a status code to validate. 31 | /// 32 | public record ValidateStatusCode 33 | { 34 | /// 35 | /// The status code to validate. 36 | /// 37 | public required uint Code { get; init; } 38 | 39 | /// 40 | /// Action to take for this status code. Possible values are "allow" or "deny". 41 | /// 42 | [ExpressionAllowed] 43 | public required string Action { get; init; } 44 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/XmlToJsonConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the xml-to-json policy. 8 | /// 9 | public record XmlToJsonConfig 10 | { 11 | /// 12 | /// Specifies the kind of transformation to apply. 13 | /// 14 | [ExpressionAllowed] 15 | public required string Kind { get; init; } 16 | 17 | /// 18 | /// Specifies how to apply the transformation. 19 | /// 20 | [ExpressionAllowed] 21 | public required string Apply { get; init; } 22 | 23 | /// 24 | /// Optional. Specifies whether to consider the Accept header when applying the transformation. 25 | /// 26 | [ExpressionAllowed] 27 | public bool? ConsiderAcceptHeader { get; init; } 28 | 29 | /// 30 | /// Optional. Specifies whether to always treat child elements as arrays. 31 | /// 32 | [ExpressionAllowed] 33 | public bool? AlwaysArrayChildElements { get; init; } 34 | } -------------------------------------------------------------------------------- /src/Authoring/Configs/XslTransformConfig.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | /// 7 | /// Configuration for the xsl-transform policy.
8 | /// Specifies the XSLT stylesheet and optional parameters. 9 | ///
10 | public record XslTransformConfig 11 | { 12 | /// 13 | /// The XSLT stylesheet to use for the transformation. Policy expressions are allowed. 14 | /// 15 | [ExpressionAllowed] 16 | public required string StyleSheet { get; init; } 17 | 18 | /// 19 | /// Optional parameters to pass to the XSLT stylesheet. 20 | /// 21 | public XslTransformParameter[]? Parameters { get; init; } 22 | } 23 | 24 | /// 25 | /// Represents a parameter to pass to the XSLT stylesheet. 26 | /// 27 | public record XslTransformParameter 28 | { 29 | /// 30 | /// The name of the parameter. 31 | /// 32 | public required string Name { get; init; } 33 | 34 | /// 35 | /// The value of the parameter. Policy expressions are allowed. 36 | /// 37 | [ExpressionAllowed] 38 | public required string Value { get; init; } 39 | } -------------------------------------------------------------------------------- /src/Authoring/DocumentScope.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | public enum DocumentScope 7 | { 8 | Any = 0, Global, Workspace, Product, Api, Operation 9 | } -------------------------------------------------------------------------------- /src/Authoring/Expression.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | 8 | public delegate T Expression(IExpressionContext context); -------------------------------------------------------------------------------- /src/Authoring/Expressions/Authorization.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | /// 7 | /// Represents an authorization object containing an access token and related claims. 8 | /// 9 | public class Authorization 10 | { 11 | /// 12 | /// Gets the access token used to authorize a backend HTTP request. 13 | /// 14 | public string AccessToken { get; } 15 | 16 | /// 17 | /// Gets a dictionary containing claims associated with the access token. 18 | /// 19 | public IReadOnlyDictionary Claims { get; } 20 | 21 | /// 22 | /// Initializes a new instance of the class. 23 | /// 24 | /// The access token used to authorize a backend HTTP request. 25 | /// A dictionary containing claims associated with the access token. 26 | public Authorization(string accessToken, IReadOnlyDictionary claims) 27 | { 28 | AccessToken = accessToken; 29 | Claims = claims; 30 | } 31 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/BasicAuthCredentials.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface BasicAuthCredentials 7 | { 8 | public string Username { get; } 9 | public string Password { get; } 10 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IApi.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IApi 7 | { 8 | string Id { get; } 9 | string Name { get; } 10 | string Path { get; } 11 | IEnumerable Protocols { get; } 12 | IUrl ServiceUrl { get; } 13 | ISubscriptionKeyParameterNames SubscriptionKeyParameterNames { get; } 14 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IContextApi.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IContextApi : IApi 7 | { 8 | bool IsCurrentRevision { get; } 9 | string Revision { get; } 10 | string Version { get; } 11 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IDeployment.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Security.Cryptography.X509Certificates; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 7 | 8 | public interface IDeployment 9 | { 10 | string GatewayId { get; } 11 | 12 | string Region { get; } 13 | 14 | string ServiceId { get; } 15 | 16 | string ServiceName { get; } 17 | 18 | IReadOnlyDictionary Certificates { get; } 19 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IExpressionContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IExpressionContext 7 | { 8 | IContextApi Api { get; } 9 | IDeployment Deployment { get; } 10 | TimeSpan Elapsed { get; } 11 | ILastError LastError { get; } 12 | IOperation Operation { get; } 13 | IProduct Product { get; } 14 | IRequest Request { get; } 15 | Guid RequestId { get; } 16 | IResponse Response { get; } 17 | ISubscription Subscription { get; } 18 | DateTime Timestamp { get; } 19 | bool Tracing { get; } 20 | IUser User { get; } 21 | IReadOnlyDictionary Variables { get; } 22 | Action Trace { get; } 23 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IGroup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IGroup 7 | { 8 | string Id { get; } 9 | string Name { get; } 10 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/ILastError.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface ILastError 7 | { 8 | string Source { get; } 9 | string Reason { get; } 10 | string Message { get; } 11 | string Scope { get; } 12 | string Section { get; } 13 | string Path { get; } 14 | string PolicyId { get; } 15 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IMessageBody.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IMessageBody 7 | { 8 | T As(bool preserveContent = false); 9 | IDictionary> AsFormUrlEncodedContent(bool preserveContent = false); 10 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IOperation.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IOperation 7 | { 8 | string Id { get; } 9 | string Method { get; } 10 | string Name { get; } 11 | string UrlTemplate { get; } 12 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IPrivateEndpointConnection.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IPrivateEndpointConnection 7 | { 8 | string Name { get; } 9 | string GroupId { get; } 10 | string MemberName { get; } 11 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IProduct.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IProduct 7 | { 8 | IEnumerable Apis { get; } 9 | bool ApprovalRequired { get; } 10 | IEnumerable Groups { get; } 11 | string Id { get; } 12 | string Name { get; } 13 | ProductState State { get; } 14 | int? SubscriptionLimit { get; } 15 | bool SubscriptionRequired { get; } 16 | } 17 | 18 | public enum ProductState { NotPublished, Published } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IRequest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Security.Cryptography.X509Certificates; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 7 | 8 | public interface IRequest 9 | { 10 | IMessageBody? Body { get; } 11 | 12 | X509Certificate2? Certificate { get; } 13 | 14 | IReadOnlyDictionary Headers { get; } 15 | 16 | string IpAddress { get; } 17 | 18 | IReadOnlyDictionary MatchedParameters { get; } 19 | 20 | string Method { get; } 21 | 22 | IUrl OriginalUrl { get; } 23 | 24 | IUrl Url { get; } 25 | 26 | IPrivateEndpointConnection? PrivateEndpointConnection { get; } 27 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IResponse.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IResponse 7 | { 8 | IMessageBody Body { get; } 9 | IReadOnlyDictionary Headers { get; } 10 | int StatusCode { get; } 11 | string StatusReason { get; } 12 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/ISubscription.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface ISubscription 7 | { 8 | DateTime CreatedDate { get; } 9 | DateTime? EndDate { get; } 10 | string Id { get; } 11 | string Key { get; } 12 | string Name { get; } 13 | string PrimaryKey { get; } 14 | string SecondaryKey { get; } 15 | DateTime? StartDate { get; } 16 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/ISubscriptionKeyParameterNames.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface ISubscriptionKeyParameterNames 7 | { 8 | string Header { get; } 9 | string Query { get; } 10 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IUrl.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IUrl 7 | { 8 | string Host { get; } 9 | string Path { get; } 10 | string Port { get; } 11 | IReadOnlyDictionary Query { get; } 12 | string QueryString { get; } 13 | string Scheme { get; } 14 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IUser.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IUser 7 | { 8 | string Email { get; } 9 | string FirstName { get; } 10 | IEnumerable Groups { get; } 11 | string Id { get; } 12 | IEnumerable Identities { get; } 13 | string LastName { get; } 14 | string Note { get; } 15 | DateTime RegistrationDate { get; } 16 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/IUserIdentity.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface IUserIdentity 7 | { 8 | string Id { get; } 9 | string Provider { get; } 10 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/Jwt.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | public interface Jwt 7 | { 8 | string Id { get; } 9 | public string Algorithm { get; } 10 | public string Issuer { get; } 11 | public string Subject { get; } 12 | public string Type { get; } 13 | public IEnumerable Audiences { get; } 14 | public IReadOnlyDictionary Claims { get; } 15 | public DateTime? ExpirationTime { get; } 16 | public DateTime? NotBefore { get; } 17 | public DateTime? IssuedAt { get; } 18 | } -------------------------------------------------------------------------------- /src/Authoring/Expressions/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Diagnostics.CodeAnalysis; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Implementations; 7 | 8 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 9 | 10 | public static class StringExtensions 11 | { 12 | public static BasicAuthCredentials? AsBasic(this string? value) 13 | => ImplementationContext.Default.GetService().Parse(value); 14 | 15 | public static bool TryParseBasic(this string? value, [MaybeNullWhen(false)] out BasicAuthCredentials credentials) 16 | => (credentials = value.AsBasic()) is not null; 17 | 18 | public static Jwt? AsJwt(this string? value) 19 | => ImplementationContext.Default.GetService().Parse(value); 20 | 21 | public static bool TryParseJwt(this string? value, [MaybeNullWhen(false)] out Jwt token) 22 | => (token = value.AsJwt()) is not null; 23 | } -------------------------------------------------------------------------------- /src/Authoring/IDocument.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | public interface IDocument 7 | { 8 | void Inbound(IInboundContext context) { } 9 | void Outbound(IOutboundContext context) { } 10 | void Backend(IBackendContext context) { } 11 | void OnError(IOnErrorContext context) { } 12 | } -------------------------------------------------------------------------------- /src/Authoring/IHaveExpressionContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | 8 | public interface IHaveExpressionContext 9 | { 10 | IExpressionContext ExpressionContext { get; } 11 | } -------------------------------------------------------------------------------- /src/Authoring/Implementations/IBasicAuthCredentialsParser.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Implementations; 7 | 8 | public interface IBasicAuthCredentialsParser 9 | { 10 | BasicAuthCredentials? Parse(string? value); 11 | } -------------------------------------------------------------------------------- /src/Authoring/Implementations/IJwtParser.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Implementations; 7 | 8 | public interface IJwtParser 9 | { 10 | Jwt? Parse(string? value); 11 | } -------------------------------------------------------------------------------- /src/Authoring/Implementations/IUrlContentEncoder.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Implementations; 5 | 6 | public interface IUrlContentEncoder 7 | { 8 | string? Encode(IDictionary>? dictionary); 9 | } -------------------------------------------------------------------------------- /src/Authoring/Implementations/ImplementationContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Runtime.CompilerServices; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Implementations; 7 | 8 | public class ImplementationContext 9 | { 10 | public static readonly ImplementationContext Default = new ImplementationContext(); 11 | 12 | private readonly Dictionary _services = new Dictionary(); 13 | 14 | public void SetService(T service) 15 | { 16 | _services[typeof(T)] = service ?? throw new NullReferenceException("service cannot be null"); 17 | } 18 | 19 | public T GetService([CallerMemberName] string memberName = "") 20 | { 21 | if (_services.TryGetValue(typeof(T), out var service)) 22 | { 23 | return (T)service; 24 | } 25 | 26 | var methodMessage = string.IsNullOrEmpty(memberName) 27 | ? "" 28 | : $" Please set {nameof(T)} before calling {memberName} method."; 29 | throw new NullReferenceException($"Implementation for {nameof(T)} is not set.{methodMessage}"); 30 | } 31 | } -------------------------------------------------------------------------------- /src/Compiling/Program.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.IoC; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.DependencyInjection; 8 | 9 | var config = new ConfigurationBuilder() 10 | .AddCommandLine(args) 11 | .Build(); 12 | var options = new CompilerOptions(config); 13 | 14 | await using ServiceProvider serviceProvider = new ServiceCollection() 15 | .SetupCompiler() 16 | .BuildServiceProvider(); 17 | 18 | if (options.IsProjectSource) 19 | { 20 | await Console.Out.WriteLineAsync("Project mode"); 21 | var compiler = serviceProvider.GetRequiredService(); 22 | var result = await compiler.Compile(options.ToProjectCompilerOptions()); 23 | return result.DocumentResults.Sum(r => r.Errors.Length); 24 | } 25 | else 26 | { 27 | await Console.Error.WriteLineAsync( 28 | "Directory mode is deprecated. Please use project mode by pointing source parameter to .csproj file or to folder with one .csproj file."); 29 | var compiler = serviceProvider.GetRequiredService(); 30 | var result = await compiler.Compile(options.ToDirectoryCompilerOptions()); 31 | return result.DocumentResults.Sum(r => r.Errors.Length); 32 | } -------------------------------------------------------------------------------- /src/Core/Compiling/DirectoryCompilerOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 7 | 8 | public record DirectoryCompilerOptions() 9 | { 10 | public required string SourceFolder { get; init; } 11 | public required string OutputFolder { get; init; } 12 | public required XmlWriterSettings XmlWriterSettings { get; init; } 13 | public required bool FormatCode { get; init; } 14 | public required string FileExtension { get; init; } 15 | } -------------------------------------------------------------------------------- /src/Core/Compiling/DirectoryCompilerResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 5 | 6 | public class DirectoryCompilerResult 7 | { 8 | public IList DocumentResults { get; } = new List(); 9 | } -------------------------------------------------------------------------------- /src/Core/Compiling/DocumentCompilationContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Collections.Immutable; 5 | using System.Xml.Linq; 6 | 7 | using Microsoft.CodeAnalysis; 8 | 9 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 10 | 11 | public class DocumentCompilationContext(Compilation compilation, SyntaxNode syntaxRoot, XElement currentElement) 12 | : IDocumentCompilationContext, IDocumentCompilationResult 13 | { 14 | public DocumentCompilationContext(IDocumentCompilationContext parent, XElement currentElement) 15 | : this(parent.Compilation, parent.SyntaxRoot, currentElement) 16 | { 17 | RootElement = parent.RootElement; 18 | Diagnostics = parent.Diagnostics; 19 | } 20 | 21 | public void AddPolicy(XNode element) => CurrentElement.Add(element); 22 | public void Report(Diagnostic diagnostic) => Diagnostics.Add(diagnostic); 23 | 24 | public Compilation Compilation { get; } = compilation; 25 | public SyntaxNode SyntaxRoot { get; } = syntaxRoot; 26 | public XElement RootElement { get; } = currentElement; 27 | public XElement CurrentElement { get; } = currentElement; 28 | public IList Diagnostics { get; } = new List(); 29 | 30 | public XElement Document => CurrentElement; 31 | public ImmutableArray Errors => [..Diagnostics]; 32 | } -------------------------------------------------------------------------------- /src/Core/Compiling/IDocumentCompilationContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.CodeAnalysis; 7 | 8 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 9 | 10 | public interface IDocumentCompilationContext 11 | { 12 | void AddPolicy(XNode element); 13 | void Report(Diagnostic diagnostic); 14 | 15 | Compilation Compilation { get; } 16 | SyntaxNode SyntaxRoot { get; } 17 | IList Diagnostics { get; } 18 | 19 | XElement RootElement { get; } 20 | XElement CurrentElement { get; } 21 | } -------------------------------------------------------------------------------- /src/Core/Compiling/IDocumentCompilationResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Collections.Immutable; 5 | using System.Xml.Linq; 6 | 7 | using Microsoft.CodeAnalysis; 8 | 9 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 10 | 11 | public interface IDocumentCompilationResult 12 | { 13 | XElement Document { get; } 14 | ImmutableArray Errors { get; } 15 | } -------------------------------------------------------------------------------- /src/Core/Compiling/IMethodPolicyHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.CodeAnalysis.CSharp.Syntax; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 7 | 8 | public interface IMethodPolicyHandler 9 | { 10 | string MethodName { get; } 11 | void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node); 12 | } -------------------------------------------------------------------------------- /src/Core/Compiling/IReturnValueMethodPolicyHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.CodeAnalysis.CSharp.Syntax; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 7 | 8 | public interface IReturnValueMethodPolicyHandler 9 | { 10 | string MethodName { get; } 11 | void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node, string variableName); 12 | } -------------------------------------------------------------------------------- /src/Core/Compiling/ISyntaxCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.CodeAnalysis; 5 | using Microsoft.CodeAnalysis.CSharp; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 8 | 9 | public interface ISyntaxCompiler 10 | { 11 | SyntaxKind Syntax { get; } 12 | 13 | void Compile(IDocumentCompilationContext context, SyntaxNode node); 14 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/AuthenticationManageIdentityReturnValueCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.CodeAnalysis.CSharp.Syntax; 8 | 9 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 10 | 11 | public class AuthenticationManageIdentityReturnValueCompiler : IReturnValueMethodPolicyHandler 12 | { 13 | public string MethodName => nameof(IInboundContext.AuthenticationManagedIdentity); 14 | 15 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node, string variableName) 16 | { 17 | var policy = new XElement("authentication-managed-identity"); 18 | var resource = node.ArgumentList.Arguments[0].Expression.ProcessParameter(context); 19 | policy.Add(new XAttribute("resource", resource)); 20 | policy.Add(new XAttribute("output-token-variable-name", variableName)); 21 | 22 | context.AddPolicy(policy); 23 | } 24 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/BaseCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.CodeAnalysis.CSharp.Syntax; 8 | 9 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 10 | 11 | public class BaseCompiler : IMethodPolicyHandler 12 | { 13 | public string MethodName => nameof(IInboundContext.Base); 14 | 15 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax _) 16 | { 17 | context.AddPolicy(new XElement("base")); 18 | } 19 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/CacheRemoveValueCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Diagnostics; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CSharp.Syntax; 10 | 11 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 12 | 13 | public class CacheRemoveValueCompiler : IMethodPolicyHandler 14 | { 15 | public string MethodName => nameof(IInboundContext.CacheRemoveValue); 16 | 17 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node) 18 | { 19 | if (!node.TryExtractingConfigParameter(context, "cache-remove-value", out var values)) 20 | { 21 | return; 22 | } 23 | 24 | var element = new XElement("cache-remove-value"); 25 | 26 | if (!element.AddAttribute(values, nameof(CacheRemoveValueConfig.Key), "key")) 27 | { 28 | context.Report(Diagnostic.Create( 29 | CompilationErrors.RequiredParameterNotDefined, 30 | node.GetLocation(), 31 | "cache-remove-value", 32 | nameof(CacheRemoveValueConfig.Key) 33 | )); 34 | return; 35 | } 36 | 37 | element.AddAttribute(values, nameof(CacheRemoveValueConfig.CachingType), "caching-type"); 38 | 39 | context.AddPolicy(element); 40 | } 41 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/CacheStoreCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Diagnostics; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CSharp.Syntax; 10 | 11 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 12 | 13 | public class CacheStoreCompiler : IMethodPolicyHandler 14 | { 15 | public string MethodName => nameof(IOutboundContext.CacheStore); 16 | 17 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node) 18 | { 19 | var arguments = node.ArgumentList.Arguments; 20 | if (arguments.Count is > 2 or < 1) 21 | { 22 | context.Report(Diagnostic.Create( 23 | CompilationErrors.ArgumentCountMissMatchForPolicy, 24 | node.ArgumentList.GetLocation(), 25 | "cache-store")); 26 | return; 27 | } 28 | 29 | var element = new XElement("cache-store"); 30 | 31 | element.Add(new XAttribute("duration", arguments[0].Expression.ProcessParameter(context))); 32 | 33 | if (arguments.Count == 2) 34 | { 35 | element.Add(new XAttribute("cache-response", arguments[1].Expression.ProcessParameter(context))); 36 | } 37 | 38 | context.AddPolicy(element); 39 | } 40 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/FindAndReplaceCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Diagnostics; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CSharp.Syntax; 10 | 11 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 12 | 13 | public class FindAndReplaceCompiler : IMethodPolicyHandler 14 | { 15 | public string MethodName => nameof(IInboundContext.FindAndReplace); 16 | 17 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node) 18 | { 19 | if (node.ArgumentList.Arguments.Count != 2) 20 | { 21 | context.Report(Diagnostic.Create( 22 | CompilationErrors.ArgumentCountMissMatchForPolicy, 23 | node.ArgumentList.GetLocation(), 24 | "find-and-replace")); 25 | return; 26 | } 27 | 28 | var from = node.ArgumentList.Arguments[0].Expression.ProcessParameter(context); 29 | var to = node.ArgumentList.Arguments[1].Expression.ProcessParameter(context); 30 | context.AddPolicy(new XElement("find-and-replace", new XAttribute("from", from), new XAttribute("to", to))); 31 | } 32 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/GenericCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 7 | 8 | public static class GenericCompiler 9 | { 10 | public static void HandleList( 11 | XElement element, 12 | IReadOnlyDictionary values, 13 | string key, 14 | string listName, 15 | string elementName) 16 | { 17 | if (!values.TryGetValue(key, out InitializerValue? listInitializer)) 18 | { 19 | return; 20 | } 21 | 22 | XElement listElement = new(listName); 23 | foreach (InitializerValue initializer in listInitializer.UnnamedValues ?? []) 24 | { 25 | listElement.Add(new XElement(elementName, initializer.Value!)); 26 | } 27 | 28 | element.Add(listElement); 29 | } 30 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/IncludeFragmentCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Diagnostics; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CSharp.Syntax; 10 | 11 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 12 | 13 | public class IncludeFragmentCompiler : IMethodPolicyHandler 14 | { 15 | public string MethodName => nameof(IInboundContext.IncludeFragment); 16 | 17 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node) 18 | { 19 | if (node.ArgumentList.Arguments.Count != 1) 20 | { 21 | context.Report(Diagnostic.Create( 22 | CompilationErrors.ArgumentCountMissMatchForPolicy, 23 | node.ArgumentList.GetLocation(), 24 | "include-fragment" 25 | )); 26 | return; 27 | } 28 | 29 | var fragmentId = node.ArgumentList.Arguments[0].Expression.ProcessParameter(context); 30 | context.AddPolicy(new XElement("include-fragment", new XAttribute("fragment-id", fragmentId))); 31 | } 32 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/JsonPCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Diagnostics; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CSharp.Syntax; 10 | 11 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 12 | 13 | public class JsonPCompiler : IMethodPolicyHandler 14 | { 15 | public string MethodName => nameof(IOutboundContext.JsonP); 16 | 17 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node) 18 | { 19 | var arguments = node.ArgumentList.Arguments; 20 | if (arguments.Count != 1) 21 | { 22 | context.Report(Diagnostic.Create( 23 | CompilationErrors.ArgumentCountMissMatchForPolicy, 24 | node.ArgumentList.GetLocation(), 25 | "jsonp")); 26 | return; 27 | } 28 | 29 | var value = node.ArgumentList.Arguments[0].Expression.ProcessParameter(context); 30 | context.AddPolicy(new XElement("jsonp", new XAttribute("callback-parameter-name", value))); 31 | } 32 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/RedirectContentUrlsCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.CodeAnalysis.CSharp.Syntax; 8 | 9 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 10 | 11 | public class RedirectContentUrlsCompiler : IMethodPolicyHandler 12 | { 13 | public string MethodName => nameof(IInboundContext.RedirectContentUrls); 14 | 15 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node) 16 | { 17 | context.AddPolicy(new XElement("redirect-content-urls")); 18 | } 19 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/SetMethodCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Diagnostics; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CSharp.Syntax; 10 | 11 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 12 | 13 | public class SetMethodCompiler : IMethodPolicyHandler 14 | { 15 | public string MethodName => nameof(IInboundContext.SetMethod); 16 | 17 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node) 18 | { 19 | if (node.ArgumentList.Arguments.Count != 1) 20 | { 21 | context.Report(Diagnostic.Create( 22 | CompilationErrors.ArgumentCountMissMatchForPolicy, 23 | node.ArgumentList.GetLocation(), 24 | "set-method")); 25 | return; 26 | } 27 | 28 | var value = node.ArgumentList.Arguments[0].Expression.ProcessParameter(context); 29 | context.AddPolicy(new XElement("set-method", value)); 30 | } 31 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/SetVariableCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Diagnostics; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CSharp.Syntax; 10 | 11 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 12 | 13 | public class SetVariableCompiler : IMethodPolicyHandler 14 | { 15 | public string MethodName => nameof(IInboundContext.SetVariable); 16 | 17 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node) 18 | { 19 | if (node.ArgumentList.Arguments.Count != 2) 20 | { 21 | context.Report(Diagnostic.Create( 22 | CompilationErrors.ArgumentCountMissMatchForPolicy, 23 | node.ArgumentList.GetLocation(), 24 | "set-variable")); 25 | return; 26 | } 27 | 28 | var name = node.ArgumentList.Arguments[0].Expression.ProcessParameter(context); 29 | var value = node.ArgumentList.Arguments[1].Expression.ProcessParameter(context); 30 | context.AddPolicy(new XElement("set-variable", new XAttribute("name", name), new XAttribute("value", value))); 31 | } 32 | } -------------------------------------------------------------------------------- /src/Core/Compiling/Policy/ValidateOdataRequestCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml.Linq; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.CodeAnalysis.CSharp.Syntax; 8 | 9 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy; 10 | 11 | public class ValidateOdataRequestCompiler : IMethodPolicyHandler 12 | { 13 | public string MethodName => nameof(IInboundContext.ValidateOdataRequest); 14 | 15 | public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node) 16 | { 17 | if (!node.TryExtractingConfigParameter(context, "validate-odata-request", 18 | out var values)) 19 | { 20 | return; 21 | } 22 | 23 | XElement element = new("validate-odata-request"); 24 | 25 | element.AddAttribute(values, nameof(ValidateOdataRequestConfig.ErrorVariableName), "error-variable-name"); 26 | element.AddAttribute(values, nameof(ValidateOdataRequestConfig.DefaultOdataVersion), "default-odata-version"); 27 | element.AddAttribute(values, nameof(ValidateOdataRequestConfig.MinOdataVersion), "min-odata-version"); 28 | element.AddAttribute(values, nameof(ValidateOdataRequestConfig.MaxOdataVersion), "max-odata-version"); 29 | element.AddAttribute(values, nameof(ValidateOdataRequestConfig.MaxSize), "max-size"); 30 | 31 | context.AddPolicy(element); 32 | } 33 | } -------------------------------------------------------------------------------- /src/Core/Compiling/ProjectCompilerOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Xml; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 7 | 8 | public class ProjectCompilerOptions 9 | { 10 | public required string ProjectPath { get; init; } 11 | public required string FileExtension { get; init; } 12 | public required string OutputFolder { get; init; } 13 | public required bool FormatCode { get; init; } 14 | public required XmlWriterSettings XmlWriterSettings { get; init; } 15 | } -------------------------------------------------------------------------------- /src/Core/Compiling/ProjectCompilerResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Collections.Immutable; 5 | 6 | using Microsoft.CodeAnalysis; 7 | 8 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 9 | 10 | public class ProjectCompilerResult 11 | { 12 | public ImmutableArray CompilerDiagnostics { get; set; } 13 | public IList DocumentResults { get; } = new List(); 14 | } -------------------------------------------------------------------------------- /src/Core/Compiling/TriviaRemoverRewriter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.CodeAnalysis; 5 | using Microsoft.CodeAnalysis.CSharp; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 8 | 9 | public class TriviaRemoverRewriter : CSharpSyntaxRewriter 10 | { 11 | public override SyntaxTriviaList VisitList(SyntaxTriviaList list) 12 | { 13 | return SyntaxFactory.TriviaList(); 14 | } 15 | } -------------------------------------------------------------------------------- /src/Core/Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | .net8 4 | enable 5 | enable 6 | 7 | false 8 | true 9 | Microsoft.Azure.ApiManagement.PolicyToolkit 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/Core/IO/PathUtils.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.IO; 5 | 6 | public static class PathUtils 7 | { 8 | public static bool IsNotInObjOrBinFolder(string path) 9 | { 10 | return path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) 11 | .All(d => !d.Equals("obj", StringComparison.OrdinalIgnoreCase) && 12 | !d.Equals("bin", StringComparison.OrdinalIgnoreCase)); 13 | } 14 | 15 | public static string PrepareOutputPath(string path, string extension) 16 | { 17 | var normalizedPath = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); 18 | var unrootedPath = UnrootPath(normalizedPath); 19 | return Path.HasExtension(path) ? path : Path.ChangeExtension(unrootedPath, extension); 20 | } 21 | 22 | public static string UnrootPath(string path) 23 | { 24 | return Path.IsPathRooted(path) ? Path.GetRelativePath(Path.GetPathRoot(path)!, path) : path; 25 | } 26 | } -------------------------------------------------------------------------------- /src/Core/IoC/LazilyResolutionModule.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Extensions.DependencyInjection; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.IoC; 7 | 8 | public static class LazilyResolutionModule 9 | { 10 | public static IServiceCollection AddLazyResolution(this IServiceCollection services) 11 | { 12 | return services.AddTransient(typeof(Lazy<>), typeof(LazyRequired<>)); 13 | } 14 | 15 | private class LazyRequired(IServiceProvider serviceProvider) : Lazy(serviceProvider.GetRequiredService) 16 | where T : notnull; 17 | } -------------------------------------------------------------------------------- /src/Templates/content/create-policy-document/PolicyDocument1.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 2 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 3 | 4 | namespace Company.PolicyProject1; 5 | 6 | [Document] 7 | public class PolicyDocument1 : IDocument 8 | { 9 | #if (Sections == Inbound) 10 | public void Inbound(IInboundContext context) 11 | { 12 | // Throttle, authorize, validate, cache, or transform the requests 13 | } 14 | 15 | #endif 16 | #if (Sections == Backend) 17 | public void Backend(IBackendContext context) 18 | { 19 | // Control if and how the requests are forwarded to services 20 | } 21 | 22 | #endif 23 | #if (Sections == Outbound) 24 | public void Outbound(IOutboundContext context) 25 | { 26 | // Customize the responses 27 | } 28 | 29 | #endif 30 | #if (Sections == OnError) 31 | public void OnError(IOnErrorContext context) 32 | { 33 | // Handle exceptions and customize error responses 34 | } 35 | #endif 36 | } -------------------------------------------------------------------------------- /src/Templates/content/create-solution/.config/dotnet-tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "isRoot": true, 4 | "tools": { 5 | "Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling": { 6 | "version": "0.0.1", 7 | "commands": [ 8 | "azure-apim-policy-compiler" 9 | ] 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/Templates/content/create-solution/Project.Solution.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio Version 17 3 | VisualStudioVersion = 17.0.31903.59 4 | MinimumVisualStudioVersion = 10.0.40219.1 5 | Global 6 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 7 | Debug|Any CPU = Debug|Any CPU 8 | Release|Any CPU = Release|Any CPU 9 | EndGlobalSection 10 | GlobalSection(SolutionProperties) = preSolution 11 | HideSolutionNode = FALSE 12 | EndGlobalSection 13 | EndGlobal -------------------------------------------------------------------------------- /src/Templates/content/create-solution/src/Project.Source.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | .net8 4 | latest 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/Templates/content/create-solution/test/Project.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net8.0 4 | latest 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/Testing/Document/MockAppendQueryParameterProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockAppendQueryParameterProvider 10 | { 11 | public static Setup AppendQueryParameter(this MockPoliciesProvider mock) => 12 | AppendQueryParameter(mock, (_, _, _) => true); 13 | 14 | public static Setup AppendQueryParameter( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly AppendQueryParameterHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | AppendQueryParameterHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockBaseProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 7 | 8 | public static class MockBaseProvider 9 | { 10 | public static Setup Base(this MockPoliciesProvider mock) where T : class => Base(mock, _ => true); 11 | 12 | public static Setup Base( 13 | this MockPoliciesProvider mock, 14 | Func predicate 15 | ) where T : class 16 | { 17 | var handler = mock.SectionContextProxy.GetHandler(); 18 | return new Setup(predicate, handler); 19 | } 20 | 21 | public class Setup 22 | { 23 | private readonly Func _predicate; 24 | private readonly BaseHandler _handler; 25 | 26 | internal Setup( 27 | Func predicate, 28 | BaseHandler handler) 29 | { 30 | _predicate = predicate; 31 | _handler = handler; 32 | } 33 | 34 | public void WithCallback(Action callback) => 35 | _handler.CallbackHooks.Add((_predicate, callback).ToTuple()); 36 | } 37 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockCacheLookupProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockCacheLookupProvider 10 | { 11 | public static Setup CacheLookup( 12 | this MockPoliciesProvider mock) => CacheLookup(mock, (_, _) => true); 13 | 14 | public static Setup CacheLookup( 15 | this MockPoliciesProvider mock, 16 | Func predicate) 17 | { 18 | var handler = mock.SectionContextProxy.GetHandler(); 19 | return new Setup(predicate, handler); 20 | } 21 | 22 | public class Setup 23 | { 24 | private readonly Func _predicate; 25 | private readonly CacheLookupHandler _handler; 26 | 27 | internal Setup( 28 | Func predicate, 29 | CacheLookupHandler handler) 30 | { 31 | _predicate = predicate; 32 | _handler = handler; 33 | } 34 | 35 | public void WithCallback(Action callback) => 36 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 37 | } 38 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockCacheStoreProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockCacheStoreProvider 10 | { 11 | public static Setup CacheStore(this MockPoliciesProvider mock) => 12 | CacheStore(mock, (_, _, _) => true); 13 | 14 | public static Setup CacheStore( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly CacheStoreHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | CacheStoreHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackHooks.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockCacheStoreValueProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockCacheStoreValueProvider 10 | { 11 | public static Setup CacheStoreValue(this MockPoliciesProvider mock) where T : class => 12 | CacheStoreValue(mock, (_, _) => true); 13 | 14 | public static Setup CacheStoreValue( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) where T : class 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly CacheStoreValueHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | CacheStoreValueHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockCorsProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockCorsProvider 10 | { 11 | public static Setup Cors(this MockPoliciesProvider mock) => 12 | Cors(mock, (_, _) => true); 13 | 14 | public static Setup Cors( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly CorsHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | CorsHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockEmitMetricProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockEmitMetricProvider 10 | { 11 | public static Setup EmitMetric(this MockPoliciesProvider mock) where T : class => 12 | EmitMetric(mock, (_, _) => true); 13 | 14 | public static Setup EmitMetric( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) where T : class 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly EmitMetricHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | EmitMetricHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockForwardRequestProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockForwardRequestProvider 10 | { 11 | public static Setup ForwardRequest(this MockPoliciesProvider mock) => 12 | ForwardRequest(mock, (_, _) => true); 13 | 14 | public static Setup ForwardRequest( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) where T : class 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly ForwardRequestHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | ForwardRequestHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockInlineProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 7 | 8 | public static class MockInlineProvider 9 | { 10 | public static Setup Inline(this MockPoliciesProvider mock) where T : class => 11 | Inline(mock, (_, _) => true); 12 | 13 | public static Setup Inline( 14 | this MockPoliciesProvider mock, 15 | Func predicate 16 | ) where T : class 17 | { 18 | var handler = mock.SectionContextProxy.GetHandler(); 19 | return new Setup(predicate, handler); 20 | } 21 | 22 | public class Setup 23 | { 24 | private readonly Func _predicate; 25 | private readonly InlinePolicyHandler _handler; 26 | 27 | internal Setup( 28 | Func predicate, 29 | InlinePolicyHandler handler) 30 | { 31 | _predicate = predicate; 32 | _handler = handler; 33 | } 34 | 35 | public void WithCallback(Action callback) => 36 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 37 | } 38 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockJsonPProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockJsonPProvider 10 | { 11 | public static Setup JsonP(this MockPoliciesProvider mock) => 12 | JsonP(mock, (_, _) => true); 13 | 14 | public static Setup JsonP( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly JsonPHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | JsonPHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockJsonToXmlProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockJsonToXmlProvider 10 | { 11 | public static Setup JsonToXml(this MockPoliciesProvider mock) where T : class => 12 | JsonToXml(mock, (_, _) => true); 13 | 14 | public static Setup JsonToXml( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) where T : class 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly JsonToXmlHandle _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | JsonToXmlHandle handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockLlmEmitTokenMetricProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockLlmEmitTokenMetricProvider 10 | { 11 | public static Setup LlmEmitTokenMetric( 12 | this MockPoliciesProvider mock) => LlmEmitTokenMetric(mock, (_, _) => true); 13 | 14 | public static Setup LlmEmitTokenMetric( 15 | this MockPoliciesProvider mock, 16 | Func predicate) 17 | { 18 | var handler = mock.SectionContextProxy.GetHandler(); 19 | return new Setup(predicate, handler); 20 | } 21 | 22 | public class Setup 23 | { 24 | private readonly Func _predicate; 25 | private readonly LlmEmitTokenMetricHandler _handler; 26 | 27 | internal Setup( 28 | Func predicate, 29 | LlmEmitTokenMetricHandler handler) 30 | { 31 | _predicate = predicate; 32 | _handler = handler; 33 | } 34 | 35 | public void WithCallback(Action callback) => 36 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 37 | } 38 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockLlmSemanticCacheStoreProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockLlmSemanticCacheStoreProvider 10 | { 11 | public static Setup LlmSemanticCacheStore( 12 | this MockPoliciesProvider mock) => LlmSemanticCacheStore(mock, (_, _) => true); 13 | 14 | public static Setup LlmSemanticCacheStore( 15 | this MockPoliciesProvider mock, 16 | Func predicate) 17 | { 18 | var handler = mock.SectionContextProxy.GetHandler(); 19 | return new Setup(predicate, handler); 20 | } 21 | 22 | public class Setup 23 | { 24 | private readonly Func _predicate; 25 | private readonly LlmSemanticCacheStoreHandler _handler; 26 | 27 | internal Setup( 28 | Func predicate, 29 | LlmSemanticCacheStoreHandler handler) 30 | { 31 | _predicate = predicate; 32 | _handler = handler; 33 | } 34 | 35 | public void WithCallback(Action callback) => 36 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 37 | } 38 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockLogToEventHubProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockLogToEventHubProvider 10 | { 11 | public static Setup LogToEventHub(this MockPoliciesProvider mock) where T : class => 12 | LogToEventHub(mock, (_, _) => true); 13 | 14 | public static Setup LogToEventHub( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) where T : class 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly LogToEventHubHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | LogToEventHubHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockMockResponseProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockMockResponseProvider 10 | { 11 | public static Setup MockResponse(this MockPoliciesProvider mock) where T : class => 12 | MockResponse(mock, (_, _) => true); 13 | 14 | public static Setup MockResponse( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) where T : class 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly MockResponseHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | MockResponseHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockPoliciesProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 7 | 8 | public class MockPoliciesProvider where TSection : class 9 | { 10 | internal readonly SectionContextProxy SectionContextProxy; 11 | 12 | internal MockPoliciesProvider(SectionContextProxy proxy) => this.SectionContextProxy = proxy; 13 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockQuotaProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockQuotaProvider 10 | { 11 | public static Setup Quota(this MockPoliciesProvider mock) => 12 | Quota(mock, (_, _) => true); 13 | 14 | public static Setup Quota( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly QuotaHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | QuotaHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockRateLimitByKeyProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockRateLimitByKeyProvider 10 | { 11 | public static Setup RateLimitByKey(this MockPoliciesProvider mock) => 12 | RateLimitByKey(mock, (_, _) => true); 13 | 14 | public static Setup RateLimitByKey( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly RateLimitByKeyHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | RateLimitByKeyHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockRateLimitProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockRateLimitProvider 10 | { 11 | public static Setup RateLimit(this MockPoliciesProvider mock) => 12 | RateLimit(mock, (_, _) => true); 13 | 14 | public static Setup RateLimit( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly RateLimitHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | RateLimitHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockRemoveQueryParameterProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockRemoveQueryParameterProvider 10 | { 11 | public static Setup RemoveQueryParameter(this MockPoliciesProvider mock) => 12 | RemoveQueryParameter(mock, (_, _) => true); 13 | 14 | public static Setup RemoveQueryParameter( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly RemoveQueryParameterHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | RemoveQueryParameterHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockReturnResponseProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockReturnResponseProvider 10 | { 11 | public static Setup ReturnResponse(this MockPoliciesProvider mock) => 12 | ReturnResponse(mock, (_, _) => true); 13 | 14 | public static Setup ReturnResponse( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) where T : class 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly ReturnResponseHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | ReturnResponseHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackHooks.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockRewriteUriProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockRewriteUriProvider 10 | { 11 | public static Setup RewriteUri(this MockPoliciesProvider mock) => 12 | RewriteUri(mock, (_, _, _) => true); 13 | 14 | public static Setup RewriteUri( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly RewriteUriHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | RewriteUriHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockSendRequestProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockSendRequestProvider 10 | { 11 | public static Setup SendRequest(this MockPoliciesProvider mock) where T : class => 12 | SendRequest(mock, (_, _) => true); 13 | 14 | public static Setup SendRequest( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) where T : class 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly SendRequestHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | SendRequestHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockSetQueryParameterProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockSetQueryParameterProvider 10 | { 11 | public static Setup SetQueryParameter(this MockPoliciesProvider mock) => 12 | SetQueryParameter(mock, (_, _, _) => true); 13 | 14 | public static Setup SetQueryParameter( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly SetQueryParameterHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | SetQueryParameterHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockSetVariableProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 7 | 8 | public static class MockSetVariableProvider 9 | { 10 | public static Setup SetVariable(this MockPoliciesProvider mock) where T : class => 11 | SetVariable(mock, (_, _, _) => true); 12 | 13 | public static Setup SetVariable( 14 | this MockPoliciesProvider mock, 15 | Func predicate 16 | ) where T : class 17 | { 18 | var handler = mock.SectionContextProxy.GetHandler(); 19 | return new Setup(predicate, handler); 20 | } 21 | 22 | public class Setup 23 | { 24 | private readonly Func _predicate; 25 | private readonly SetVariableHandler _handler; 26 | 27 | internal Setup( 28 | Func predicate, 29 | SetVariableHandler handler) 30 | { 31 | _predicate = predicate; 32 | _handler = handler; 33 | } 34 | 35 | public void WithCallback(Action callback) => 36 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 37 | } 38 | } -------------------------------------------------------------------------------- /src/Testing/Document/MockValidateJwtProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class MockValidateJwtProvider 10 | { 11 | public static Setup ValidateJwt(this MockPoliciesProvider mock) => 12 | ValidateJwt(mock, (_, _) => true); 13 | 14 | public static Setup ValidateJwt( 15 | this MockPoliciesProvider mock, 16 | Func predicate 17 | ) 18 | { 19 | var handler = mock.SectionContextProxy.GetHandler(); 20 | return new Setup(predicate, handler); 21 | } 22 | 23 | public class Setup 24 | { 25 | private readonly Func _predicate; 26 | private readonly ValidateJwtHandler _handler; 27 | 28 | internal Setup( 29 | Func predicate, 30 | ValidateJwtHandler handler) 31 | { 32 | _predicate = predicate; 33 | _handler = handler; 34 | } 35 | 36 | public void WithCallback(Action callback) => 37 | _handler.CallbackSetup.Add((_predicate, callback).ToTuple()); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Document/TestDocumentExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 8 | 9 | public static class TestDocumentExtensions 10 | { 11 | public static MockPoliciesProvider SetupInbound(this TestDocument document) => 12 | new(document.Context.InboundProxy); 13 | 14 | public static MockPoliciesProvider SetupBackend(this TestDocument document) => 15 | new(document.Context.BackendProxy); 16 | 17 | public static MockPoliciesProvider SetupOutbound(this TestDocument document) => 18 | new(document.Context.OutboundProxy); 19 | 20 | public static MockPoliciesProvider SetupOnError(this TestDocument document) => 21 | new(document.Context.OnErrorProxy); 22 | 23 | public static CertificateStore SetupCertificateStore(this TestDocument document) => 24 | document.Context.CertificateStore; 25 | 26 | public static CacheStore SetupCacheStore(this TestDocument document) => 27 | document.Context.CacheStore; 28 | 29 | public static ResponseExampleStore SetupResponseExampleStore(this TestDocument document) => 30 | document.Context.ResponseExampleStore; 31 | 32 | public static LoggerStore SetupLoggerStore(this TestDocument document) => 33 | document.Context.LoggerStore; 34 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Data/CacheValue.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 5 | 6 | public record CacheValue(object Value, uint Duration = 0); -------------------------------------------------------------------------------- /src/Testing/Emulator/Data/CertificateStore.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography.X509Certificates; 2 | 3 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 4 | 5 | public class CertificateStore 6 | { 7 | internal readonly Dictionary ById = new(); 8 | internal readonly Dictionary ByThumbprint = new(); 9 | 10 | public CertificateStore WithCertificateById(string id, X509Certificate2 certificate) 11 | { 12 | ById.Add(id, certificate); 13 | return this; 14 | } 15 | 16 | public CertificateStore WithCertificateByThumbprint(string thumbprint, X509Certificate2 certificate) 17 | { 18 | ByThumbprint.Add(thumbprint, certificate); 19 | return this; 20 | } 21 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Data/EventHubEvent.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 5 | 6 | public record EventHubEvent(string Value, string? PartitionId = null, string? PartitionKey = null); -------------------------------------------------------------------------------- /src/Testing/Emulator/Data/Logger.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Collections.Immutable; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 7 | 8 | public class Logger(string loggerId) 9 | { 10 | public string LoggerId => loggerId; 11 | internal readonly IList EventsInternal = new List(); 12 | public ImmutableArray Events => EventsInternal.ToImmutableArray(); 13 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Data/LoggerStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Diagnostics.CodeAnalysis; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 7 | 8 | public class LoggerStore 9 | { 10 | private readonly Dictionary _loggers = new(); 11 | 12 | public Logger Add(string loggerId) 13 | { 14 | var logger = new Logger(loggerId); 15 | this.Add(logger); 16 | return logger; 17 | } 18 | 19 | public void Add(Logger logger) 20 | { 21 | if (!_loggers.TryAdd(logger.LoggerId, logger)) 22 | { 23 | throw new Exception($"Logger with id {logger.LoggerId} already exists."); 24 | } 25 | } 26 | 27 | public bool TryGet(string loggerId, [NotNullWhen(true)] out Logger logger) => 28 | _loggers.TryGetValue(loggerId, out logger!); 29 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Data/ResponseExample.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 5 | 6 | public record ResponseExample(int ResponseCode, string Sample, string? ContentType = null); -------------------------------------------------------------------------------- /src/Testing/Emulator/Data/ResponseExampleStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 5 | 6 | public class ResponseExampleStore 7 | { 8 | private readonly Dictionary>> _responseExamples = new(); 9 | 10 | public ResponseExample[] GetOrDefault(string apiId, string operationId) 11 | { 12 | if (this._responseExamples.TryGetValue(apiId, out var operations) && 13 | operations.TryGetValue(operationId, out var operationExamples)) 14 | { 15 | return operationExamples.ToArray(); 16 | } 17 | 18 | return []; 19 | } 20 | 21 | public void Add(GatewayContext context, params ResponseExample[] examples) => 22 | Add(context.Api.Id, context.Operation.Id, examples); 23 | 24 | public void Add(string apiId, string operationId, params ResponseExample[] examples) 25 | { 26 | if (!this._responseExamples.TryGetValue(apiId, out var operations)) 27 | { 28 | operations = new Dictionary>(); 29 | this._responseExamples[apiId] = operations; 30 | } 31 | 32 | if (!operations.TryGetValue(operationId, out var operationExamples)) 33 | { 34 | operationExamples = []; 35 | operations[operationId] = operationExamples; 36 | } 37 | 38 | operationExamples.AddRange(examples); 39 | } 40 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/FinishSectionProcessingException.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator; 5 | 6 | public class FinishSectionProcessingException : Exception 7 | { 8 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/IPolicyHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator; 5 | 6 | internal interface IPolicyHandler 7 | { 8 | public string PolicyName { get; } 9 | object? Handle(GatewayContext context, object?[]? args); 10 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/AppendHeaderHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext)), Section(nameof(IBackendContext))] 9 | internal class AppendHeaderRequestHandler : AppendHeaderHandler 10 | { 11 | protected override Dictionary GetHeaders(GatewayContext context) => context.Request.Headers; 12 | } 13 | 14 | [Section(nameof(IOutboundContext)), Section(nameof(IOnErrorContext))] 15 | internal class AppendHeaderResponseHandler : AppendHeaderHandler 16 | { 17 | protected override Dictionary GetHeaders(GatewayContext context) => context.Response.Headers; 18 | } 19 | 20 | internal abstract class AppendHeaderHandler : PolicyHandler 21 | { 22 | public override string PolicyName => nameof(IInboundContext.AppendHeader); 23 | 24 | protected override void Handle(GatewayContext context, string name, string[] values) 25 | { 26 | var headers = GetHeaders(context); 27 | if (headers.TryGetValue(name, out var currentValues)) 28 | { 29 | values = currentValues.Concat(values).ToArray(); 30 | } 31 | 32 | headers[name] = values; 33 | } 34 | 35 | protected abstract Dictionary GetHeaders(GatewayContext context); 36 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/AppendQueryParameterHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class AppendQueryParameterHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.AppendQueryParameter); 17 | 18 | protected override void Handle(GatewayContext context, string name, string[] values) 19 | { 20 | var query = context.Request.Url.Query; 21 | if (query.TryGetValue(name, out var currentValues)) 22 | { 23 | values = currentValues.Concat(values).ToArray(); 24 | } 25 | 26 | query[name] = values; 27 | } 28 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/AuthenticationBasicHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | 8 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 9 | 10 | [Section(nameof(IInboundContext))] 11 | internal class AuthenticationBasicHandler : PolicyHandler 12 | { 13 | public override string PolicyName => nameof(IInboundContext.AuthenticationBasic); 14 | 15 | protected override void Handle(GatewayContext context, string username, string password) 16 | { 17 | var authHeader = $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"))}"; 18 | context.Request.Headers["Authorization"] = [authHeader]; 19 | } 20 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/AzureOpenAiEmitTokenMetricHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class AzureOpenAiEmitTokenMetricHandler : LlmEmitTokenMetricHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.AzureOpenAiEmitTokenMetric); 12 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/AzureOpenAiSemanticCacheLookupHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class AzureOpenAiSemanticCacheLookupHandler : LlmSemanticCacheLookupHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.AzureOpenAiSemanticCacheLookup); 12 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/AzureOpenAiSemanticCacheStoreHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IOutboundContext))] 9 | internal class AzureOpenAiSemanticCacheStoreHandler : LlmSemanticCacheStoreHandler 10 | { 11 | public override string PolicyName => nameof(IOutboundContext.AzureOpenAiSemanticCacheStore); 12 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/BaseHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class BaseHandler : IPolicyHandler 15 | { 16 | public List, 18 | Action 19 | >> CallbackHooks { get; } = new(); 20 | 21 | public string PolicyName => nameof(IInboundContext.Base); 22 | 23 | public object? Handle(GatewayContext context, object?[]? args) 24 | { 25 | var callbackHook = CallbackHooks.Find(hook => hook.Item1(context)); 26 | callbackHook?.Item2(context); 27 | return null; 28 | } 29 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/CacheLookupHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class CacheLookupHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.CacheLookup); 12 | 13 | protected override void Handle(GatewayContext context, CacheLookupConfig config) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/CacheRemoveValueHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class CacheRemoveValueHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.CacheRemoveValue); 17 | 18 | protected override void Handle(GatewayContext context, CacheRemoveValueConfig config) 19 | { 20 | var store = context.CacheStore.GetCache(config.CachingType ?? "prefer-external"); 21 | store?.Remove(config.Key); 22 | } 23 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/CacheStoreValueHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 8 | 9 | [ 10 | Section(nameof(IInboundContext)), 11 | Section(nameof(IBackendContext)), 12 | Section(nameof(IOutboundContext)), 13 | Section(nameof(IOnErrorContext)) 14 | ] 15 | internal class CacheStoreValueHandler : PolicyHandler 16 | { 17 | public override string PolicyName => nameof(IInboundContext.CacheStoreValue); 18 | 19 | protected override void Handle(GatewayContext context, CacheStoreValueConfig config) 20 | { 21 | var store = context.CacheStore.GetCache(config.CachingType ?? "prefer-external"); 22 | 23 | if (store is not null) 24 | { 25 | store[config.Key] = new CacheValue(config.Value) { Duration = config.Duration }; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/CorsHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class CorsHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.Cors); 12 | 13 | protected override void Handle(GatewayContext context, CorsConfig config) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/EmitMetricHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IOutboundContext)), 11 | Section(nameof(IOnErrorContext)) 12 | ] 13 | internal class EmitMetricHandler : PolicyHandler 14 | { 15 | public override string PolicyName => nameof(IInboundContext.EmitMetric); 16 | 17 | protected override void Handle(GatewayContext context, EmitMetricConfig config) 18 | { 19 | throw new NotImplementedException(); 20 | } 21 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/ExpressionContextHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class ExpressionContextHandler : IPolicyHandler 15 | { 16 | public string PolicyName => "get_ExpressionContext"; 17 | public object? Handle(GatewayContext context, object?[]? args) => context; 18 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/ForwardRequestHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IBackendContext))] 9 | internal class ForwardRequestHandler : PolicyHandlerOptionalParam 10 | { 11 | public override string PolicyName => nameof(IBackendContext.ForwardRequest); 12 | 13 | protected override void Handle(GatewayContext context, ForwardRequestConfig? config) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/InlinePolicyHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class InlinePolicyHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.InlinePolicy); 17 | 18 | protected override void Handle(GatewayContext context, string config) 19 | { 20 | throw new NotImplementedException(); 21 | } 22 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/JsonPHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IOutboundContext))] 9 | internal class JsonPHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IOutboundContext.JsonP); 12 | 13 | protected override void Handle(GatewayContext context, string config) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/JsonToXmlHandle.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class JsonToXmlHandle : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.JsonToXml); 17 | 18 | protected override void Handle(GatewayContext context, JsonToXmlConfig config) 19 | { 20 | throw new NotImplementedException(); 21 | } 22 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/LlmEmitTokenMetricHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class LlmEmitTokenMetricHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.LlmEmitTokenMetric); 12 | 13 | protected override void Handle(GatewayContext context, EmitTokenMetricConfig config) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/LlmSemanticCacheLookupHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class LlmSemanticCacheLookupHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.LlmSemanticCacheLookup); 12 | 13 | protected override void Handle(GatewayContext context, SemanticCacheLookupConfig config) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/LlmSemanticCacheStoreHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IOutboundContext))] 9 | internal class LlmSemanticCacheStoreHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IOutboundContext.LlmSemanticCacheStore); 12 | 13 | protected override void Handle(GatewayContext context, uint duration) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/LogToEventHubHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 8 | 9 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 10 | 11 | [ 12 | Section(nameof(IInboundContext)), 13 | Section(nameof(IBackendContext)), 14 | Section(nameof(IOutboundContext)), 15 | Section(nameof(IOnErrorContext)) 16 | ] 17 | internal class LogToEventHubHandler : PolicyHandler 18 | { 19 | const int MaxMessageBytes = 204000; 20 | 21 | public override string PolicyName => nameof(IInboundContext.LogToEventHub); 22 | 23 | protected override void Handle(GatewayContext context, LogToEventHubConfig config) 24 | { 25 | if (!context.LoggerStore.TryGet(config.LoggerId, out var logger)) 26 | { 27 | return; 28 | } 29 | 30 | var content = Encoding.UTF8.GetBytes(config.Value); 31 | if (content.Length > MaxMessageBytes) 32 | { 33 | var copyBytes = content; 34 | content = new byte[MaxMessageBytes]; 35 | Array.Copy(copyBytes, content, MaxMessageBytes); 36 | } 37 | 38 | var hubEvent = new EventHubEvent(Encoding.UTF8.GetString(content), config.PartitionId, config.PartitionKey); 39 | logger.EventsInternal.Add(hubEvent); 40 | } 41 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/QuotaHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class QuotaHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.Quota); 12 | 13 | protected override void Handle(GatewayContext context, QuotaConfig config) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/RateLimitByKeyHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class RateLimitByKeyHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.RateLimitByKey); 12 | 13 | protected override void Handle(GatewayContext context, RateLimitByKeyConfig config) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/RateLimitHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class RateLimitHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.RateLimit); 12 | 13 | protected override void Handle(GatewayContext context, RateLimitConfig config) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/RemoveHeaderHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext)), Section(nameof(IBackendContext))] 9 | internal class RemoveHeaderRequestHandler : RemoveHeaderHandler 10 | { 11 | protected override Dictionary GetHeaders(GatewayContext context) 12 | => context.Request.Headers; 13 | } 14 | 15 | [Section(nameof(IOutboundContext)), Section(nameof(IOnErrorContext))] 16 | internal class RemoveHeaderResponseHandler : RemoveHeaderHandler 17 | { 18 | protected override Dictionary GetHeaders(GatewayContext context) 19 | => context.Response.Headers; 20 | } 21 | 22 | internal abstract class RemoveHeaderHandler : PolicyHandler 23 | { 24 | public override string PolicyName => nameof(IInboundContext.RemoveHeader); 25 | 26 | protected override void Handle(GatewayContext context, string name) => GetHeaders(context).Remove(name); 27 | 28 | protected abstract Dictionary GetHeaders(GatewayContext context); 29 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/RemoveQueryParameterHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class RemoveQueryParameterHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.RemoveQueryParameter); 17 | protected override void Handle(GatewayContext context, string name) => context.Request.Url.Query.Remove(name); 18 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/RewriteUriHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class RewriteUriHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.RewriteUri); 12 | 13 | protected override void Handle(GatewayContext context, string tempalte, bool copyUnmatchedParams) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/SendRequestHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class SendRequestHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.SendRequest); 17 | 18 | protected override void Handle(GatewayContext context, SendRequestConfig config) 19 | { 20 | throw new NotImplementedException(); 21 | } 22 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/SetBackendServiceHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class SetBackendServiceHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.SetBackendService); 17 | 18 | protected override void Handle(GatewayContext context, SetBackendServiceConfig config) 19 | { 20 | throw new NotImplementedException(); 21 | } 22 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/SetHeaderHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext)), Section(nameof(IBackendContext))] 9 | internal class SetHeaderRequestHandler : SetHeaderHandler 10 | { 11 | protected override Dictionary GetHeaders(GatewayContext context) => context.Request.Headers; 12 | } 13 | 14 | [Section(nameof(IOutboundContext)), Section(nameof(IOnErrorContext))] 15 | internal class SetHeaderResponseHandler : SetHeaderHandler 16 | { 17 | protected override Dictionary GetHeaders(GatewayContext context) => context.Response.Headers; 18 | } 19 | 20 | internal abstract class SetHeaderHandler : PolicyHandler 21 | { 22 | public override string PolicyName => nameof(IInboundContext.SetHeader); 23 | 24 | protected override void Handle(GatewayContext context, string name, string[] values) => 25 | GetHeaders(context)[name] = values; 26 | 27 | protected abstract Dictionary GetHeaders(GatewayContext context); 28 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/SetHeaderIfNotExistHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext)), Section(nameof(IBackendContext))] 9 | internal class SetHeaderIfNotExistRequestHandler : SetHeaderIfNotExistHandler 10 | { 11 | protected override Dictionary GetHeaders(GatewayContext context) => context.Request.Headers; 12 | } 13 | 14 | [Section(nameof(IOutboundContext)), Section(nameof(IOnErrorContext))] 15 | internal class SetHeaderIfNotExistResponseHandler : SetHeaderIfNotExistHandler 16 | { 17 | protected override Dictionary GetHeaders(GatewayContext context) => context.Response.Headers; 18 | } 19 | 20 | internal abstract class SetHeaderIfNotExistHandler : PolicyHandler 21 | { 22 | public override string PolicyName => nameof(IInboundContext.SetHeaderIfNotExist); 23 | 24 | protected override void Handle(GatewayContext context, string name, string[] values) => 25 | GetHeaders(context).TryAdd(name, values); 26 | 27 | protected abstract Dictionary GetHeaders(GatewayContext context); 28 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/SetMethodHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class SetMethodHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.SetMethod); 17 | protected override void Handle(GatewayContext context, string method) => context.Request.Method = method; 18 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/SetQueryParameterHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class SetQueryParameterHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.SetQueryParameter); 17 | 18 | protected override void Handle(GatewayContext context, string name, string[] value) => 19 | context.Request.Url.Query[name] = value; 20 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/SetQueryParameterIfNotExistHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class SetQueryParameterIfNotExistHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.SetQueryParameterIfNotExist); 17 | 18 | protected override void Handle(GatewayContext context, string name, string[] values) => 19 | context.Request.Url.Query.TryAdd(name, values); 20 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/SetStatusHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class SetStatusHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.SetStatus); 17 | 18 | protected override void Handle(GatewayContext context, StatusConfig config) 19 | { 20 | context.Response.StatusCode = config.Code; 21 | context.Response.StatusReason = config.Reason; 22 | } 23 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/SetVariableHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [ 9 | Section(nameof(IInboundContext)), 10 | Section(nameof(IBackendContext)), 11 | Section(nameof(IOutboundContext)), 12 | Section(nameof(IOnErrorContext)) 13 | ] 14 | internal class SetVariableHandler : PolicyHandler 15 | { 16 | public override string PolicyName => nameof(IInboundContext.SetVariable); 17 | 18 | protected override void Handle(GatewayContext context, string name, object value) => 19 | context.Variables[name] = value; 20 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/Policies/ValidateJwtHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies; 7 | 8 | [Section(nameof(IInboundContext))] 9 | internal class ValidateJwtHandler : PolicyHandler 10 | { 11 | public override string PolicyName => nameof(IInboundContext.ValidateJwt); 12 | 13 | protected override void Handle(GatewayContext context, ValidateJwtConfig config) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/PolicyExeption.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator; 5 | 6 | public class PolicyException(Exception e) : Exception(e.Message, e) 7 | { 8 | public required string Policy { get; init; } 9 | public required string Section { get; init; } 10 | public required object?[]? PolicyArgs { get; init; } 11 | } -------------------------------------------------------------------------------- /src/Testing/Emulator/SectionAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator; 5 | 6 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 7 | public class SectionAttribute(string scope) : Attribute 8 | { 9 | public string Scope { get; } = scope; 10 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/Extensions/MockBasicAuthCredentials.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public record MockBasicAuthCredentials(string Username, string Password) : BasicAuthCredentials 9 | { 10 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/Extensions/MockExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Implementations; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public static class MockExtensions 9 | { 10 | public static void SetBasicAuthCredentialParser(IBasicAuthCredentialsParser parser) 11 | => ImplementationContext.Default.SetService(parser); 12 | 13 | public static void SetDefaultBasicAuthCredentialParser() 14 | => SetBasicAuthCredentialParser(new BasicAuthCredentialsParser()); 15 | 16 | public static void SetJwtParser(IJwtParser parser) 17 | => ImplementationContext.Default.SetService(parser); 18 | 19 | public static void SetDefaultJwtParser() 20 | => SetJwtParser(new JwtParser()); 21 | 22 | public static void SetUrlContentEncoder(IUrlContentEncoder encoder) 23 | => ImplementationContext.Default.SetService(encoder); 24 | 25 | public static void SetDefaultUrlContentEncoder() 26 | => SetUrlContentEncoder(new UrlContentEncoder()); 27 | 28 | public static void SetDefaultServices() 29 | { 30 | SetDefaultBasicAuthCredentialParser(); 31 | SetDefaultJwtParser(); 32 | SetDefaultUrlContentEncoder(); 33 | } 34 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/Extensions/MockJwt.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockJwt : Jwt 9 | { 10 | public string Id { get; set; } 11 | public string Algorithm { get; set; } 12 | public string Issuer { get; set; } 13 | public string Subject { get; set; } 14 | public string Type { get; set; } 15 | public IEnumerable Audiences { get; set; } 16 | public IReadOnlyDictionary Claims { get; set; } 17 | public DateTime? ExpirationTime { get; set; } 18 | public DateTime? NotBefore { get; set; } 19 | public DateTime? IssuedAt { get; set; } 20 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/Extensions/UrlContentEncoder.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text; 5 | using System.Text.Encodings.Web; 6 | 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Implementations; 8 | 9 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 10 | 11 | public class UrlContentEncoder : IUrlContentEncoder 12 | { 13 | public string? Encode(IDictionary>? dictionary) 14 | => UrlContentEncoder.Encode(dictionary); 15 | 16 | public static string? Encode(IDictionary? dictionary) where T : IEnumerable 17 | { 18 | if (dictionary == null || dictionary.Count == 0) 19 | { 20 | return null; 21 | } 22 | 23 | return dictionary.SelectMany(kvp => kvp.Value.Select(v => (kvp.Key, Value: v))) 24 | .Aggregate( 25 | new StringBuilder(), 26 | (sb, kvp) => 27 | { 28 | if (sb.Length > 0) 29 | { 30 | sb.Append('&'); 31 | } 32 | 33 | sb.Append(UrlEncoder.Default.Encode(kvp.Key)); 34 | sb.Append('='); 35 | sb.Append(UrlEncoder.Default.Encode(kvp.Value)); 36 | return sb; 37 | }, 38 | sb => sb.ToString()); 39 | } 40 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockApi.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockApi : IApi 9 | { 10 | public string Id { get; set; } = "CVjSPi5XPE"; 11 | public string Name { get; set; } = "mock-api"; 12 | 13 | public string Path { get; set; } = "/mock"; 14 | 15 | public IEnumerable Protocols { get; set; } = ["https"]; 16 | 17 | public MockUrl ServiceUrl { get; set; } = new MockUrl(); 18 | IUrl IApi.ServiceUrl => ServiceUrl; 19 | 20 | public MockSubscriptionKeyParameterNames SubscriptionKeyParameterNames { get; set; } = 21 | new MockSubscriptionKeyParameterNames(); 22 | 23 | ISubscriptionKeyParameterNames IApi.SubscriptionKeyParameterNames => SubscriptionKeyParameterNames; 24 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockContextApi.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockContextApi : MockApi, IContextApi 9 | { 10 | public bool IsCurrentRevision { get; set; } = true; 11 | 12 | public string Revision { get; set; } = "2"; 13 | 14 | public string Version { get; set; } = "v2"; 15 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockDeployment.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Security.Cryptography.X509Certificates; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 7 | 8 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 9 | 10 | public class MockDeployment : IDeployment 11 | { 12 | public string GatewayId { get; set; } = "managed"; 13 | public string Region { get; set; } = "eastus"; 14 | public string ServiceId { get; } = "contoso-dev-apim"; 15 | public string ServiceName { get; } = "contoso-dev-apim"; 16 | 17 | public Dictionary Certificates { get; set; } = new Dictionary(); 18 | IReadOnlyDictionary IDeployment.Certificates => Certificates; 19 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockGroup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockGroup : IGroup 9 | { 10 | public string Id { get; set; } = "ZKK26R31mv"; 11 | public string Name { get; set; } = "Developers"; 12 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockLastError.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockLastError : ILastError 9 | { 10 | public string Source { get; set; } 11 | public string Reason { get; set; } 12 | public string Message { get; set; } 13 | public string Scope { get; set; } 14 | public string Section { get; set; } 15 | public string Path { get; set; } 16 | public string PolicyId { get; set; } 17 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockMessage.cs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 2 | 3 | public class MockMessage 4 | { 5 | public MockBody Body { get; set; } = new MockBody(); 6 | public Dictionary Headers { get; set; } = new Dictionary(); 7 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockOperation.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockOperation : IOperation 9 | { 10 | public string Id { get; set; } = "operation-id"; 11 | public string Method { get; set; } = "GET"; 12 | public string Name { get; set; } = "fetch-operation"; 13 | public string UrlTemplate { get; set; } = "/v2/mock/op"; 14 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockPrivateEndpointConnection.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockPrivateEndpointConnection : IPrivateEndpointConnection 9 | { 10 | public string Name { get; set; } 11 | public string GroupId { get; set; } 12 | public string MemberName { get; set; } 13 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockProduct.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockProduct : IProduct 9 | { 10 | public IEnumerable Apis { get; set; } 11 | public bool ApprovalRequired { get; set; } 12 | public IEnumerable Groups { get; set; } 13 | public string Id { get; set; } 14 | public string Name { get; set; } 15 | public ProductState State { get; set; } 16 | public int? SubscriptionLimit { get; set; } 17 | public bool SubscriptionRequired { get; set; } 18 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockRequest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Security.Cryptography.X509Certificates; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 7 | 8 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 9 | 10 | public class MockRequest : MockMessage, IRequest 11 | { 12 | IMessageBody IRequest.Body => Body; 13 | 14 | public X509Certificate2? Certificate { get; set; } = null; 15 | 16 | IReadOnlyDictionary IRequest.Headers => Headers; 17 | 18 | public string IpAddress { get; set; } = "192.168.0.1"; 19 | 20 | public Dictionary MatchedParameters { get; set; } = new Dictionary(); 21 | IReadOnlyDictionary IRequest.MatchedParameters => MatchedParameters; 22 | 23 | public string Method { get; set; } = "GET"; 24 | 25 | public MockUrl OriginalUrl { get; set; } = new MockUrl(); 26 | IUrl IRequest.OriginalUrl => OriginalUrl; 27 | 28 | public MockUrl Url { get; set; } = new MockUrl(); 29 | IUrl IRequest.Url => Url; 30 | 31 | public MockPrivateEndpointConnection? PrivateEndpointConnection { get; set; } 32 | IPrivateEndpointConnection? IRequest.PrivateEndpointConnection => PrivateEndpointConnection; 33 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockResponse.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockResponse : MockMessage, IResponse 9 | { 10 | IMessageBody IResponse.Body => Body; 11 | 12 | IReadOnlyDictionary IResponse.Headers => Headers; 13 | 14 | public int StatusCode { get; set; } = 200; 15 | 16 | public string StatusReason { get; set; } = "OK"; 17 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockSubscription.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockSubscription : ISubscription 9 | { 10 | public DateTime CreatedDate { get; set; } = DateTime.UtcNow.AddDays(-3); 11 | 12 | public DateTime? EndDate { get; set; } 13 | 14 | public string Id { get; set; } = "MBJsUa3qCI"; 15 | 16 | public string Key { get; set; } = "jkgvggusT9"; 17 | 18 | public string Name { get; set; } = "mock-api-access"; 19 | 20 | public string PrimaryKey { get; set; } = "AGfCkbqC6J5wu1n1AnGrl8p5eC5pirHD"; 21 | 22 | public string SecondaryKey { get; set; } = "Of0lkMYsLVnt9f7WfWHBZn2GhZlHfgAJ"; 23 | 24 | public DateTime? StartDate { get; set; } 25 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockSubscriptionKeyParameterNames.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockSubscriptionKeyParameterNames : ISubscriptionKeyParameterNames 9 | { 10 | public string Header { get; set; } = "X-Sub-Header"; 11 | public string Query { get; set; } = "subQuery"; 12 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockUrl.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Web; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 7 | 8 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 9 | 10 | public class MockUrl : IUrl 11 | { 12 | public string Scheme { get; set; } = "https"; 13 | public string Host { get; set; } = "contoso.example"; 14 | public string Port { get; set; } = "443"; 15 | public string Path { get; set; } = "/v2/mock/op"; 16 | 17 | public Dictionary Query { get; set; } = new Dictionary { }; 18 | IReadOnlyDictionary IUrl.Query => Query; 19 | 20 | public string QueryString 21 | { 22 | get 23 | { 24 | var content = UrlContentEncoder.Encode(Query); 25 | return string.IsNullOrEmpty(content) ? "" : $"?{content}"; 26 | } 27 | set 28 | { 29 | var nameValueCollection = HttpUtility.ParseQueryString(value); 30 | var newQuery = new Dictionary(); 31 | foreach (var key in nameValueCollection.AllKeys) 32 | { 33 | newQuery[key!] = nameValueCollection.GetValues(key)!; 34 | } 35 | 36 | Query = newQuery; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockUser.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockUser : IUser 9 | { 10 | public string Email { get; set; } = "joe.doe@contoso.example"; 11 | 12 | public string FirstName { get; set; } = "Joe"; 13 | 14 | public List MockGroups { get; set; } = new List() { new MockGroup() }; 15 | public IEnumerable Groups => MockGroups; 16 | 17 | public string Id { get; set; } = "joe-doe-contoso-example"; 18 | 19 | public List MockUserIdentities { get; set; } = 20 | new List() { new MockUserIdentity() }; 21 | 22 | public IEnumerable Identities => MockUserIdentities; 23 | 24 | public string LastName { get; set; } = "Doe"; 25 | 26 | public string Note { get; set; } = "Joe likes dogs and cats equally"; 27 | 28 | public DateTime RegistrationDate { get; set; } = DateTime.UtcNow.AddDays(-5); 29 | } -------------------------------------------------------------------------------- /src/Testing/Expressions/MockUserIdentity.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 7 | 8 | public class MockUserIdentity : IUserIdentity 9 | { 10 | public string Id { get; set; } = "xPTL3ja8qr"; 11 | public string Provider { get; set; } = "basic"; 12 | } -------------------------------------------------------------------------------- /src/Testing/GatewayContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator; 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Data; 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions; 8 | 9 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing; 10 | 11 | public class GatewayContext : MockExpressionContext 12 | { 13 | internal readonly SectionContextProxy InboundProxy; 14 | internal readonly SectionContextProxy BackendProxy; 15 | internal readonly SectionContextProxy OutboundProxy; 16 | internal readonly SectionContextProxy OnErrorProxy; 17 | internal readonly CertificateStore CertificateStore = new(); 18 | internal readonly CacheStore CacheStore = new(); 19 | internal readonly ResponseExampleStore ResponseExampleStore = new(); 20 | internal readonly LoggerStore LoggerStore = new(); 21 | 22 | public GatewayContext() 23 | { 24 | InboundProxy = SectionContextProxy.Create(this); 25 | BackendProxy = SectionContextProxy.Create(this); 26 | OutboundProxy = SectionContextProxy.Create(this); 27 | OnErrorProxy = SectionContextProxy.Create(this); 28 | } 29 | } -------------------------------------------------------------------------------- /src/Testing/IDocumentExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | 6 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing; 7 | 8 | public static class IDocumentExtensions 9 | { 10 | public static TestDocument AsTestDocument(this IDocument document) => new(document); 11 | } -------------------------------------------------------------------------------- /src/Testing/TestDocument.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Testing; 8 | 9 | public class TestDocument(IDocument document) 10 | { 11 | public GatewayContext Context { get; init; } = new(); 12 | 13 | public void RunInbound() => this.Handle(Context.InboundProxy.Object, document.Inbound); 14 | public void RunBackend() => this.Handle(Context.BackendProxy.Object, document.Backend); 15 | public void RunOutbound() => this.Handle(Context.OutboundProxy.Object, document.Outbound); 16 | public void RunOnError() => this.Handle(Context.OnErrorProxy.Object, document.OnError); 17 | 18 | private void Handle(T context, Action section) 19 | { 20 | try 21 | { 22 | section(context); 23 | } 24 | catch (FinishSectionProcessingException) { } 25 | } 26 | } -------------------------------------------------------------------------------- /test/Test.Analyzers/Test.Analyzers.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | .net8 4 | enable 5 | 6 | false 7 | true 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /test/Test.Analyzers/TypeUsedTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Analyzers; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Analyzers.Test; 6 | 7 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Test.Analyzers; 8 | 9 | [TestClass] 10 | public class TypeUsedTests 11 | { 12 | public static Task VerifyAsync(string source, params DiagnosticResult[] diags) 13 | { 14 | return new BaseAnalyzerTest(source, diags).RunAsync(); 15 | } 16 | 17 | [TestMethod] 18 | public async Task Should() 19 | { 20 | await VerifyAsync( 21 | """ 22 | public static class ExpressionLibrary 23 | { 24 | [Expression] 25 | public static string Method(IExpressionContext context) 26 | { 27 | if(context.Request.Headers.TryGetValue("Authorization", out var value)) 28 | { 29 | return value[0]; 30 | } else 31 | { 32 | return ""; 33 | } 34 | } 35 | 36 | public static string Good(IExpressionContext context) 37 | { 38 | return "test".GetType().FullName; 39 | } 40 | } 41 | """ 42 | ); 43 | } 44 | } -------------------------------------------------------------------------------- /test/Test.Analyzers/Usings.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | global using Microsoft.CodeAnalysis.Testing; 5 | global using Microsoft.VisualStudio.TestTools.UnitTesting; -------------------------------------------------------------------------------- /test/Test.Core/Assertions/AssertionExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Diagnostics.Contracts; 5 | 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 7 | 8 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Assertions; 9 | 10 | public static class AssertionExtensions 11 | { 12 | [Pure] 13 | public static CompilationResultAssertion Should(this IDocumentCompilationResult documentCompilationResult) 14 | { 15 | return new CompilationResultAssertion(documentCompilationResult); 16 | } 17 | } -------------------------------------------------------------------------------- /test/Test.Core/Assertions/CompilationResultAssertion.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using FluentAssertions.Execution; 5 | using FluentAssertions.Primitives; 6 | 7 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 8 | 9 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Assertions; 10 | 11 | public class CompilationResultAssertion : ObjectAssertions 12 | { 13 | public CompilationResultAssertion(IDocumentCompilationResult value) : base(value) 14 | { 15 | } 16 | 17 | public AndConstraint BeSuccessful(string because = "", params object[] becauseArgs) 18 | { 19 | using var scope = new AssertionScope(); 20 | scope.BecauseOf(because, becauseArgs); 21 | this.NotBeNull(); 22 | Subject.Errors.Should().BeEmpty(); 23 | Subject.Document.Should().NotBeNull(); 24 | return new AndConstraint(this); 25 | } 26 | 27 | public AndConstraint DocumentEquivalentTo(string expectedXml, string because = "", 28 | params object[] becauseArgs) 29 | { 30 | Subject.Document.Should().BeEquivalentTo(expectedXml, because, becauseArgs); 31 | return new AndConstraint(this); 32 | } 33 | } -------------------------------------------------------------------------------- /test/Test.Core/Assertions/XElementAssertionsExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text; 5 | using System.Xml; 6 | 7 | using FluentAssertions.Xml; 8 | 9 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Serialization; 10 | 11 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Assertions; 12 | 13 | public static class XElementAssertionsExtensions 14 | { 15 | readonly static XmlWriterSettings DefaultSerializeSettings = new() 16 | { 17 | OmitXmlDeclaration = true, 18 | ConformanceLevel = ConformanceLevel.Fragment, 19 | Indent = true, 20 | IndentChars = " ", 21 | NewLineChars = Environment.NewLine, 22 | }; 23 | 24 | // 25 | // Summary: 26 | // Asserts that a string is exactly the same as policy xml serialized with indentation, without expression formatting 27 | public static void BeEquivalentTo(this XElementAssertions assertions, string expectedXml, string because = "", 28 | params object[] becauseArgs) 29 | { 30 | var strBuilder = new StringBuilder(); 31 | using (var writer = CustomXmlWriter.Create(strBuilder, DefaultSerializeSettings)) 32 | { 33 | writer.Write(assertions.Subject); 34 | } 35 | 36 | var document = strBuilder.ToString(); 37 | document.Should().BeEquivalentTo(expectedXml.ReplaceLineEndings(), because, becauseArgs); 38 | } 39 | } -------------------------------------------------------------------------------- /test/Test.Core/Compiling/AuthenticatiionManagedIdentityTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 5 | 6 | [TestClass] 7 | public class AuthenticationManagedIdentityTests 8 | { 9 | [TestMethod] 10 | [DataRow( 11 | """ 12 | [Document] 13 | public class PolicyDocument : IDocument 14 | { 15 | public void Inbound(IInboundContext context) 16 | { 17 | context.AuthenticationManagedIdentity(new ManagedIdentityAuthenticationConfig { Resource = "resource" }); 18 | } 19 | public void Outbound(IOutboundContext context) 20 | { 21 | context.AuthenticationManagedIdentity(new ManagedIdentityAuthenticationConfig { Resource = "resource" }); 22 | } 23 | } 24 | """, 25 | """ 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | """, 35 | DisplayName = "Should compile authentication manage identity policy in sections" 36 | )] 37 | public void ShouldCompileAuthenticationManagedIdentityPolicy(string code, string expectedXml) 38 | { 39 | code.CompileDocument().Should().BeSuccessful().And.DocumentEquivalentTo(expectedXml); 40 | } 41 | } -------------------------------------------------------------------------------- /test/Test.Core/Compiling/BaseTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 5 | 6 | [TestClass] 7 | public class BaseTests 8 | { 9 | [TestMethod] 10 | [DataRow( 11 | """ 12 | [Document] 13 | public class PolicyDocument : IDocument 14 | { 15 | public void Inbound(IInboundContext context) { context.Base(); } 16 | public void Outbound(IOutboundContext context) { context.Base(); } 17 | public void Backend(IBackendContext context) { context.Base(); } 18 | public void OnError(IOnErrorContext context) { context.Base(); } 19 | } 20 | """, 21 | """ 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | """, 37 | DisplayName = "Should compile base policy in sections" 38 | )] 39 | public void ShouldCompileBasePolicy(string code, string expectedXml) 40 | { 41 | code.CompileDocument().Should().BeSuccessful().And.DocumentEquivalentTo(expectedXml); 42 | } 43 | } -------------------------------------------------------------------------------- /test/Test.Core/Compiling/RedirectContentUrlsTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling; 5 | 6 | [TestClass] 7 | public class RedirectContentUrlsTests 8 | { 9 | [TestMethod] 10 | [DataRow( 11 | """ 12 | [Document] 13 | public class PolicyDocument : IDocument 14 | { 15 | public void Inbound(IInboundContext context) { context.RedirectContentUrls(); } 16 | public void Outbound(IOutboundContext context) { context.RedirectContentUrls(); } 17 | } 18 | """, 19 | """ 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | """, 29 | DisplayName = "Should compile redirect content urls policy in sections" 30 | )] 31 | public void ShouldCompileRedirectContentUrlsPolicy(string code, string expectedXml) 32 | { 33 | code.CompileDocument().Should().BeSuccessful().And.DocumentEquivalentTo(expectedXml); 34 | } 35 | } -------------------------------------------------------------------------------- /test/Test.Core/Test.Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | .net8 4 | enable 5 | enable 6 | 7 | false 8 | true 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /test/Test.Core/Usings.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | global using FluentAssertions; 5 | 6 | global using Microsoft.Azure.ApiManagement.PolicyToolkit.Assertions; 7 | global using Microsoft.Azure.ApiManagement.PolicyToolkit.Tests.Extensions; 8 | global using Microsoft.VisualStudio.TestTools.UnitTesting; -------------------------------------------------------------------------------- /test/Test.Testing/Emulator/Policies/AzureOpenAiEmitTokenMetricTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing; 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 7 | 8 | namespace Test.Emulator.Emulator.Policies; 9 | 10 | [TestClass] 11 | public class AzureOpenAiEmitTokenMetricTests 12 | { 13 | class SimpleAzureOpenAiEmitTokenMetric : IDocument 14 | { 15 | public void Inbound(IInboundContext context) 16 | { 17 | context.AzureOpenAiEmitTokenMetric(new EmitTokenMetricConfig 18 | { 19 | Dimensions = [new MetricDimensionConfig() { Name = "Test" }] 20 | }); 21 | } 22 | } 23 | 24 | [TestMethod] 25 | public void AzureOpenAiEmitTokenMetric_Callback() 26 | { 27 | var test = new SimpleAzureOpenAiEmitTokenMetric().AsTestDocument(); 28 | var executedCallback = false; 29 | test.SetupInbound().AzureOpenAiEmitTokenMetric().WithCallback((_, _) => 30 | { 31 | executedCallback = true; 32 | }); 33 | 34 | test.RunInbound(); 35 | 36 | executedCallback.Should().BeTrue(); 37 | } 38 | } -------------------------------------------------------------------------------- /test/Test.Testing/Emulator/Policies/AzureOpenAiSemanticCacheLookupTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing; 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 7 | 8 | namespace Test.Emulator.Emulator.Policies; 9 | 10 | [TestClass] 11 | public class AzureOpenAiSemanticCacheLookupTests 12 | { 13 | class SimpleAzureOpenAiSemanticCacheLookup : IDocument 14 | { 15 | public void Inbound(IInboundContext context) 16 | { 17 | context.AzureOpenAiSemanticCacheLookup(new SemanticCacheLookupConfig() 18 | { 19 | ScoreThreshold = 0.05M, EmbeddingsBackendId = "backend-id", EmbeddingsBackendAuth = "token" 20 | }); 21 | } 22 | } 23 | 24 | [TestMethod] 25 | public void AzureOpenAiEmitTokenMetric_Callback() 26 | { 27 | var test = new SimpleAzureOpenAiSemanticCacheLookup().AsTestDocument(); 28 | var executedCallback = false; 29 | test.SetupInbound().AzureOpenAiSemanticCacheLookup().WithCallback((_, _) => 30 | { 31 | executedCallback = true; 32 | }); 33 | 34 | test.RunInbound(); 35 | 36 | executedCallback.Should().BeTrue(); 37 | } 38 | } -------------------------------------------------------------------------------- /test/Test.Testing/Emulator/Policies/ForwardRequestTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring; 5 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing; 6 | using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Document; 7 | 8 | namespace Test.Emulator.Emulator.Policies; 9 | 10 | [TestClass] 11 | public class ForwardRequestTests 12 | { 13 | class SimpleForwardRequest : IDocument 14 | { 15 | public void Backend(IBackendContext context) 16 | { 17 | context.ForwardRequest(); 18 | } 19 | } 20 | 21 | [TestMethod] 22 | public void ForwardRequest_Callback() 23 | { 24 | var test = new SimpleForwardRequest().AsTestDocument(); 25 | var executedCallback = false; 26 | test.SetupBackend().ForwardRequest().WithCallback((_, _) => 27 | { 28 | executedCallback = true; 29 | }); 30 | 31 | test.RunBackend(); 32 | 33 | executedCallback.Should().BeTrue(); 34 | } 35 | } -------------------------------------------------------------------------------- /test/Test.Testing/Test.Testing.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | false 9 | true 10 | Test.Emulator 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /test/Test.Testing/Usings.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | global using FluentAssertions; 5 | 6 | global using Microsoft.VisualStudio.TestTools.UnitTesting; --------------------------------------------------------------------------------