Skip to content

Conversation

@ericallam
Copy link
Member

This PR fixes the x-trigger-branch header support for targeting specific preview branches when managing environment variables. The header was documented but not actually being extracted or used in the environment variable API routes. Additionally, the query logic in authenticatedEnvironmentForAuthentication was fundamentally broken—it searched for environments with both slug: "preview" (parent environment property) AND a specific branchName (child environment property), which no environment could satisfy simultaneously. The fix extracts the branch name using branchNameFromRequest() and correctly queries for child branch environments using type: "PREVIEW" and the specific branchName. This ensures that environment variable operations (create, update, get, list) properly target individual preview branches instead of affecting all preview environments.

…utes

This PR fixes the `x-trigger-branch` header support for targeting specific preview branches when managing environment variables. The header was documented but not actually being extracted or used in the environment variable API routes. Additionally, the query logic in `authenticatedEnvironmentForAuthentication` was fundamentally broken—it searched for environments with both `slug: "preview"` (parent environment property) AND a specific `branchName` (child environment property), which no environment could satisfy simultaneously. The fix extracts the branch name using `branchNameFromRequest()` and correctly queries for child branch environments using `type: "PREVIEW"` and the specific `branchName`. This ensures that environment variable operations (create, update, get, list) properly target individual preview branches instead of affecting all preview environments.
@changeset-bot
Copy link

changeset-bot bot commented Nov 19, 2025

⚠️ No Changeset found

Latest commit: 055b078

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 19, 2025

Walkthrough

This change implements branch-aware environment authentication across the API layer. The updates include: adding branchNameFromRequest imports to multiple API route files and passing extracted branch information to authenticatedEnvironmentForAuthentication calls; extending the authenticatedEnvironmentForAuthentication signature to accept an additional branchName parameter; implementing branch name sanitization in apiAuth.server.ts with conditional logic that falls back to slug-based environment lookup when the sanitized branch is falsy; and extending sanitizeBranchName in gitBranch.ts to accept undefined inputs and recognize additional git ref prefixes (tags, pull, merge, release).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~35 minutes

  • Branch sanitization fallback logic in apiAuth.server.ts: Verify the conditional guard correctly handles falsy sanitized branches and that slug-based lookups function as intended.
  • Consistency across authentication paths: Ensure branch handling is mirrored correctly in both personalAccessToken and organizationAccessToken branches.
  • Ref prefix expansion in sanitizeBranchName: Validate that all new ref prefix patterns (refs/tags/, refs/pull/, refs/merge/, refs/release/) are correctly processed and that the null guard for unknown refs/ formats behaves as expected.
  • Undefined input handling: Confirm that the widened function signature gracefully handles undefined inputs throughout the call chain.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description is largely incomplete. It lacks the required Testing section describing test steps, the Changelog section with a short description of changes, and the initial issue reference (Closes #). The checklist items are also not marked. Add the missing sections: include 'Closes #' with the issue number at the start, fill in the Testing section with test steps, add a Changelog section, mark the completed checklist items, and optionally add screenshots if applicable.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title accurately describes the main change: fixing preview branch targeting in environment variable API routes by supporting the x-trigger-branch header.
✨ 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/editing-branch-env-vars

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

🧹 Nitpick comments (3)
apps/webapp/app/v3/gitBranch.ts (1)

32-43: Clarify behavior for invalid refs/* inputs in sanitizeBranchName

The updated sanitizeBranchName correctly handles more ref prefixes and undefined input. Note that it also returns null for any unrecognized refs/* value, which means callers that treat !sanitizedBranch as “no branch provided” will silently ignore such headers and fall back to slug-based behavior. If distinguishing “no branch” from “invalid branch header” would be useful (e.g., to return a 4xx instead of silently falling back), consider returning a separate sentinel or throwing in that case.

apps/webapp/app/services/apiAuth.server.ts (2)

500-556: Preview branch lookup for personal access tokens: behavior & assumptions

The new sanitizedBranch flow for personalAccessToken looks sound and addresses the previous slug+branch mismatch:

  • When branch is missing or sanitization returns null, you fall back to the existing slug-based query (including the dev + orgMember.userId filter), preserving current behavior.
  • When sanitizedBranch is truthy, you query by { projectId, type: "PREVIEW", branchName: sanitizedBranch, archivedAt: null } and require a parentEnvironment, which correctly targets child preview environments instead of the parent “preview” slug.

Two points to double‑check:

  1. Branch uniqueness assumption – Because the branch lookup ignores slug/parent, it relies on branchName being unique per project across all preview environments. If that’s not guaranteed, it may be safer to also constrain on parentEnvironment.slug === slug (or another parent identifier).
  2. Invalid refs/* headers – For unknown refs/* formats sanitizeBranchName returns null, so these headers are treated the same as “no branch” and will hit the slug-based environment instead of failing. Confirm this is intentional for envvar APIs; otherwise you might want to surface a 4xx error instead of silently ignoring a malformed branch header.

Overall, the fix matches the PR intent of targeting individual preview branches instead of all preview environments.


579-627: Organization token branch lookup mirrors PAT logic; consider small refactor

The organizationAccessToken branch handling mirrors the PAT case: sanitize, fall back to slug when falsy, and otherwise query { projectId, type: "PREVIEW", branchName: sanitizedBranch, archivedAt: null } with the same parentEnvironment checks. That keeps behavior consistent across token types and fixes the same slug+branch issue for org tokens.

Given the near‑identical logic in the two cases, you could extract a small helper (e.g., findPreviewEnvironmentByBranch(projectId, slug, sanitizedBranch)), which would reduce duplication and centralize any future tweaks to preview-branch lookup behavior.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between abee783 and 055b078.

📒 Files selected for processing (6)
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.ts (2 hunks)
  • apps/webapp/app/routes/api.v1.projects.$projectRef.background-workers.$envSlug.$version.ts (2 hunks)
  • apps/webapp/app/routes/api.v1.projects.$projectRef.envvars.$slug.$name.ts (3 hunks)
  • apps/webapp/app/routes/api.v1.projects.$projectRef.envvars.$slug.ts (3 hunks)
  • apps/webapp/app/services/apiAuth.server.ts (4 hunks)
  • apps/webapp/app/v3/gitBranch.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-05T15:32:41.553Z
Learnt from: myftija
Repo: triggerdotdev/trigger.dev PR: 2464
File: apps/webapp/app/services/projectSettings.server.ts:210-0
Timestamp: 2025-09-05T15:32:41.553Z
Learning: In the ProjectSettingsService.updateGitSettings method in apps/webapp/app/services/projectSettings.server.ts, when productionBranch or stagingBranch parameters are undefined, the method intentionally writes empty objects to clear existing branch configurations. This is the desired behavior, not a bug.

Applied to files:

  • apps/webapp/app/v3/gitBranch.ts
  • apps/webapp/app/services/apiAuth.server.ts
📚 Learning: 2025-09-03T14:35:52.384Z
Learnt from: myftija
Repo: triggerdotdev/trigger.dev PR: 2464
File: apps/webapp/app/utils/pathBuilder.ts:144-146
Timestamp: 2025-09-03T14:35:52.384Z
Learning: In the trigger.dev codebase, organization slugs are safe for URL query parameters and don't require URL encoding, as confirmed by the maintainer in apps/webapp/app/utils/pathBuilder.ts.

Applied to files:

  • apps/webapp/app/services/apiAuth.server.ts
🧬 Code graph analysis (5)
apps/webapp/app/routes/api.v1.projects.$projectRef.envvars.$slug.ts (1)
apps/webapp/app/services/apiAuth.server.ts (1)
  • branchNameFromRequest (283-285)
apps/webapp/app/routes/api.v1.projects.$projectRef.envvars.$slug.$name.ts (1)
apps/webapp/app/services/apiAuth.server.ts (1)
  • branchNameFromRequest (283-285)
apps/webapp/app/routes/api.v1.projects.$projectRef.background-workers.$envSlug.$version.ts (1)
apps/webapp/app/services/apiAuth.server.ts (1)
  • branchNameFromRequest (283-285)
apps/webapp/app/routes/api.v1.projects.$projectRef.$env.ts (2)
apps/webapp/app/env.server.ts (1)
  • env (1246-1246)
apps/webapp/app/services/apiAuth.server.ts (1)
  • branchNameFromRequest (283-285)
apps/webapp/app/services/apiAuth.server.ts (1)
apps/webapp/app/v3/gitBranch.ts (1)
  • sanitizeBranchName (32-44)
⏰ 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). (23)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (5, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (8, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (7, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (6, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (5, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (2, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (4, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (6, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (3, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (4, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (8, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (1, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (7, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (1, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (3, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (2, 8)
  • GitHub Check: units / packages / 🧪 Unit Tests: Packages (1, 1)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
apps/webapp/app/routes/api.v1.projects.$projectRef.envvars.$slug.ts (1)

4-8: Branch header correctly threaded into envvar list/create handlers

Importing branchNameFromRequest and passing it as the 4th argument to authenticatedEnvironmentForAuthentication in both action and loader cleanly enables branch-aware envvar operations while preserving existing behavior when the header is absent (branch is undefined and the auth helper falls back to slug-based lookup). Looks consistent with the updated helper signature.

Also applies to: 29-35, 77-82

apps/webapp/app/routes/api.v1.projects.$projectRef.$env.ts (1)

5-9: Consistent branch-aware environment lookup for project env endpoint

Passing branchNameFromRequest(request) into authenticatedEnvironmentForAuthentication aligns this route with the new branch-aware auth behavior and keeps the non-branch case unchanged. Wiring looks correct and consistent with other routes.

Also applies to: 33-38

apps/webapp/app/routes/api.v1.projects.$projectRef.background-workers.$envSlug.$version.ts (1)

4-8: Background worker loader now participates in branch-aware env resolution

Using branchNameFromRequest(request) as the 4th parameter to authenticatedEnvironmentForAuthentication aligns this route with the new preview-branch behavior so background workers can be fetched per branch. The change is minimal and consistent with the other updated routes.

Also applies to: 30-35

apps/webapp/app/routes/api.v1.projects.$projectRef.envvars.$slug.$name.ts (1)

5-9: Per-variable envvar routes correctly wired for preview branch targeting

Importing branchNameFromRequest and passing it into authenticatedEnvironmentForAuthentication in both action and loader ensures that create/update/delete and read of a specific env var are all scoped to the correct preview branch when x-trigger-branch is present, while preserving existing slug-only behavior when it isn’t. This matches the changes in the list/create envvar route.

Also applies to: 31-36, 108-113

@matt-aitken matt-aitken merged commit 4347499 into main Nov 19, 2025
31 checks passed
@matt-aitken matt-aitken deleted the fix/editing-branch-env-vars branch November 19, 2025 18:01
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.

3 participants