Skip to content

fix: validate agency namespace for stops #1099

Open
ARCoder181105 wants to merge 1 commit into
OneBusAway:mainfrom
ARCoder181105:fix-1094
Open

fix: validate agency namespace for stops #1099
ARCoder181105 wants to merge 1 commit into
OneBusAway:mainfrom
ARCoder181105:fix-1094

Conversation

@ARCoder181105

@ARCoder181105 ARCoder181105 commented Jun 20, 2026

Copy link
Copy Markdown
Collaborator

Description

Resolves #1094 by ensuring the /stop endpoint strictly validates the requested agency namespace.

Changes Made

  • Validation Added: The handler now verifies that the requested agencyID actually serves the retrieved stop. If the agency does not have any routes serving the stop, it returns a 404 Not Found instead of falsely returning the stop.
  • Orphaned Stop Fallback: Because Maglev's stops table lacks an explicit agency_id column, if a stop has no routes at all, the handler allows retrieval as long as the requested agencyID exists in the database.
  • Test Coverage: Added TestStopHandler_WrongAgency to guarantee that requesting a valid stop under an incorrect or non-existent agency namespace correctly triggers a 404.

Testing

  • Run make test to verify the new TestStopHandler_WrongAgency assertions pass successfully.

Summary by CodeRabbit

  • Bug Fixes
    • Stop endpoint now enforces agency namespace validation. Requests with a non-matching or non-existent agency namespace return 404 Not Found.

@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ARCoder181105, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 42 minutes and 4 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cf448f2c-b1b0-4496-bb0c-668d59298261

📥 Commits

Reviewing files that changed from the base of the PR and between b793a37 and 087afa2.

📒 Files selected for processing (2)
  • internal/restapi/stop_handler.go
  • internal/restapi/stop_handler_test.go
📝 Walkthrough

Walkthrough

stopHandler now validates the requested agency namespace against the agencies found in the stop's associated routes. If routes exist, a non-matching agency returns 404; if no routes exist, the handler checks whether the agency itself exists. A new test TestStopHandler_WrongAgency covers the correct, wrong, and unknown agency cases.

Changes

Agency Namespace Validation for Stop Endpoint

Layer / File(s) Summary
Agency validation logic and tests
internal/restapi/stop_handler.go, internal/restapi/stop_handler_test.go
stopHandler builds uniqueAgencyIDs from route.AgencyID values on the stop's routes and 404s when the requested agency namespace is absent (falling back to checking agency existence when the stop has no routes). TestStopHandler_WrongAgency provisions GTFS records under one agency and asserts 200 for the correct agency namespace and 404 for a mismatched or nonexistent agency namespace.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • burma-shave
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: validate agency namespace for stops' clearly and concisely describes the main change: adding validation for agency namespace when retrieving stops.
Linked Issues check ✅ Passed The PR implementation fully addresses all acceptance criteria from issue #1094: validates that retrieved stops are served by the requested agency, returns 404 for invalid namespaces, and includes the required TestStopHandler_WrongAgency test.
Out of Scope Changes check ✅ Passed All changes are directly related to the linked issue #1094 requirements: agency namespace validation in stopHandler and its corresponding test coverage.

✏️ 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.

@ARCoder181105

Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jun 21, 2026

Copy link
Copy Markdown
✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
internal/restapi/stop_handler_test.go (1)

515-583: ⚡ Quick win

Add a test for the orphan-stop fallback branch (len(routes)==0).

This test only exercises the len(routes) > 0 path. Please add a case where a stop has no associated routes and an existing agency namespace still returns 200, while a non-existent agency returns 404.

Proposed test extension
 func TestStopHandler_WrongAgency(t *testing.T) {
@@
 	// Test 3: Request with an agency that doesn't even exist in the DB -> 404 Not Found
 	respGhost, modelGhost := callAPIHandler[StopEntryResponse](t, api, stopURL(utils.FormCombinedID("GhostAgency", stopID)))
 	require.Equal(t, http.StatusNotFound, respGhost.StatusCode)
 	assert.Equal(t, http.StatusNotFound, modelGhost.Code)
+
+	// Test 4: Orphan stop (no routes) with existing agency namespace -> 200 OK
+	orphanStopID := "OrphanStop"
+	_, err = q.CreateStop(ctx, gtfsdb.CreateStopParams{
+		ID: orphanStopID, Name: nulls.String("Orphan Stop"), Lat: 47.61, Lon: -122.31,
+	})
+	require.NoError(t, err)
+
+	respOrphanValid, modelOrphanValid := callAPIHandler[StopEntryResponse](t, api, stopURL(utils.FormCombinedID(validAgency, orphanStopID)))
+	require.Equal(t, http.StatusOK, respOrphanValid.StatusCode)
+	assert.Equal(t, http.StatusOK, modelOrphanValid.Code)
+
+	// Test 5: Orphan stop with non-existent agency namespace -> 404 Not Found
+	respOrphanGhost, modelOrphanGhost := callAPIHandler[StopEntryResponse](t, api, stopURL(utils.FormCombinedID("GhostAgency", orphanStopID)))
+	require.Equal(t, http.StatusNotFound, respOrphanGhost.StatusCode)
+	assert.Equal(t, http.StatusNotFound, modelOrphanGhost.Code)
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/restapi/stop_handler_test.go` around lines 515 - 583, The
TestStopHandler_WrongAgency test only covers the case where a stop has
associated routes (len(routes) > 0). Add test cases for an orphan stop with no
associated routes by creating a second stop in the test data that is not linked
to any route, trip, or stop_time. Then add test assertions after the existing
three test cases to verify that requesting this orphan stop with an existing
agency namespace (like validAgency) returns 200 OK, and requesting it with a
non-existent agency namespace (like GhostAgency) returns 404 Not Found.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/restapi/stop_handler_test.go`:
- Around line 515-583: The TestStopHandler_WrongAgency test only covers the case
where a stop has associated routes (len(routes) > 0). Add test cases for an
orphan stop with no associated routes by creating a second stop in the test data
that is not linked to any route, trip, or stop_time. Then add test assertions
after the existing three test cases to verify that requesting this orphan stop
with an existing agency namespace (like validAgency) returns 200 OK, and
requesting it with a non-existent agency namespace (like GhostAgency) returns
404 Not Found.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5be52f3e-1e9c-4127-86e8-5c4feea5f713

📥 Commits

Reviewing files that changed from the base of the PR and between 99e138d and b793a37.

📒 Files selected for processing (2)
  • internal/restapi/stop_handler.go
  • internal/restapi/stop_handler_test.go

- Ensure the `/stop` endpoint verifies the requested agency namespace serves the retrieved stop.
- Return 404 Not Found when requesting a valid stop under an incorrect or non-existent agency namespace.
- Add a fallback to allow retrieval of orphaned stops (no associated routes) as long as the requested agency exists.
- Add test coverage for invalid agency and orphaned stop scenarios.
@sonarqubecloud

Copy link
Copy Markdown

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.

spec-gap: Missing Agency Namespace Validation

1 participant