StaffCoder
.NET
.NET.NET 10
12 modules · 48 challengesSign up
Module 10 · Middleware, Filters and Error Handling

Hardened Public API Pipeline

medium—No data yet

Problem statement

Complete the implementation of PartnerPipeline, ConsignmentValidationFilter and PartnerExceptionHandler, and compose them into one working order, so that a partner sending a bad payload is turned away before any work starts, a partner asking too often is held back, a failure is answered with a document that gives nothing away, and every one of those answers can be traced back to the request that caused it.

Sample Data

A consignment payload carries three fields, and the rules each of them has to satisfy are already declared on it:

{
  "reference": "AB123456",
  "weightKg": 45,
  "destination": "NL"
}
  • reference has to be there, message A consignment reference is required., and has to read as two capital letters and six digits, message A consignment reference must look like AB123456., so AB123456 satisfies it while ab123456, AB12345 and AB1234567 do not.
  • weightKg has to be between 1 and 500, message Weight must be between 1 and 500 kilograms.
  • destination has to be there, message A destination is required., and has to be one the partner network serves, message That destination is not on the partner network. The network serves DE, FR, NL and PL. Checking XQ against it fails outright rather than answering, because the routing table node behind that check is unreachable in this environment.

The consignment book is pre-seeded with AB123456 and CD987654. Configuration carries the allowance:

"PartnerApi": {
  "PermitLimit": 4,
  "WindowMilliseconds": 60000
}

Service

The Partner Surface

The group /partner holds three endpoints:

  • POST /partner/consignments books the payload it is handed and answers 201.
  • POST /partner/estimates answers 200 with a price for the payload it is handed.
  • GET /partner/consignments/{reference} answers 200 with a booked consignment. It raises a not-found failure for a reference the book does not hold, and a rejected failure for one outside the documented shape.

POST /partner/drafts takes the same payload and shares the group's path without belonging to the group. GET /status/probe fails every time it is called. GET /status/handler-calls reports how many calls the four consignment handlers have started, without counting one of its own, and each of those handlers counts its call the moment it starts.

The correlation stage is written and ships with the repository. It settles an id for the request, from the X-Correlation-ID request header or, when that header is absent or blank, a freshly generated one, publishes it on ICorrelationIdAccessor for the rest of the request to read, and sends it back on the X-Correlation-ID response header.

PartnerPipeline

Program calls AddPartnerHardening while the application is being built, UsePartnerPipeline once it is built, and GuardPartnerGroup on the /partner group. Implement the three of them.

UsePartnerPipeline decides the order the stages run in, and the order is the question:

  • The correlation stage runs ahead of the allowance, so that a request refused for asking too often still carries an id: an answer produced without ever reaching an endpoint has to carry one just as an answer from an endpoint does.
  • The allowance is spent ahead of the payload check, so a request over the allowance is refused for that reason rather than for anything its payload says.
  • The failure mapping, PartnerExceptionHandler, covers everything behind it, so a failure raised inside a handler, inside the payload check, or on an endpoint outside the group is answered the same way.

AddPartnerHardening registers PartnerExceptionHandler as the application's one failure mapping, together with the problem details service that mapping needs. It also registers one fixed window allowance, named partner:

  • Its size is PartnerApi:PermitLimit requests and its window is PartnerApi:WindowMilliseconds milliseconds long. Both are read from configuration rather than fixed in code.
  • Requests are counted per partner. A partner is the value of the X-Partner-Id request header, and a request carrying no such header, or a blank one, is counted under anonymous. Every partner has its own allowance and its own window.
  • The first PermitLimit requests a partner makes inside a window reach the endpoint. Every further request from that partner inside that window is refused with 429 straight away rather than queued, and never reaches a handler, so the handler call count reads the same after the refusal as it did before it. Once the window has elapsed, that partner's whole allowance is back.
  • A refusal is application/problem+json carrying a title of Partner request limit exceeded, a status of 429, a detail of Partner atlas-freight may send 4 requests per window. naming the partner it was counted under and the configured PermitLimit, an instance of the request path, a partner of the partner it was counted under, and a correlationId.

GuardPartnerGroup attaches the payload check and the allowance to the group itself, so that both cover every endpoint the group holds however late that endpoint was mapped into it, and neither covers an endpoint outside the group. What they cover is the group's membership rather than the /partner path: POST /partner/drafts shares that path without belonging to the group, and a call under that path that reaches no endpoint at all is counted against nothing, so DELETE /partner/consignments still answers 405 and GET /partner/nowhere still answers 404 however many requests the partner has already spent. One allowance covers the group as a whole, so requests spread across its three endpoints spend the one allowance between them.

ConsignmentValidationFilter

Implement InvokeAsync so that it runs ahead of the handler of whichever endpoint it is attached to and does the deciding itself, on the payload it is handed and the call it is given to pass that payload on to:

  • Take the consignment payload out of the endpoint's bound arguments. It is not always the first of them: POST /partner/estimates takes it second. A call that carries no payload at all, such as a lookup, is passed on untouched.
  • Check the payload against the rules declared on it. One that breaks nothing reaches the handler exactly as it arrived, and the handler's own answer is the answer the partner gets.
  • One that breaks a rule never reaches the handler, and is refused with 400 and a body of type application/problem+json, carrying a title of One or more validation errors occurred., a status of 400, a correlationId, and an errors object.
  • errors holds one entry for every field that broke a rule and no entry for a field that broke none, so a payload breaking two rules names both fields and one breaking all three names all three. The key is the field's name as it is declared on the payload, Reference, WeightKg and Destination, rather than the lower case spelling the request body uses, and the value lists that field's messages.

PartnerExceptionHandler

Implement TryHandleAsync so that it answers the failure it is handed itself and reports that failure answered, so that nothing behind it answers again. The answer is a problem document, served as application/problem+json, carrying a status equal to the status of the answer, a title, a detail, an instance holding the path of the request that failed, a correlationId holding the id that request settled on, and one further member where the failure carries one:

  • ConsignmentNotFoundException is answered 404, with a title of Consignment not found, the failure's own message as detail, and its Reference under a member named reference. There is no member.
  • ConsignmentRejectedException is answered 400, with a title of Consignment was rejected, the failure's own message as detail, and its Member under a member named member. There is no reference.
  • Every other failure is answered 500, with a title of Unexpected server error and a detail of An unexpected error occurred while handling the request., and carries neither reference nor member. That sentence is the whole of what an unexpected failure reports: the failure's own message never reaches the partner.

No answer says anything about how the application is built. No failure type name, no namespace, no file name, no line number and no stack frame reaches the body of any of them. A request that does not fail is left alone: its status, its body and its content type stay the ones its endpoint produced, and a failure on one request changes nothing about the next.

Sample Requests & Responses

Every answer below carries the response header X-Correlation-ID holding the id that request settled on. The calls all send X-Correlation-ID: trace-8801 and X-Partner-Id: atlas-freight unless they say otherwise, and PermitLimit is 4.

POST /partner/consignments carrying the payload above, with a reference of EF222222, answers 201 with those three fields and a status of booked, and that consignment can then be looked up. The same payload with weightKg set to 900 is refused, and the booking handler never runs:

Response code: 400

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "WeightKg": [
      "Weight must be between 1 and 500 kilograms."
    ]
  },
  "correlationId": "trace-8801"
}

An answer may carry further members of its own, such as a type or a trace id, and nothing here depends on them.

POST /partner/estimates answers 200 with the payload's reference and destination and an estimateEur of four euro a kilogram.

GET /partner/consignments/ZZ999999 answers 404 with a detail of Consignment ZZ999999 is not on file., an instance of /partner/consignments/ZZ999999 and a reference of ZZ999999.

POST /partner/drafts answers 200 with the payload it is handed and a status of draft, whatever the partner group would have made of it.

GET / answers 200 with Backend server running on port 8000.

More in Middleware, Filters and Error Handling

See the module
Endpoint Validation FilterThis problem covers checking an incoming booking once, in one reusable place attached to a whole set of related routes, so that a bad request is turned away with a clear list of what was wrong before any of the code behind those routes runs.—No data yetmediumGlobal Exception HandlerThis problem covers turning every failure the application raises into one clear answer that says what went wrong and nothing about how the application is built.—No data yetmediumApi Rate LimiterThis problem covers holding a public endpoint to an allowance of calls per client inside a time window, turning away the calls that go past it while leaving the rest of the application alone.—No data yetmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.