Skip to content

feat(policy): add set-status-code policy v0.1.0#167

Open
renuka-fernando wants to merge 4 commits intowso2:mainfrom
renuka-fernando:set-status-code
Open

feat(policy): add set-status-code policy v0.1.0#167
renuka-fernando wants to merge 4 commits intowso2:mainfrom
renuka-fernando:set-status-code

Conversation

@renuka-fernando
Copy link
Copy Markdown
Contributor

@renuka-fernando renuka-fernando commented Apr 2, 2026

Purpose

Add a new set-status-code gateway policy that overwrites the upstream response status code before forwarding to the downstream client. This is useful for normalising status codes across backends or masking upstream error codes from clients.

Approach

  • Implements ResponsePolicy.OnResponseBody using DownstreamResponseModifications.StatusCode from sdk/core v1alpha2
  • Accepts a single statusCode integer parameter (100–599); handles both int and float64 types to support JSON-unmarshalled params
  • Returns a 500 config error response on missing, invalid type, or out-of-range parameter
  • Adds policy-definition.yaml with parameter schema (min: 100, max: 599)
  • Adds unit tests covering valid codes, boundary values, float64 input, nil/missing params, invalid types, and out-of-range values
  • Adds docs under docs/set-status-code/v0.1/ with metadata and usage guide

Related Issues

N/A

Checklist

  • Tests added or updated (unit, integration, etc.)
  • Samples updated (if applicable)

Summary by CodeRabbit

  • New Features

    • New Set Status Code policy available to overwrite upstream response HTTP status for API gateways (configurable 100–599).
  • Documentation

    • Added comprehensive docs and examples for the Set Status Code policy, including configuration and runtime behavior.
  • Chores

    • Tightened policy parameter schemas to reject unspecified fields and updated underlying module dependencies across multiple policies for consistency.

Add a new gateway policy that overwrites the upstream response status
code before forwarding to the downstream client.

- Implements ResponsePolicy.OnResponseBody using DownstreamResponseModifications.StatusCode
- Accepts statusCode integer param (100–599); handles both int and float64 (JSON unmarshal)
- Returns 500 config error on missing, invalid type, or out-of-range param
- Includes policy-definition.yaml, tests, and docs (v0.1)
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 2, 2026

Walkthrough

Adds a new "Set Status Code" policy with implementation, tests, policy definition, module files, and documentation; it validates a configured statusCode (100–599) and sets the downstream response status code or returns a 500 configuration error on invalid input.

Changes

Cohort / File(s) Summary
Documentation
docs/set-status-code/v0.1/docs/set-status-code.md, docs/set-status-code/v0.1/metadata.json
New docs and metadata describing the Set Status Code policy, configuration, example YAML, runtime behavior, and parameter constraints.
Policy Definition & Module
policies/set-status-code/go.mod, policies/set-status-code/policy-definition.yaml
New Go module and policy-definition declaring set-status-code v0.1.0 with a required statusCode integer parameter (min:100, max:599).
Policy Implementation
policies/set-status-code/setstatuscode.go
New policy type and factory; buffers response body, parses/validates statusCode (accepts int or integer-valued float64), returns 500 ImmediateResponse on invalid config, otherwise returns DownstreamResponseModifications with the configured status code.
Tests
policies/set-status-code/setstatuscode_test.go
Comprehensive unit tests for valid, boundary, and invalid parameter cases, Mode() assertions, and GetPolicy factory coverage.
Go module bumps
policies/*/go.mod (multiple policies, see repo)
Updated github.com/wso2/api-platform/sdk/core dependency from v0.2.4 to v0.2.9 across many policy modules (multiple small, identical go.mod edits).
Policy schema tightening
policies/.../policy-definition.yaml (multiple policies)
Added additionalProperties: false to top-level parameters in several policy definition YAMLs, restricting allowed parameter keys (multiple similar schema edits).
sequenceDiagram
    participant Client as Client
    participant Gateway as Gateway Policy Engine
    participant Upstream as Upstream Service

    Client->>Upstream: Request (via Gateway)
    Upstream-->>Gateway: Response (status, headers, body)
    Gateway->>Gateway: OnResponseBody — parse params, validate statusCode
    alt statusCode valid
        Gateway-->>Client: Forward response with replaced status code
    else invalid or missing
        Gateway-->>Client: Immediate 500 JSON error response
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I’m a rabbit with a tiny rule,
I hop and change a status cool,
From upstream’s code to downstream’s view,
I keep it neat from 100 to 599 true,
A cheerful hop — the gateway’s new tool 🐇✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The PR description covers Purpose and Approach but is missing several required sections from the template (Goals, User stories, Release note, Documentation, Training, Certification, Marketing, Security checks, Samples, Migrations, Test environment, Learning). Complete the PR description by adding the missing sections: Goals, User stories, Release note, Documentation, Training, Certification, Marketing, Security checks (with yes/no answers), Samples, Migrations, Test environment, and Learning. Alternatively, provide explanations for why certain sections are N/A.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding a new set-status-code policy at version 0.1.0, which is the primary objective of the pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@policies/set-status-code/go.mod`:
- Line 5: The go.mod in the set-status-code policy pins
github.com/wso2/api-platform/sdk/core to v0.2.9 while most other policy modules
use v0.2.4; update the dependency to align versions across policies or add a
clear justification comment in this module explaining why v0.2.9 is required
(e.g., list the API/ABI differences or functions on which this policy relies) so
reviewers/runtime maintainers understand the divergence; specifically edit the
require line for github.com/wso2/api-platform/sdk/core in set-status-code (and
verify host-rewrite) or add a DOCUMENTATION comment in this module referencing
the differing version and the reason.

In `@policies/set-status-code/policy-definition.yaml`:
- Around line 6-16: The policy schema currently allows unknown extra keys
because the top-level "parameters" schema is missing additionalProperties:
false; update the "parameters" object in policy-definition.yaml to add
additionalProperties: false so only the declared "statusCode" property is
permitted (retain the existing "statusCode" constraints and required array).

In `@policies/set-status-code/setstatuscode.go`:
- Around line 67-72: The float64 branch in the switch handling raw input in
setstatuscode.go currently truncates decimals (case float64 { statusCode =
int(v) }) which allows fractional inputs like 200.9; change the float64 case in
the function that parses the raw parameter so it first checks if math.Trunc(v)
== v and only then converts with int(v), otherwise return an error/validation
failure (consistent with existing error handling paths) so non-integer floats
are rejected; also add a unit test (e.g., in
TestSetStatusCodePolicy_OnResponseBody_Float64Param) that passes a fractional
float64 (like 200.9) and asserts the policy rejects it.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b6f0b64c-6d5a-4944-bd86-4f4018e77145

📥 Commits

Reviewing files that changed from the base of the PR and between b398aca and d1bc51d.

⛔ Files ignored due to path filters (1)
  • policies/set-status-code/go.sum is excluded by !**/*.sum
📒 Files selected for processing (6)
  • docs/set-status-code/v0.1/docs/set-status-code.md
  • docs/set-status-code/v0.1/metadata.json
  • policies/set-status-code/go.mod
  • policies/set-status-code/policy-definition.yaml
  • policies/set-status-code/setstatuscode.go
  • policies/set-status-code/setstatuscode_test.go

Comment thread policies/set-status-code/go.mod
Comment thread policies/set-status-code/policy-definition.yaml
Comment thread policies/set-status-code/setstatuscode.go
The top-level `parameters` object in 17 policy-definition.yaml files
was missing `additionalProperties: false`, allowing unknown extra keys
to pass schema validation silently. Added the constraint to:
- set-status-code, basic-auth, host-rewrite, cors
- content-length-guardrail, regex-guardrail, json-schema-guardrail
- model-round-robin, model-weighted-round-robin
- pii-masking-regex, prompt-decorator, prompt-template
- semantic-cache, semantic-prompt-guard, semantic-tool-filtering
- aws-bedrock-guardrail, azure-content-safety-content-moderation
- Add fractional check in the float64 switch case: converts to int and
  verifies round-trip equality before accepting the value
- Add TestSetStatusCodePolicy_OnResponseBody_Float64FractionalParam to
  assert that inputs like 200.9 are rejected with a 500 error
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
policies/content-length-guardrail/policy-definition.yaml (1)

109-111: Consider adding additionalProperties: false to systemParameters for consistency.

Other policies (e.g., azure-content-safety-content-moderation) include additionalProperties: false on their systemParameters object. Here, systemParameters has empty properties: {} but no additionalProperties constraint, which would allow arbitrary keys to be passed.

If this policy intentionally has no system parameters, adding the constraint would enforce that explicitly.

Suggested change
 systemParameters:         
   type: object
+  additionalProperties: false
   properties: {}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@policies/content-length-guardrail/policy-definition.yaml` around lines 109 -
111, The systemParameters object currently defines properties: {} but lacks an
explicit additionalProperties constraint; update the policy-definition.yaml by
adding additionalProperties: false under the systemParameters schema to
explicitly forbid any unknown keys (i.e., modify the systemParameters block so
that the symbol systemParameters contains type: object, properties: {}, and
additionalProperties: false) to match other policies like
azure-content-safety-content-moderation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@policies/content-length-guardrail/policy-definition.yaml`:
- Around line 109-111: The systemParameters object currently defines properties:
{} but lacks an explicit additionalProperties constraint; update the
policy-definition.yaml by adding additionalProperties: false under the
systemParameters schema to explicitly forbid any unknown keys (i.e., modify the
systemParameters block so that the symbol systemParameters contains type:
object, properties: {}, and additionalProperties: false) to match other policies
like azure-content-safety-content-moderation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cbe2b007-3968-4c71-89ab-5acdbc3ee7a2

📥 Commits

Reviewing files that changed from the base of the PR and between d1bc51d and 413aef6.

📒 Files selected for processing (46)
  • policies/analytics-header-filter/go.mod
  • policies/aws-bedrock-guardrail/policy-definition.yaml
  • policies/azure-content-safety-content-moderation/go.mod
  • policies/azure-content-safety-content-moderation/policy-definition.yaml
  • policies/basic-auth/go.mod
  • policies/basic-auth/policy-definition.yaml
  • policies/content-length-guardrail/go.mod
  • policies/content-length-guardrail/policy-definition.yaml
  • policies/cors/go.mod
  • policies/cors/policy-definition.yaml
  • policies/dynamic-endpoint/go.mod
  • policies/host-rewrite/policy-definition.yaml
  • policies/json-schema-guardrail/policy-definition.yaml
  • policies/json-xml-mediator/go.mod
  • policies/llm-cost/go.mod
  • policies/log-message/go.mod
  • policies/mcp-acl-list/go.mod
  • policies/mcp-auth/go.mod
  • policies/mcp-authz/go.mod
  • policies/mcp-rewrite/go.mod
  • policies/model-round-robin/go.mod
  • policies/model-round-robin/policy-definition.yaml
  • policies/model-weighted-round-robin/go.mod
  • policies/model-weighted-round-robin/policy-definition.yaml
  • policies/pii-masking-regex/go.mod
  • policies/pii-masking-regex/policy-definition.yaml
  • policies/prompt-decorator/go.mod
  • policies/prompt-decorator/policy-definition.yaml
  • policies/prompt-template/go.mod
  • policies/prompt-template/policy-definition.yaml
  • policies/regex-guardrail/go.mod
  • policies/regex-guardrail/policy-definition.yaml
  • policies/remove-headers/go.mod
  • policies/request-rewrite/go.mod
  • policies/respond/go.mod
  • policies/semantic-cache/policy-definition.yaml
  • policies/semantic-prompt-guard/policy-definition.yaml
  • policies/semantic-tool-filtering/policy-definition.yaml
  • policies/sentence-count-guardrail/go.mod
  • policies/set-headers/go.mod
  • policies/set-status-code/policy-definition.yaml
  • policies/set-status-code/setstatuscode.go
  • policies/set-status-code/setstatuscode_test.go
  • policies/subscription-validation/go.mod
  • policies/url-guardrail/go.mod
  • policies/word-count-guardrail/go.mod
✅ Files skipped from review due to trivial changes (34)
  • policies/model-round-robin/go.mod
  • policies/analytics-header-filter/go.mod
  • policies/dynamic-endpoint/go.mod
  • policies/url-guardrail/go.mod
  • policies/log-message/go.mod
  • policies/remove-headers/go.mod
  • policies/llm-cost/go.mod
  • policies/regex-guardrail/go.mod
  • policies/subscription-validation/go.mod
  • policies/pii-masking-regex/go.mod
  • policies/azure-content-safety-content-moderation/go.mod
  • policies/model-weighted-round-robin/go.mod
  • policies/aws-bedrock-guardrail/policy-definition.yaml
  • policies/request-rewrite/go.mod
  • policies/mcp-rewrite/go.mod
  • policies/mcp-acl-list/go.mod
  • policies/respond/go.mod
  • policies/cors/go.mod
  • policies/sentence-count-guardrail/go.mod
  • policies/semantic-cache/policy-definition.yaml
  • policies/model-weighted-round-robin/policy-definition.yaml
  • policies/mcp-auth/go.mod
  • policies/mcp-authz/go.mod
  • policies/prompt-template/go.mod
  • policies/model-round-robin/policy-definition.yaml
  • policies/basic-auth/go.mod
  • policies/host-rewrite/policy-definition.yaml
  • policies/word-count-guardrail/go.mod
  • policies/set-headers/go.mod
  • policies/prompt-decorator/go.mod
  • policies/regex-guardrail/policy-definition.yaml
  • policies/set-status-code/policy-definition.yaml
  • policies/json-xml-mediator/go.mod
  • policies/content-length-guardrail/go.mod
🚧 Files skipped from review as they are similar to previous changes (1)
  • policies/set-status-code/setstatuscode.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant