Skip to content

feat: Allow production environment to access Swagger UI for testing#45

Merged
taiphanvan2k3 merged 1 commit intomainfrom
fix/allow-production-environment-to-access-swagger
Nov 14, 2025
Merged

feat: Allow production environment to access Swagger UI for testing#45
taiphanvan2k3 merged 1 commit intomainfrom
fix/allow-production-environment-to-access-swagger

Conversation

@taiphanvan2k3
Copy link
Copy Markdown
Member

@taiphanvan2k3 taiphanvan2k3 commented Nov 14, 2025

Summary by CodeRabbit

  • Chores
    • API documentation is now accessible across all deployment environments.

@taiphanvan2k3 taiphanvan2k3 self-assigned this Nov 14, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Nov 14, 2025

Walkthrough

Swagger documentation registration is now unconditional in the HTTP request pipeline. The environment-specific check that previously restricted Swagger to Development has been removed, enabling API documentation endpoints in all environments.

Changes

Cohort / File(s) Summary
HTTP Pipeline Configuration
src/Web.Api/Program.cs
Removed environment-specific conditional guard from Swagger middleware registration; UseSwagger and UseSwaggerUI now execute in all deployment environments

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Considerations for review:
    • Verify that exposing Swagger documentation in Production and other non-Development environments aligns with organizational security policies
    • Confirm no authentication/authorization guards are needed for the Swagger endpoints in production deployments
    • Check for any related configuration or environment variable controls that may have been intended

Poem

🐰 A swagger in every place,
No environment to hide its face,
Documentation flows so free,
Hopping through all environments with glee!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: enabling Swagger UI access in production environments. It accurately reflects the core modification visible in the PR—removing environment-specific Swagger restrictions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/allow-production-environment-to-access-swagger

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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a36378d and db6555b.

📒 Files selected for processing (1)
  • src/Web.Api/Program.cs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-and-deploy

Comment thread src/Web.Api/Program.cs
Comment on lines +52 to +54
// Allow Production environment to access the Swagger UI for testing purposes
app.UseSwagger();
app.UseSwaggerUI();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

Security risk: Exposing Swagger UI in production enables information disclosure.

Enabling Swagger UI in production reveals your complete API structure, endpoints, parameters, and validation rules to potential attackers. This degrades your security posture and violates industry best practices.

The comment mentions "testing purposes"—production should not be used for testing. Consider these alternatives:

  1. Use a dedicated staging/testing environment (recommended)
  2. Conditionally enable based on configuration:
-// Allow Production environment to access the Swagger UI for testing purposes
-app.UseSwagger();
-app.UseSwaggerUI();
+if (app.Environment.IsDevelopment() || builder.Configuration.GetValue<bool>("EnableSwagger"))
+{
+    app.UseSwagger();
+    app.UseSwaggerUI();
+}
  1. Protect with authentication if production access is absolutely necessary:
app.UseSwagger();
app.UseSwaggerUI(options =>
{
    options.ConfigObject.AdditionalItems["onComplete"] = "() => { ui.preauthorizeApiKey('Bearer', 'your-token'); }";
});
// Then add authorization policies to Swagger endpoints

Is exposing Swagger in production a permanent requirement? If so, what security controls are planned to protect it?


🏁 Script executed:

#!/bin/bash
# Examine the Program.cs file to see actual content around lines 52-54
# and check for any environment checks or authentication
fd -e "Program.cs" -t f | head -5

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Get content around lines 52-54 to verify the claim
if [ -f "src/Web.Api/Program.cs" ]; then
  sed -n '40,70p' "src/Web.Api/Program.cs" | cat -n
fi

Length of output: 1071


🏁 Script executed:

#!/bin/bash
# Search for any Swagger-related configuration, authentication, or conditionals
rg -n "Swagger|swagger" --type cs -C 5 "src/Web.Api/Program.cs" || echo "File not found or no matches"

Length of output: 1022


🏁 Script executed:

#!/bin/bash
# Check if there's an environment check on UseSwagger/UseSwaggerUI
rg -n "UseSwagger|UseSwaggerUI" --type cs -C 3

Length of output: 435


🏁 Script executed:

#!/bin/bash
# Look for authorization middleware that might protect Swagger
rg -n "Authorization|Authentication|Middleware" --type cs -C 2 "src/Web.Api/Program.cs" || echo "Checking codebase"

Length of output: 634


🏁 Script executed:

#!/bin/bash
# Search for any configuration or conditional logic related to Swagger
rg -n "IsDevelopment|Environment|Configuration|GetValue" --type cs -C 2 | grep -A 2 -B 2 -i swagger || echo "No environment conditionals found for Swagger"

Length of output: 256


🏁 Script executed:

#!/bin/bash
# Check git history to see if Swagger was previously conditional
git log -p --all -- "src/Web.Api/Program.cs" | grep -A 10 -B 10 "UseSwagger" | head -50 || echo "Git history unavailable"

Length of output: 59



---

🌐 Web query:

```web
Swagger OpenAPI security best practices production environment

💡 Result:

Short checklist of OpenAPI/Swagger security best practices for production:

  • Don’t publicly expose docs/UI unless required — disable Swagger UI and/or the OpenAPI JSON in prod (or serve only on secured/staging hosts). [4][6]
  • If you must expose, protect access with strong authentication (OIDC/OAuth2, mTLS, or at minimum basic auth) and IP or VPN restrictions. [5][2]
  • Disable or restrict “Try it out” (supportedSubmitMethods = [] or equivalent) so the UI can’t execute requests against your live APIs. Also disable withCredentials/CORS use in the UI. [1][3]
  • Do not allow loading remote specs via URL params (prevent ?url abuse) — remove/disable that feature or patch Swagger UI. [3]
  • Hide or limit sensitive schema details: avoid publishing internal endpoints, admin/debug operations, implementation details or example secrets in the OpenAPI spec. Treat the spec as sensitive inventory. [2]
  • Enforce strong API-level controls: robust authn/authz, per-endpoint & per-object authorization checks, input validation, rate limiting and quotas. (Follow OWASP API Security Top 10.) [2]
  • Keep Swagger UI and libraries up-to-date; monitor CVEs (SSRF and other fixes have been released). [3]
  • Disable automatic validation against public validators and remove any client-side credentials propagation features that could leak tokens. [1][3]
  • Log and monitor usage of docs endpoints and “Try it out” executions; include alerts for abnormal activity. [2]
  • Bake deployment checks into CI/CD (ensure docs are disabled or protected in prod) and maintain an inventory of exposed API docs/versions. [6][2]

If you want, I can produce concrete config snippets for your stack (Spring/fastapi/Express/.NET) or a small CI check that fails deploy when docs are enabled in prod.


🌐 Web query:

OWASP API security Swagger UI exposure risks

💡 Result:

Short summary of risks when Swagger UI / OpenAPI docs are exposed (mapped to OWASP API risks) and concise mitigations.

Risks

  • Increased attack surface / endpoint discovery — exposes all routes, parameters, request/response shapes and example data that make API1/API3/API9 exploitation easier. [1][4]
  • Sensitive-data leakage — example requests/responses or inline secrets in spec files can reveal PII, API keys, admin endpoints. (API3/Improper Assets). [1][4]
  • Security misconfiguration & information disclosure — default or misconfigured Swagger/hosting plugins can accidentally serve files or internal assets (e.g., Fastify CVE). [1][3]
  • Client-side attacks (XSS, spoofing, SSRF) — past swagger-ui vulnerabilities allowed XSS, spoofing or SSRF that can hijack sessions or leak tokens. [2][6][9]
  • Automation and abuse — public docs enable automated scanning/enumeration and credential stuffing or abuse of sensitive business flows (API4/API6). [1][4]

High-level mitigations (practical)

  • Don’t publish docs publicly in production — restrict access to trusted networks or auth (VPN, IP allowlist, SSO/mTLS). [1][4]
  • Require authentication & least privilege for the docs UI and the underlying /openapi.json (OAuth2, API gateway auth, short-lived tokens). [1][4]
  • Remove sensitive examples & sample secrets from specs; sanitize responses/examples before publishing. [1][4]
  • Harden Swagger UI deployment: keep libraries/plugins updated, follow vendor security notes, set secure plugin options (e.g., Fastify baseDir), and disable remote-spec loading. [2][3][6]
  • Reduce disclosure: serve minimal public specs (only public endpoints), use endpoint-level authorization checks (object/property-level auth), and disable "Try it out" in production. [1][4]
  • Monitor & rate-limit access to docs and API endpoints; log accesses and alert on unusual enumeration patterns. [1]
  • Automate discovery/testing: scan your domains for exposed swagger/openapi endpoints and fix exposures. [4]

If you want, I can:

  • scan your domain for common Swagger/OpenAPI endpoints (safe, non-destructive) and return findings; or
  • produce a short checklist/config snippets for securing Swagger UI on a specific stack (Springfox/Swagger-UI, Fastify, Express, etc.).

Sources: OWASP API Top 10 (2023) [1]; Swagger UI XSS advisory (example) [2]; CVE-2024-22207 analysis (fastify-swagger-ui disclosure) [3]; public scanners / exposed-endpoint guidance (APIDetector/RedPacket) [4].


🌐 Web query:

ASP.NET Core Swagger authentication authorization middleware order

💡 Result:

Short answer — order matters. Recommended pipeline (minimal, with Swagger + auth):

app.UseSwagger();
app.UseSwaggerUI(...);

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints => endpoints.MapControllers());

Rationale/notes

  • UseAuthentication() must run before UseAuthorization() because authentication populates HttpContext.User that authorization uses. [1]
  • Swagger/SwaggerUI are static/UI middleware that can be added before routing (they just serve the generated JSON/UI assets). The Swashbuckle samples put UseSwagger/UseSwaggerUI before UseRouting. [2]
  • If you want the generated /swagger/v1/swagger.json or the UI itself protected, explicitly protect those endpoints (e.g., map the swagger JSON under an endpoint with RequireAuthorization or add middleware to block it) or configure Swagger UI OAuth settings (OAuth client/redirect) so the UI can obtain tokens. See examples for configuring Swagger UI OAuth/OIDC. [2][3]

Sources

  • ASP.NET Core middleware guidance (ordering, auth before authorization). [1]
  • Swashbuckle / Microsoft sample showing UseSwagger/UseSwaggerUI placement. [2]
  • Examples configuring Swagger UI OAuth/authorization (protecting APIs, OAuth redirect config). [3]

🌐 Web query:

industry standards disabling Swagger UI production environment

💡 Result:

Short answer

  • Best practice: do not expose Swagger UI (or the raw OpenAPI JSON) in production unless you intentionally publish interactive docs for a public API. Instead disable or restrict it and keep only a hardened, authenticated docs endpoint if needed. [1][2][3][7]

Why (industry reasoning)

  • UI + open schema can leak endpoint details, example data and auth hints that help attackers. Swagger/ui has had real-world XSS and remote-loading vulnerabilities. Keeping it reachable increases attack surface. [4][5][10]

Concrete controls widely used

  1. Disable mounting the UI and/or openapi.json in production (framework feature flags/profiles). Examples: Spring profiles or property toggles; FastAPI docs_url/openapi_url=None. [2][1][7]
  2. If docs needed in non-public prod: require strong authentication (SAML/OAuth2), IP allowlists, VPN or private network. [6]
  3. Remove or sanitize examples/credentials from OpenAPI files; avoid embedding secrets. [6]
  4. Keep swagger-ui and dependencies up to date and monitor advisories (GHSA/CVEs). Apply security patches promptly. [4][5][10]
  5. Use runtime controls: feature flags, env-based conditionals, and CI checks to prevent accidental enablement in prod. [2][3]

Quick implementation references

  • Spring Boot / SpringDoc: use @Profile or @ConditionalOnExpression to avoid loading Swagger beans in prod. [2]
  • FastAPI: set docs_url=None, redoc_url=None and openapi_url=None to disable endpoints. [7]
  • Verify by removing endpoints (e.g., /swagger-ui.html, /docs, /openapi.json) from prod routes and testing. [1][7]

References
[1] Baeldung — How to Turn Off Swagger-UI in Production.
[2] Spring Boot tutorials / examples for disabling Swagger in production.
[3] FastAPI docs/examples for disabling Swagger UI and OpenAPI endpoint.
[4] Snyk vulnerability writeups on swagger-ui XSS.
[5] GitHub/GHSA advisories on swagger-ui remote-loading/XSS; Ed‑Fi advisory recommending not using Swagger in production.

(If you want, I can fetch direct links or sample code for your stack — tell me which framework.)


Security risk: Exposing Swagger UI in production violates industry best practices and enables information disclosure.

Exposing Swagger UI in production increases attack surface by making all endpoints, parameters, and request/response shapes discoverable. The current code enables this unconditionally with no authentication protecting the /swagger endpoints.

Industry best practice is to not expose Swagger UI or OpenAPI JSON in production unless you intentionally publish interactive docs for a public API. If Swagger UI must be exposed, it should be protected with strong authentication (OAuth2, SAML, mTLS, or at minimum basic auth) and IP or VPN restrictions.

The code comment mentions "testing purposes"—production should not be used for testing. Consider these alternatives:

  1. Use a dedicated staging/testing environment (recommended)
  2. Conditionally enable based on environment:
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
  1. Protect with authentication if production access is absolutely necessary:
app.MapGet("/swagger/index.html", () => Results.Redirect("/swagger/"))
    .RequireAuthorization("AdminPolicy");

If production Swagger access is a requirement, what security controls are planned to protect it?

@taiphanvan2k3 taiphanvan2k3 merged commit eabc176 into main Nov 14, 2025
3 checks passed
@taiphanvan2k3 taiphanvan2k3 deleted the fix/allow-production-environment-to-access-swagger branch November 14, 2025 08:32
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