├── .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