agentleFS
Microsoft AzureKnown publisherAzure/azure-api-management-policy-toolkit/.github/skills/policy-codebase-reference/SKILL.md

policy-codebase-reference

Skill95 starsChanged 12 months agoMITView on GitHub

Reference guide for the Azure API Management policy toolkit codebase structure. Use this skill when you need to find existing policies, infrastructure, or naming conventions.

The file

We split this skill into the rules it gives an agent

3 rules. About 0 are common, 2 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every new .cs file must start with:

    line 79
  2. Distinctive:

    When implementing a new policy, choose the closest structural match as your reference:

    line 88
  3. Distinctive:

    When implementing a new emulator handler, choose the closest structural match:

    line 159

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Policy Toolkit Codebase Reference

This skill provides an inventory of the codebase structure, shared infrastructure, reference policy selection, and naming conventions for the Azure API Management policy toolkit.

File Path Conventions

Authoring & Compilation

ArtifactLocationExample
Config recordsrc/Authoring/Configs/{PolicyName}Config.csRateLimitConfig.cs
Document attributesrc/Authoring/Attributes/DocumentAttribute.cs—
Expression attributesrc/Authoring/Attributes/ExpressionAttribute.cs—
Expression-allowed attributesrc/Authoring/Attributes/ExpressionAllowedAttribute.cs—
Section interfacessrc/Authoring/I{Section}Context.csIInboundContext.cs
Compiler classsrc/Core/Compiling/Policy/{PolicyName}Compiler.csRateLimitCompiler.cs
Compiler test classtest/Test.Core/Compiling/{PolicyName}Tests.csRateLimitTests.cs
Available policies docdocs/AvailablePolicies.md—
Compiler utilitiessrc/Core/Compiling/CompilerUtils.cs—
Syntax extensionssrc/Core/Compiling/SyntaxExtensions.cs—
Diagnosticssrc/Core/Compiling/Diagnostics/CompilationErrors.cs—
IoC / auto-registrationsrc/Core/IoC/CompilerModule.cs—
Test initializationtest/Test.Core/CompilerTestInitialize.cs—
Assertion helperstest/Test.Core/Assertions/CompilationResultAssertion.cs
Generic compiler utilitiessrc/Core/Compiling/Policy/GenericCompiler.cs—
Add-policy guidedocs/AddPolicyGuide.md—

Gateway Emulator

ArtifactLocationExample
Emulator handler classsrc/Testing/Emulator/Policies/{PolicyName}Handler.csSetHeaderHandler.cs
Handler base classessrc/Testing/Emulator/Policies/PolicyHandler.cs—
IPolicyHandler interfacesrc/Testing/Emulator/IPolicyHandler.cs—
Section attributesrc/Testing/Emulator/Policies/SectionAttribute.cs—
Argument extensionssrc/Testing/Emulator/Policies/ArgumentsExtensions.cs—
Policy exceptionsrc/Testing/Emulator/PolicyExeption.csNote: filename has typo
SectionContextProxysrc/Testing/Emulator/SectionContextProxy.cs—
GatewayContextsrc/Testing/GatewayContext.cs—
TestDocumentsrc/Testing/TestDocument.cs—
Emulator test classtest/Test.Testing/Emulator/Policies/{PolicyName}Tests.csSetHeaderTests.cs
Emulator policy checklistdocs/EmulatorPolicyChecklist.md—

Naming Conventions

Authoring & Compilation

ArtifactConventionExample
Config record{PolicyName}ConfigRateLimitConfig
Sub-config record{DescriptiveName}ApiRateLimit, AddressRange
Compiler class{PolicyName}CompilerRateLimitCompiler
Compiler test class{PolicyName}TestsRateLimitTests
Context method{PolicyName}RateLimit
XML element namekebab-caserate-limit
Config namespaceMicrosoft.Azure.ApiManagement.PolicyToolkit.Authoring—
Compiler namespaceMicrosoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy—
Compiler test namespaceMicrosoft.Azure.ApiManagement.PolicyToolkit.Compiling—

Gateway Emulator

ArtifactConventionExample
Handler class{PolicyName}HandlerSetHeaderHandler
Emulator test class{PolicyName}TestsSetHeaderTests
PolicyName propertyPascalCase method name from section interfaceSetHeader
Handler namespaceMicrosoft.Azure.ApiManagement.PolicyToolkit.Testing.Emulator.Policies—
Emulator test namespaceTest.Emulator.Emulator.Policies—

Note: JsonToXmlHandle.cs is a naming inconsistency in the source (missing the r in Handler). Do not rename it.

Copyright Header

Every new .cs file must start with:

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

Reference Policy Selection Guide

When implementing a new policy, choose the closest structural match as your reference:

Policy StructureReference ConfigReference CompilerReference Tests
Simple attributes onlyRateLimitByKeyConfigRateLimitByKeyCompilerRateLimitByKeyTests
Attributes + child elementsRateLimitConfigRateLimitCompilerRateLimitTests
Attributes + typed child arraysIpFilterConfigIpFilterCompilerIpFilterTests
String-list child elementsValidateJwtConfigValidateJwtCompilerValidateJwtTests
Complex nested configsCorsConfigCorsCompilerCorsTests
Direct parameters (no config)—SetMethodCompilerSetMethodTests

Shared Infrastructure Inventory

Expression Support

  • [Document] attribute (src/Authoring/Attributes/DocumentAttribute.cs) — Marks a class as a policy document. Optional name parameter; Scope and Type properties control document scope and type.
  • [Expression] attribute (src/Authoring/Attributes/ExpressionAttribute.cs) — Marks a method as a policy expression helper. Captures source file path via [CallerFilePath].
  • [ExpressionAllowed] attribute (src/Authoring/Attributes/ExpressionAllowedAttribute.cs) — Marks properties or parameters that accept policy expressions.
  • Expression<T> delegate (src/Authoring/Expression.cs) — delegate T Expression<out T>(IExpressionContext context).
  • IHaveExpressionContext interface (src/Authoring/IHaveExpressionContext.cs) — Base interface for all section contexts, providing IExpressionContext ExpressionContext { get; }.

Compiler Infrastructure

  • IMethodPolicyHandler interface (src/Core/Compiling/IMethodPolicyHandler.cs) — The primary compiler interface. Properties: string MethodName { get; }. Method: void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node).
  • IReturnValueMethodPolicyHandler interface (src/Core/Compiling/IReturnValueMethodPolicyHandler.cs) — For policies returning a value. Currently disabled (the LocalDeclarationStatementCompiler is commented out in CompilerModule.cs).
  • Auto-registration (src/Core/IoC/CompilerModule.cs) — Uses reflection to find and register all public, non-abstract classes in the Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy namespace that implement IMethodPolicyHandler. No manual DI wiring needed for standard compilers.
  • CompilerUtils (src/Core/Compiling/CompilerUtils.cs) — Static utility class with methods for parameter extraction (ProcessParameter, TryExtractingConfig), expression processing, and syntax normalization. Also defines InitializerValue for property name → value mapping.
  • SyntaxExtensions (src/Core/Compiling/SyntaxExtensions.cs) — Extension methods for Roslyn syntax trees: attribute detection (ContainsAttributeOfType<T>), document class discovery (GetDocumentAttributedClasses), and document metadata extraction.
  • GenericCompiler.HandleList (src/Core/Compiling/Policy/GenericCompiler.cs) — Utility for compiling string arrays into repeated child XML elements.
  • CompilationErrors (src/Core/Compiling/Diagnostics/CompilationErrors.cs) — Static class with DiagnosticDescriptor fields for all compilation error types.

Compiler Test Infrastructure

  • CompilerTestInitialize (test/Test.Core/CompilerTestInitialize.cs) — Assembly-level MSTest setup. Creates Roslyn compilation with references to System, System.Xml.Linq, and the Authoring assembly. Provides the CompileDocument() extension method.
  • CompilationResultAssertion (test/Test.Core/Assertions/CompilationResultAssertion.cs) — FluentAssertions extension providing BeSuccessful() and DocumentEquivalentTo(string expectedXml).
  • Usings.cs (test/Test.Core/Usings.cs) — Global usings: FluentAssertions, Microsoft.VisualStudio.TestTools.UnitTesting, assertion helpers, test extensions.

Emulator Infrastructure

  • IPolicyHandler interface (src/Testing/Emulator/IPolicyHandler.cs) — The handler interface. Properties: string PolicyName { get; }. Method: object? Handle(GatewayContext context, object?[]? args).
  • PolicyHandler<T> base classes (src/Testing/Emulator/Policies/PolicyHandler.cs) — Three generic variants: single config, optional config, and two-parameter. All include CallbackSetup for test mocking.
  • SectionContextProxy<T> (src/Testing/Emulator/SectionContextProxy.cs) — Uses System.Reflection.DispatchProxy to dynamically route method calls to handlers. Discovers handlers via reflection on namespace + [Section] attribute.
  • [Section] attribute (src/Testing/Emulator/Policies/SectionAttribute.cs) — Constructor takes string scope (use nameof(IInboundContext), etc.). Multiple attributes can be stacked.
  • ArgumentsExtensions (src/Testing/Emulator/Policies/ArgumentsExtensions.cs) — Static utility for safe argument extraction from object?[]?: ExtractArgument<T>() (required single arg), ExtractOptionalArgument<T>() (nullable), and ExtractArguments<T1, T2>() (two-param handlers).
  • PolicyException (src/Testing/Emulator/PolicyExeption.cs) — Exception thrown when a handler fails. Carries Policy, Section, and PolicyArgs context. Note: filename has a typo (Exeption) — do not rename.
  • GatewayContext (src/Testing/GatewayContext.cs) — Central mock object with section proxies, mock stores (CertificateStore, CacheStore, ResponseExampleStore, LoggerStore), and expression context.
  • TestDocument (src/Testing/TestDocument.cs) — Orchestrates test execution across policy sections. Wraps IDocument and calls section methods through proxies.
  • FinishSectionProcessingException — Thrown by handlers (e.g., MockResponse, ReturnResponse) to terminate section processing early.

Emulator Test Infrastructure

  • .AsTestDocument() extension — Creates TestDocument from IDocument for fluent test setup.
  • SetupInbound()/SetupOutbound()/etc. — Returns MockPoliciesProvider<TSection> for mock configuration.
  • Usings.cs (test/Test.Testing/Usings.cs) — Global usings for FluentAssertions and MSTest.

Section Interfaces

Policies can be available in one or more pipeline sections:

SectionInterface FileXML Section
Inboundsrc/Authoring/IInboundContext.cs<inbound>
Outboundsrc/Authoring/IOutboundContext.cs<outbound>
Backendsrc/Authoring/IBackendContext.cs<backend>
On-Errorsrc/Authoring/IOnErrorContext.cs<on-error>
Fragmentsrc/Authoring/IFragmentContext.csN/A (reusable fragment)

Note: IFragmentContext duplicates method signatures from other interfaces (see //TODO at top of file). Copy signatures verbatim when adding policies there.

Emulator Reference Handler Selection Guide

When implementing a new emulator handler, choose the closest structural match:

Policy StructureReference HandlerReference Test
Single config, simple state changeSetStatusHandlerSetStatusTests
Two parameters (name + values)SetHeaderHandlerSetHeaderTests
Config with callback hooks only (no-op)RateLimitHandlerRateLimitTests
Optional configMockResponseHandlerMockResponseTests
Validation + short-circuitCheckHeaderHandlerCheckHeaderTests
Authentication + tokenAuthenticationManagedIdentityHandlerAuthenticationManagedIdentityHandlerTests
Cache interactionCacheLookupValueHandlerCacheLookupValueTests
Logging/store interactionLogToEventHubHandlerLogToEventHubTests
No-config (no-arg method)BaseHandlerBaseTests
Custom flow control / wrapperReturnResponseHandler—
AzureOpenAi variant (inherits Llm)AzureOpenAiEmitTokenMetricHandler—

Common Pitfalls

PitfallRule
Modifying .csproj filesDo not change Compiling.csproj or Testing.csproj unless explicitly required. Reformatting, reordering, or encoding changes (BOM, line endings) cause noisy diffs and will be rejected in review.
Missing IFragmentContext entryEvery method added to a section interface (IInboundContext, IOutboundContext, etc.) must also be added to IFragmentContext.cs. See the authoring skill for details.
Missing expression testsEvery property marked [ExpressionAllowed] in a config must have a corresponding expression test [DataRow]. See the testing skill section 3 for the pattern.

Build and Test Commands

# Build the entire solution
dotnet build

# Run all compiler tests
dotnet test --project test/Test.Core

# Run all emulator tests
dotnet test --project test/Test.Testing

# Run tests for a specific policy
dotnet test --filter "FullyQualifiedName~{PolicyName}Tests"

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.