Skip to content

refactor: trpc middleware#3008

Closed
chronark wants to merge 4 commits intomainfrom
refactor-trpc-middleware
Closed

refactor: trpc middleware#3008
chronark wants to merge 4 commits intomainfrom
refactor-trpc-middleware

Conversation

@chronark
Copy link
Collaborator

@chronark chronark commented Mar 21, 2025

I wanted to help meg with trpc to make workspaces optional. so she could use it during signup but before the user had a workspace
I got carried a way a little and I’m not sure if this isn’t causing more pain due to merge conflicts 😅

TLDR: this allows to use trpc without the need to have a workspace, but it can optionally be enforced via middleware
all of the middlewares are optional, but they can be stacked and you have full typesafety

export const XXX = t.procedure
  .use(requireUser)
  .use(requireWorkspace)
  .use(withRatelimit(ratelimit.read))

@changeset-bot
Copy link

changeset-bot bot commented Mar 21, 2025

⚠️ No Changeset found

Latest commit: dae5cd9

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

@vercel
Copy link

vercel bot commented Mar 21, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 21, 2025 0:10am
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 21, 2025 0:10am
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 21, 2025 0:10am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
dashboard ⬜️ Ignored (Inspect) Visit Preview Mar 21, 2025 0:10am

@github-actions
Copy link
Contributor

github-actions bot commented Mar 21, 2025

Thank you for following the naming conventions for pull request titles! 🙏

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 21, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This PR streamlines audit logging and workspace management across both the API and dashboard. It removes cache‐related logic and dynamic bucket lookups in favor of a hardcoded bucket value ("unkey_mutations"). UI components have been updated to use simplified string arrays instead of object arrays for bucket identifiers, while the TRPC endpoints now enforce stricter user and workspace validations by replacing the old auth middleware with requireUser/requireWorkspace and by integrating a new rate limiting mechanism. Related database schema changes remove audit log bucket definitions and their relations.

Changes

Files Change Summary
apps/api/src/pkg/audit.ts, apps/dashboard/lib/audit.ts Removed cache logic and bucket lookup in audit log insertion. The bucket is now hardcoded as "unkey_mutations" and the bucketId parameter has been eliminated.
apps/dashboard/app/(app)/audit/... (actions.ts, bucket-filter.tsx, logs-filters/index.tsx, logs-client.tsx, page.tsx) Updated audit log UI components: renamed props from bucketFilter to buckets, changed type from object array to string array, and removed conditional rendering for audit logs.
apps/dashboard/app/api/webhooks/stripe/route.ts Simplified workspace query by removing the nested with clause for auditLogBuckets and updated the parameters passed to insertAuditLogs.
apps/dashboard/app/new/... & multiple apps/dashboard/lib/trpc/routers/... files (api, keys, audit, rbac, stripe, vercel, workspace, etc.) Replaced auth with requireUser/requireWorkspace and incorporated the withRatelimit middleware. Removed passing audit log bucket IDs from logging calls to streamline security and control flow.
internal/db/src/schema/audit_logs.ts, internal/db/src/schema/workspaces.ts, internal/db/src/types.ts Removed audit log bucket definitions, relations, and associated types. Changed bucketId fields to bucket with a default of "unkey_mutations" and removed the workspace relation in audit logs.
apps/dashboard/lib/trpc/context.ts, apps/dashboard/lib/trpc/trpc.ts Simplified context creation by removing redundant workspace retrieval and audit log bucket handling. Introduced new middleware functions and a structured rate limiting mechanism.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant EP as TRPC Endpoint
    participant MW as Middleware Stack (requireUser, requireWorkspace, withRatelimit)
    participant DB as Database / Logger

    U->>EP: Send API request
    EP->>MW: Invoke requireUser (authenticate)
    MW-->>EP: User validated
    EP->>MW: Invoke requireWorkspace (validate workspace)
    MW-->>EP: Workspace validated
    EP->>MW: Apply withRatelimit (rate limiting)
    MW-->>EP: Rate limit check passed
    EP->>DB: Execute procedure & log audit event ("unkey_mutations")
    DB-->>EP: Return response
    EP-->>U: Response delivered
Loading

Possibly related PRs

Suggested labels

Bug, 🕹️ oss.gg, :joystick: 300 points, hacktoberfest

Suggested reviewers

  • mcstepp
  • perkinsjr
  • ogzhanolguncu

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Member

perkinsjr commented Mar 21, 2025

Why would we do this before Auth?

Did we discuss making no major changes to things prior to Auth. Just yesterday.

This changes the fundamental way tRPC works.

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 (4)
apps/dashboard/lib/trpc/trpc.ts (2)

34-61: Remove redundant nullish coalescing operators.

The nullish coalescing operator (??) is redundant in lines 37, 43, 49, and 55 since you already check for the existence of UNKEY_ROOT_KEY in line 34.

  export const ratelimit = env().UNKEY_ROOT_KEY
    ? {
        create: new Ratelimit({
-         rootKey: env().UNKEY_ROOT_KEY ?? "",
+         rootKey: env().UNKEY_ROOT_KEY,
          namespace: "trpc_create",
          limit: 25,
          duration: "3s",
        }),
        read: new Ratelimit({
-         rootKey: env().UNKEY_ROOT_KEY ?? "",
+         rootKey: env().UNKEY_ROOT_KEY,
          namespace: "trpc_read",
          limit: 100,
          duration: "10s",
        }),
        update: new Ratelimit({
-         rootKey: env().UNKEY_ROOT_KEY ?? "",
+         rootKey: env().UNKEY_ROOT_KEY,
          namespace: "trpc_update",
          limit: 25,
          duration: "5s",
        }),
        delete: new Ratelimit({
-         rootKey: env().UNKEY_ROOT_KEY ?? "",
+         rootKey: env().UNKEY_ROOT_KEY,
          namespace: "trpc_delete",
          limit: 25,
          duration: "5s",
        }),
      }
    : {};

63-78: Ensure user exists before accessing its id.

The non-null assertion on ctx.user!.id in line 68 could potentially cause runtime errors if ctx.user is undefined. Consider adding a safety check.

export const withRatelimit = (ratelimit: Ratelimit | undefined) =>
  t.middleware(async ({ next, ctx }) => {
    if (!ratelimit) {
      return next();
    }
+   if (!ctx.user) {
+     throw new TRPCError({ code: "UNAUTHORIZED" });
+   }
    const response = await ratelimit.limit(ctx.user!.id);

    if (!response.success) {
      throw new TRPCError({
        code: "TOO_MANY_REQUESTS",
        message: "Too many requests in the allowed duration. Please try again",
      });
    }

    return next();
  });
apps/dashboard/lib/trpc/routers/audit/fetch.ts (2)

121-121: Consider selective loading of targets.

If the targets relationship is optional, consider a conditional fetch to reduce overhead. For large logs, fetching all targets might become expensive.


101-119:

Details

❓ Verification inconclusive

Ensure indexes match query filters for performance.

This expanded query includes multiple filters (workspaceId, bucket, event, actorId, and time range) with an ordering by id. Confirm that appropriate indexes exist for these columns to keep queries efficient when dealing with large audit logs.

Could you verify the relevant indexes in the schema?


🏁 Script executed:

#!/bin/bash
# Searching for index definitions in the schema regarding columns used in the query: workspaceId, bucket, event, time, createdAt, id
rg --ignore-case 'index.*(workspaceId|bucket|event|time|createdAt|id)' -A 5

Length of output: 37941


Audit Log Query Indexes Verification

  • Verified that the audit log schema defines indexes on the key columns used in the query:
    • workspaceId uses the workspace_id_idx.
    • bucket is indexed via bucket_idx.
    • event is covered by the event_idx.
    • actorId is indexed using actor_id_idx.
    • The predicate on time for cursor pagination leverages the time_idx on the time column.
  • Note: The query’s between filter uses table.createdAt, but the schema appears to index the time column. Please confirm that createdAt either maps to or is aliased with time so that the index effectively supports the filter.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 97703d2 and cec64b8.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (83)
  • apps/api/src/pkg/audit.ts (2 hunks)
  • apps/dashboard/app/(app)/audit/actions.ts (0 hunks)
  • apps/dashboard/app/(app)/audit/components/controls/components/logs-filters/components/bucket-filter.tsx (1 hunks)
  • apps/dashboard/app/(app)/audit/components/controls/components/logs-filters/index.tsx (1 hunks)
  • apps/dashboard/app/(app)/audit/components/logs-client.tsx (1 hunks)
  • apps/dashboard/app/(app)/audit/page.tsx (1 hunks)
  • apps/dashboard/app/api/webhooks/stripe/route.ts (1 hunks)
  • apps/dashboard/app/new/create-ratelimit.tsx (1 hunks)
  • apps/dashboard/app/new/page.tsx (2 hunks)
  • apps/dashboard/lib/audit.ts (3 hunks)
  • apps/dashboard/lib/trpc/context.ts (1 hunks)
  • apps/dashboard/lib/trpc/ratelimitProcedure.ts (0 hunks)
  • apps/dashboard/lib/trpc/routers/api/create.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/api/delete.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/api/keys/llm-search/index.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/api/keys/query-active-keys-timeseries/index.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/api/keys/query-overview-logs/index.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/api/keys/query-overview-timeseries/index.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/api/overview-api-search.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/api/overview/query-overview/index.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/api/overview/query-timeseries/index.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/api/updateDeleteProtection.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/api/updateIpWhitelist.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/api/updateName.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/audit/fetch.ts (3 hunks)
  • apps/dashboard/lib/trpc/routers/audit/llm-search/index.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/audit/schema.ts (4 hunks)
  • apps/dashboard/lib/trpc/routers/key/create.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/key/createRootKey.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/key/delete.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/key/deleteRootKey.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/key/updateEnabled.ts (4 hunks)
  • apps/dashboard/lib/trpc/routers/key/updateExpiration.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/key/updateMetadata.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/key/updateName.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/key/updateOwnerId.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts (3 hunks)
  • apps/dashboard/lib/trpc/routers/key/updateRemaining.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/key/updateRootKeyName.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/logs/llm-search/index.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/logs/query-logs/index.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/logs/query-timeseries/index.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/plain.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/createOverride.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/deleteNamespace.ts (3 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/deleteOverride.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/llm-search/index.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/namespace-search.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/query-latency-timeseries/index.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/query-logs/index.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/query-overview-logs/index.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/query-timeseries/index.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/updateNamespaceName.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/ratelimit/updateOverride.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/rbac.ts (24 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/addPermissionToRootKey.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/connectPermissionToRole.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/connectRoleToKey.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/createPermission.ts (3 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/createRole.ts (4 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/deletePermission.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/deleteRole.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/disconnectPermissionFromRole.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/disconnectRoleFromKey.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/removePermissionFromRootKey.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/updatePermission.ts (3 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/updateRole.ts (3 hunks)
  • apps/dashboard/lib/trpc/routers/rbac/upsertPermission.ts (3 hunks)
  • apps/dashboard/lib/trpc/routers/stripe/cancelSubscription.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/stripe/createSubscription.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/stripe/uncancelSubscription.ts (1 hunks)
  • apps/dashboard/lib/trpc/routers/stripe/updateSubscription.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/vercel.ts (15 hunks)
  • apps/dashboard/lib/trpc/routers/workspace/changeName.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/workspace/create.ts (2 hunks)
  • apps/dashboard/lib/trpc/routers/workspace/optIntoBeta.ts (2 hunks)
  • apps/dashboard/lib/trpc/trpc.ts (1 hunks)
  • internal/db/src/schema/audit_logs.ts (5 hunks)
  • internal/db/src/schema/workspaces.ts (0 hunks)
  • internal/db/src/types.ts (0 hunks)
💤 Files with no reviewable changes (4)
  • apps/dashboard/app/(app)/audit/actions.ts
  • internal/db/src/schema/workspaces.ts
  • internal/db/src/types.ts
  • apps/dashboard/lib/trpc/ratelimitProcedure.ts
🧰 Additional context used
🧠 Learnings (1)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)
Learnt from: chronark
PR: unkeyed/unkey#2146
File: apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts:80-80
Timestamp: 2025-03-19T14:21:17.890Z
Learning: Ensure that audit log descriptions accurately reflect the action being performed, such as updating the `defaultPrefix`, and avoid incorrect references like 'name' when not applicable.
🧬 Code Definitions (69)
apps/dashboard/lib/trpc/routers/logs/llm-search/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/key/updateMetadata.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/api/delete.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/key/createRootKey.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/key/create.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/rbac/connectRoleToKey.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/rbac/updatePermission.ts (2)
apps/dashboard/lib/trpc/trpc.ts (2) (2)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/ratelimit/deleteOverride.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/ratelimit/updateNamespaceName.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/api/overview/query-timeseries/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/api/updateDeleteProtection.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/key/updateExpiration.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/key/updateRootKeyName.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/rbac/disconnectPermissionFromRole.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/logs/query-timeseries/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/workspace/changeName.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/rbac/createPermission.ts (2)
apps/dashboard/lib/trpc/trpc.ts (2) (2)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/api/overview-api-search.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/ratelimit/namespace-search.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/key/updateOwnerId.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/workspace/create.ts (2)
apps/dashboard/lib/trpc/trpc.ts (2) (2)
  • t (7-7)
  • requireUser (9-20)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/stripe/uncancelSubscription.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/env.ts (1) (1)
  • stripeEnv (70-70)
apps/dashboard/lib/trpc/routers/api/create.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/ratelimit/createOverride.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/stripe/cancelSubscription.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/env.ts (1) (1)
  • stripeEnv (70-70)
apps/dashboard/lib/trpc/routers/rbac/deletePermission.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/api/keys/query-overview-timeseries/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/api/updateName.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/api/keys/query-active-keys-timeseries/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/rbac/upsertPermission.ts (3)
apps/dashboard/lib/trpc/context.ts (1) (1)
  • Context (40-40)
internal/db/src/types.ts (1) (1)
  • Permission (22-22)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/key/updateRemaining.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/ratelimit/query-latency-timeseries/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/stripe/createSubscription.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/logs/query-logs/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/rbac/disconnectRoleFromKey.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/key/updateName.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/rbac/addPermissionToRootKey.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/app/api/webhooks/stripe/route.ts (1)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/stripe/updateSubscription.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/ratelimit/query-logs/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/api/keys/llm-search/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/plain.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/ratelimit/query-overview-logs/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/ratelimit/deleteNamespace.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/rbac/deleteRole.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/rbac/updateRole.ts (2)
apps/dashboard/lib/trpc/trpc.ts (2) (2)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/api/overview/query-overview/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/key/deleteRootKey.ts (1)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/trpc/routers/workspace/optIntoBeta.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/app/(app)/audit/components/controls/components/logs-filters/components/bucket-filter.tsx (2)
apps/dashboard/app/(app)/audit/hooks/use-filters.ts (1) (1)
  • useFilters (27-160)
apps/dashboard/components/logs/checkbox/filter-checkbox.tsx (1) (1)
  • FilterCheckbox (49-252)
apps/dashboard/lib/trpc/routers/ratelimit/updateOverride.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/audit/llm-search/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/ratelimit/llm-search/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/app/(app)/audit/page.tsx (1)
apps/dashboard/app/(app)/audit/components/logs-client.tsx (1) (1)
  • LogsClient (24-48)
apps/dashboard/lib/trpc/routers/ratelimit/query-timeseries/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/key/delete.ts (1)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/trpc/routers/api/keys/query-overview-logs/index.ts (1)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/trpc/routers/key/updateEnabled.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/app/new/create-ratelimit.tsx (1)
internal/db/src/types.ts (1) (1)
  • Workspace (10-10)
apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/rbac/connectPermissionToRole.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (2)
apps/dashboard/lib/trpc/trpc.ts (3) (3)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/audit/schema.ts (1)
apps/dashboard/lib/audit.ts (1) (1)
  • AUDIT_LOG_BUCKET (8-8)
apps/dashboard/lib/trpc/routers/vercel.ts (2)
apps/dashboard/lib/trpc/trpc.ts (2) (2)
  • t (7-7)
  • requireUser (9-20)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/trpc.ts (2)
apps/dashboard/lib/trpc/context.ts (1) (1)
  • Context (40-40)
internal/db/src/types.ts (1) (1)
  • Ratelimit (43-43)
apps/dashboard/lib/trpc/routers/rbac/createRole.ts (2)
apps/dashboard/lib/trpc/trpc.ts (2) (2)
  • requireUser (9-20)
  • requireWorkspace (22-32)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
apps/dashboard/lib/trpc/routers/rbac.ts (2)
apps/dashboard/lib/trpc/trpc.ts (5) (5)
  • t (7-7)
  • requireUser (9-20)
  • requireWorkspace (22-32)
  • withRatelimit (63-78)
  • ratelimit (34-61)
apps/dashboard/lib/audit.ts (1) (1)
  • insertAuditLogs (96-137)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Go API Local / Test (Shard 7/8)
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Test Go API Local / Test (Shard 1/8)
  • GitHub Check: Test Packages / Test ./internal/resend
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: Build / Build
🔇 Additional comments (221)
apps/dashboard/lib/trpc/routers/ratelimit/query-logs/index.ts (1)

4-4: Improved middleware implementation with explicit authentication and rate limiting.

The refactoring from rateLimitedProcedure(ratelimit.read) to a chain of specific middleware functions enhances security and clarity. The code now follows a more explicit approach by first requiring user authentication, then workspace validation, and finally applying rate limiting.

This change is part of the broader middleware refactoring effort across the codebase and provides better separation of concerns while maintaining the same functionality. The explicit middleware chain makes the code more maintainable and easier to understand.

Also applies to: 23-26

apps/dashboard/lib/trpc/routers/logs/llm-search/index.ts (2)

2-2: Updated imports to support the new middleware pattern.

The import statement has been updated to include the necessary middleware functions (requireUser, requireWorkspace, withRatelimit) and the TRPC instance (t) to support the new middleware pattern.


13-16: Enhanced security with explicit middleware chain.

The procedure definition has been improved by replacing the previous rateLimitedProcedure with a more explicit middleware chain. This change:

  1. Adds proper user authentication via requireUser
  2. Ensures workspace validation with requireWorkspace
  3. Applies rate limiting specifically for read operations

This enhances security by enforcing proper checks before executing the main procedure logic and aligns with the PR objective of streamlining middleware usage across the application.

apps/dashboard/lib/trpc/routers/ratelimit/deleteNamespace.ts (4)

6-6: Enhanced authentication import structure

The import statement has been updated to include the specific middleware functions requireUser and requireWorkspace from the trpc module, replacing the previous generic auth import. This change improves code clarity by making the specific authentication requirements explicit.


8-9: Improved security with granular middleware approach

Replacing the single auth middleware with separate requireUser and requireWorkspace middlewares is a positive change that:

  1. Enforces explicit user authentication checks
  2. Ensures workspace context validation
  3. Provides more specific error messages when authentication fails
  4. Aligns with separation of concerns principle

This approach enhances security by validating both requirements independently before executing the deletion logic.


46-64: Simplified audit logging implementation

The audit logging call has been simplified by removing the previously required bucket ID parameter. This change:

  1. Streamlines the audit logging process
  2. Centralizes the bucket definition logic within the insertAuditLogs function
  3. Reduces the chance of inconsistent bucket usage across different parts of the application

This change aligns with the PR's goal of removing dynamic bucket lookups in favor of a hardcoded bucket value.


83-108: Consistent audit logging simplification for overrides

The same audit logging simplification has been applied here for recording the deletion of ratelimit overrides. This maintains consistency with the changes made to the earlier audit logging call and ensures uniform audit logging implementation throughout the codebase.

apps/dashboard/lib/trpc/trpc.ts (3)

9-20: Good refactor: Clear and descriptive middleware renaming.

The change from auth to requireUser is more descriptive and clearer about its purpose. The middleware now properly handles both user authentication and tenant context, improving the maintainability of the code.


22-32: Middleware separation improves security and responsibility isolation.

Breaking out the workspace validation into a separate middleware follows the single responsibility principle and allows for more flexible combinations of middleware in TRPC procedures.


3-3: Good addition of rate limiting functionality.

The import and implementation of the Ratelimit class from @unkey/ratelimit provides a solid foundation for protecting your API endpoints from abuse.

apps/dashboard/lib/trpc/routers/ratelimit/namespace-search.ts (1)

2-8:

Details

❓ Verification inconclusive

Good refactoring to use explicit middleware chain

The refactoring improves clarity by breaking down the authentication, workspace validation, and rate limiting into separate middleware functions. This makes the code more maintainable and the requirements more explicit.

However, I noticed that the rate limiting configuration has changed from what was likely ratelimit.update (based on the mutation nature of this endpoint) to ratelimit.read.

Is this intentional? The endpoint is a mutation but is using the read rate limit configuration. You may want to verify that this is the intended behavior.


🏁 Script executed:

#!/bin/bash
# Check if other mutation endpoints are using read rate limits
echo "Checking rate limit configuration for other mutation endpoints..."
rg -A 1 -B 1 "\.mutation" --glob "*.ts" | grep -B 2 "withRatelimit"

Length of output: 208


Action: Verify Rate Limiting Configuration for Mutation Endpoint

The refactored middleware chain is clear and well-structured. However, the endpoint in apps/dashboard/lib/trpc/routers/ratelimit/namespace-search.ts is configured with withRatelimit(ratelimit.read), even though its nature as a mutation suggests that it might require a write-related rate limit (e.g., ratelimit.update). The initial script inspection did not return any evidence from other mutation endpoints, so it's unclear whether this is by design or an oversight.

  • File: apps/dashboard/lib/trpc/routers/ratelimit/namespace-search.ts
  • Snippet:
    export const searchNamespace = t.procedure
      .use(requireUser)
      .use(requireWorkspace)
      .use(withRatelimit(ratelimit.read))

Please verify manually if using ratelimit.read for this mutation is intentional.

apps/dashboard/lib/trpc/routers/logs/query-logs/index.ts (1)

4-26: Improved middleware structure enhances security and clarity

The refactoring from a monolithic procedure to explicit middleware chain is a good improvement. The code now clearly enforces:

  1. User authentication via requireUser
  2. Workspace validation via requireWorkspace
  3. Rate limiting via withRatelimit(ratelimit.read)

This approach makes the security requirements more explicit and enables better error handling by ensuring preconditions are checked in a specific order.

apps/dashboard/lib/trpc/routers/ratelimit/query-overview-logs/index.ts (1)

4-26: Well-structured middleware chain for query procedure

The explicit middleware chain is a good improvement over the previous implementation. This ensures proper authentication, workspace validation, and rate limiting before executing the query logic.

The rate limit configuration using ratelimit.read is appropriate for this query operation, which aligns with the common pattern of having higher limits for read operations compared to write operations.

apps/dashboard/lib/trpc/routers/stripe/uncancelSubscription.ts (2)

4-8: Enhanced authentication with explicit middleware

The refactoring replaces the generic auth middleware with more specific requireUser and requireWorkspace middleware functions. This improves the code by:

  1. Making authentication requirements explicit
  2. Separating user and workspace validation concerns
  3. Providing clearer error messages when either validation fails

This change aligns with the broader TRPC middleware refactoring across the codebase.


9-35: Code structure and error handling improved

The error handling for Stripe environment configuration and the checks for customer and subscription IDs are now properly organized after the middleware validations. This ensures that authentication and workspace checks occur before any business logic is executed.

apps/dashboard/app/new/page.tsx (2)

188-188: Simplified component interface - passing workspace directly

The CreateRatelimit component now receives the workspace object directly without any modifications or extraction of auditLogBucket information. This aligns with the broader refactoring to remove audit log bucket dependencies throughout the application.


221-240: Simplified audit logging parameters

The audit logging call has been refactored to remove the bucketId parameter, now only using workspaceId directly. This is consistent with the PR's goal of standardizing on a hardcoded bucket value ("unkey_mutations") instead of dynamically looking up bucket IDs.

apps/dashboard/lib/trpc/routers/ratelimit/query-latency-timeseries/index.ts (2)

4-4: Updated imports for new middleware approach

The imports now include essential middleware functions (requireUser, requireWorkspace, withRatelimit) and the base TRPC object t, which are needed for the new middleware chain implementation.


9-12: Enhanced procedure with explicit middleware chain

The rateLimitedProcedure has been replaced with a more explicit middleware chain that:

  1. Requires authenticated user validation
  2. Requires workspace context validation
  3. Applies rate limiting with appropriate limits

This change enforces stricter validation before executing the query and makes the authorization requirements clearer and more maintainable.

apps/dashboard/app/new/create-ratelimit.tsx (2)

7-7: Simplified type import

Removed the AuditLogBucket import, as it's no longer needed in the component props.


13-13: Simplified component Props interface

The Props interface has been streamlined to only require a Workspace object, removing the dependency on AuditLogBucket. This is consistent with the PR's goal of simplifying workspace management by eliminating bucket-related data.

apps/dashboard/lib/trpc/routers/workspace/changeName.ts (3)

6-6: Updated imports for new middleware approach

Imported the required middleware functions (requireUser, requireWorkspace) and the base TRPC object t to support the new middleware implementation.


8-9: Enhanced procedure with explicit middleware chain

Replaced the previous auth middleware with a more explicit middleware chain that:

  1. Verifies the user is authenticated with requireUser
  2. Validates workspace context with requireWorkspace

This change enforces proper authentication and context validation before executing the mutation.


32-47: Simplified audit logging implementation

The call to insertAuditLogs has been refactored to remove the dependency on ctx.workspace.auditLogBucket.id, now only requiring the transaction object and audit log details. This aligns with the PR's goal of standardizing on a hardcoded bucket value instead of dynamic bucket lookups.

apps/dashboard/lib/trpc/routers/api/keys/query-overview-logs/index.ts (1)

3-3: Improved security and modularity with explicit middleware chain.

The refactoring replaces the previous rateLimitedProcedure with a more explicit middleware chain that clearly separates concerns:

  1. User authentication with requireUser
  2. Workspace validation with requireWorkspace
  3. Rate limiting with withRatelimit

This approach provides better separation of concerns and makes the authentication flow more readable and maintainable.

Also applies to: 29-32

apps/api/src/pkg/audit.ts (2)

51-51: Simplified service retrieval by removing the unused cache.

The removal of the cache destructuring aligns with the broader refactoring to eliminate cache-related logic for audit log buckets.


61-61: Hardcoded bucket value simplifies audit logging.

Replacing dynamic bucket lookups with the hardcoded "unkey_mutations" value simplifies the audit logging process by:

  1. Eliminating the need for database queries to fetch or create buckets
  2. Reducing potential failure points in the audit logging flow
  3. Making the code more straightforward and easier to reason about

This change aligns with the PR's objective to streamline audit logging across the application.

Also applies to: 79-79

apps/dashboard/lib/trpc/routers/rbac/deleteRole.ts (2)

5-5: Enhanced security with granular middleware.

Replacing the generic auth middleware with specific requireUser and requireWorkspace middlewares provides more explicit control over authentication and authorization requirements.

Also applies to: 7-8


41-41: Simplified audit logging by removing bucket ID parameter.

The call to insertAuditLogs has been simplified by removing the workspace audit log bucket ID parameter, which aligns with the hardcoded bucket approach implemented in apps/api/src/pkg/audit.ts.

apps/dashboard/lib/trpc/routers/api/keys/query-overview-timeseries/index.ts (1)

4-4: Consistent middleware pattern improves security and maintainability.

This change follows the same pattern as other TRPC endpoints in this PR, replacing the previous rateLimitedProcedure with a more explicit middleware chain:

  1. User authentication with requireUser
  2. Workspace validation with requireWorkspace
  3. Rate limiting with withRatelimit

This consistent approach across the codebase enhances maintainability and provides clearer security boundaries.

Also applies to: 9-12

apps/dashboard/lib/trpc/routers/ratelimit/query-timeseries/index.ts (2)

4-4: Updated imports to support the new middleware approach.

The imports have been updated to include the necessary middleware functions (requireUser, requireWorkspace, withRatelimit) and the TRPC instance (t). This aligns with the refactoring effort to standardize middleware usage across TRPC procedures.


8-11: Improved procedure definition with explicit middleware chain.

The procedure has been refactored to use a clear chain of middleware functions instead of the previous rateLimitedProcedure. This change:

  1. Enforces user authentication via requireUser
  2. Validates workspace context via requireWorkspace
  3. Applies rate limiting via withRatelimit

This approach provides better separation of concerns and makes the security requirements more explicit.

apps/dashboard/lib/trpc/routers/stripe/cancelSubscription.ts (3)

4-4: Updated imports to support the new middleware approach.

The imports have been updated to include the necessary middleware functions (requireUser, requireWorkspace) and the TRPC instance (t). This aligns with the refactoring effort to standardize middleware usage across TRPC procedures.


5-8: Enhanced security with explicit middleware chain.

The procedure has been refactored to use a clear chain of middleware functions:

  1. requireUser ensures the user is authenticated before proceeding
  2. requireWorkspace validates that a workspace context exists

This provides better separation of concerns and makes the security requirements more explicit compared to the previous implementation.


9-34: Improved error handling flow in the mutation.

The function body now follows a clear validation sequence:

  1. Verifies Stripe environment configuration
  2. Initializes the Stripe client
  3. Validates workspace Stripe customer ID
  4. Validates workspace subscription ID
  5. Performs the cancellation

This structure ensures all necessary prerequisites are met before attempting to cancel the subscription.

internal/db/src/schema/audit_logs.ts (7)

2-2: Updated import of MySQL table schema components.

The import statement has been updated to include all necessary schema components for the modified table structures.


8-44: Removed auditLogBucket table and relations.

The auditLogBucket table and its relations have been commented out, indicating a shift away from using a separate entity for audit log buckets. This simplifies the database schema by removing an entire table and its relations.


54-56: Simplified bucket handling in audit logs.

The bucketId field has been replaced with a direct bucket field that has a default value of "unkey_mutations". This eliminates the need for foreign key relationships while maintaining bucket categorization functionality.


77-78: Updated indexes for the new bucket field structure.

The index for bucketId has been commented out and replaced with an index for the new bucket field, maintaining query performance for filtering by bucket.


90-94: Removed relation to the audit log bucket table.

The relation between audit logs and bucket entities has been commented out, which is consistent with the removal of the auditLogBucket table.


101-104: Simplified bucket handling in audit log targets.

Similar to the audit log table, the bucketId field in the target table has been replaced with a direct bucket field with a default value of "unkey_mutations". This ensures consistency across related tables.


132-136: Removed relation to the audit log bucket table for targets.

The relation between audit log targets and bucket entities has been commented out, maintaining consistency with the overall schema changes.

apps/dashboard/app/(app)/audit/components/logs-client.tsx (1)

15-15: Simplified the buckets data structure.

The buckets property in WorkspaceProps has been changed from an array of objects { id: string; name: string; }[] to a simple string array string[]. This simplification aligns with the database schema changes and reduces complexity in components that use this data.

apps/dashboard/app/(app)/audit/components/controls/components/logs-filters/index.tsx (1)

39-39: Prop rename aligns with component expectations

The change from bucketFilter={props.buckets} to buckets={props.buckets} properly aligns with the BucketFilter component's updated interface, which now expects a buckets prop containing an array of strings instead of an array of objects.

apps/dashboard/lib/trpc/routers/key/updateMetadata.ts (2)

5-8: Improved security with explicit middleware

The change replaces the generic auth middleware with two more specific middlewares: requireUser and requireWorkspace. This ensures both user authentication and workspace validation before proceeding with the operation.


68-68: Simplified audit logging call

The call to insertAuditLogs has been simplified by removing the workspace audit log bucket ID parameter, which is now handled internally with a hardcoded bucket value.

apps/dashboard/lib/trpc/routers/key/createRootKey.ts (2)

9-16: Enhanced security with explicit middleware

The change replaces the generic auth middleware with specific middlewares: requireUser and requireWorkspace. This provides better separation of concerns and explicit validation of both user authentication and workspace context.


173-173: Streamlined audit logging

The updated insertAuditLogs call simplifies the audit logging process by removing the workspace audit log bucket ID parameter, as bucket handling is now standardized internally.

apps/dashboard/lib/trpc/routers/api/overview/query-overview/index.ts (1)

2-10: More explicit middleware chaining with better security

The refactoring replaces the monolithic rateLimitedProcedure with a modular approach using explicit middleware chaining. The procedure now:

  1. Starts with the base t.procedure
  2. Adds user authentication with requireUser
  3. Validates workspace with requireWorkspace
  4. Applies rate limiting with withRatelimit(ratelimit.read)

This approach provides better separation of concerns and ensures that authentication and workspace validation occur before rate limiting is applied.

apps/dashboard/lib/trpc/routers/key/delete.ts (2)

5-5: Import statement updated for refined middleware approach.

The update changes from using a generic auth middleware to more specific requireUser and requireWorkspace middlewares, which provides clearer separation of concerns.


8-9: Authentication approach refined with specific middleware functions.

Replacing the generic .use(auth) with separate .use(requireUser) and .use(requireWorkspace) middlewares improves security by explicitly validating both user authentication and workspace context before proceeding with deletion operations.

apps/dashboard/lib/trpc/routers/rbac/removePermissionFromRootKey.ts (3)

5-5: Import statement updated for refined middleware approach.

The update changes from using a generic auth middleware to more specific requireUser and requireWorkspace middlewares, which provides clearer separation of concerns.


7-8: Authentication approach refined with specific middleware functions.

Replacing the generic .use(auth) with separate .use(requireUser) and .use(requireWorkspace) middlewares improves security by explicitly validating both user authentication and workspace context before proceeding with permission removal operations.


60-60: Audit logging parameter structure simplified.

The insertAuditLogs call has been updated to directly pass the transaction object without including the workspace audit log bucket ID, which aligns with the new centralized approach using a hardcoded bucket value.

apps/dashboard/app/(app)/audit/page.tsx (1)

16-16: Simplified bucket handling with hardcoded value.

Replacing dynamic bucket selection with a hardcoded ["unkey_mutations"] array simplifies the component logic by removing conditional rendering that previously checked for workspace.auditLogBuckets.length. This change aligns with the broader refactoring to streamline audit logging.

apps/dashboard/lib/trpc/routers/rbac/updatePermission.ts (3)

5-5: Import statement updated for refined middleware approach.

The update changes from using a generic auth middleware to more specific requireUser and requireWorkspace middlewares, which provides clearer separation of concerns.


15-16: Authentication approach refined with specific middleware functions.

Replacing the generic .use(auth) with separate .use(requireUser) and .use(requireWorkspace) middlewares improves security by explicitly validating both user authentication and workspace context before proceeding with permission update operations.


48-48: Audit logging parameter structure simplified.

The insertAuditLogs call has been updated to directly pass the transaction object without including the workspace audit log bucket ID, which aligns with the new centralized approach using a hardcoded bucket value.

apps/dashboard/lib/trpc/routers/api/updateName.ts (2)

7-11: LGTM: Good middleware refactoring

The changes from using a single auth middleware to separate requireUser and requireWorkspace middlewares align with the PR objectives. This provides more granular control over authentication and authorization, enforcing specific checks for both user authentication and workspace validation.


58-76: Audit log implementation simplified

The audit logging implementation has been simplified by removing the dependency on ctx.workspace.auditLogBucket.id and directly passing the transaction object and audit log details. This aligns with the PR's goal of removing dynamic bucket lookups in favor of hardcoded bucket values.

apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2)

6-10: LGTM: Good middleware refactoring

The changes from using a single auth middleware to separate requireUser and requireWorkspace middlewares align with the PR objectives. This provides more granular control, enforcing specific checks for both user authentication and workspace validation.


62-80: Audit log implementation simplified

The audit logging implementation has been simplified by removing the dependency on ctx.workspace.auditLogBucket.id and directly passing the transaction object and audit log details. This aligns with the PR's goal of removing dynamic bucket lookups in favor of hardcoded bucket values.

The audit log description correctly reflects the action being performed, in accordance with the retrieved learning from a previous PR.

apps/dashboard/lib/trpc/routers/audit/schema.ts (4)

1-1: LGTM: Import updated for constant

Updated import to use AUDIT_LOG_BUCKET from "@/lib/audit" instead of DEFAULT_BUCKET_NAME, which aligns with the PR's goal of simplifying bucket management.


42-42: LGTM: Renamed property for consistency

Renamed bucketId to bucket in the AuditLogWithTargets type, which aligns with the PR's goal of simplifying bucket representation using string values instead of object references.


57-57: LGTM: Renamed property for consistency

Renamed bucketId to bucket in the targets array of the AuditLogWithTargets type, maintaining consistency throughout the schema.


71-71: LGTM: Updated default bucket value

Updated the default value for the bucket property to use AUDIT_LOG_BUCKET instead of DEFAULT_BUCKET_NAME, aligning with the PR's goal of using a hardcoded bucket value.

apps/dashboard/lib/trpc/routers/api/delete.ts (2)

6-9: LGTM: Good middleware refactoring

The changes from using a single auth middleware to separate requireUser and requireWorkspace middlewares align with the PR objectives. This provides more granular control over authentication and authorization, enforcing specific checks for both user authentication and workspace validation.


51-69: Audit log implementation simplified

The audit logging implementation has been simplified by removing the dependency on ctx.workspace.auditLogBucket.id and directly passing the transaction object and audit log details. This aligns with the PR's goal of removing dynamic bucket lookups in favor of hardcoded bucket values.

apps/dashboard/lib/trpc/routers/rbac/connectRoleToKey.ts (2)

5-8: Authentication middleware refactored for better separation of concerns.

The change from using a single .auth middleware to separating concerns with .requireUser and .requireWorkspace is a good architectural improvement. This approach more explicitly checks both authentication states and provides clearer error messages based on what's missing.


80-99: Audit logging simplified by removing bucket ID dependency.

The updated insertAuditLogs call no longer requires a separate bucket ID parameter. This is consistent with the PR's objective of streamlining audit logging by using a hardcoded bucket value internally within the insertAuditLogs function.

apps/dashboard/lib/trpc/routers/key/create.ts (2)

7-11: Authentication middleware refactored for better separation of concerns.

The change from using a single .auth middleware to separating concerns with .requireUser and .requireWorkspace improves the security model by making both requirements explicit.


105-120: Audit logging simplified by removing bucket ID dependency.

The updated insertAuditLogs call now correctly uses the simplified interface that doesn't require a bucket ID parameter. This change reduces complexity in the audit logging process.

apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (2)

6-10: Authentication middleware refactored for better separation of concerns.

The change from using a single .auth middleware to separate .requireUser and .requireWorkspace middlewares improves clarity and error handling. Each middleware now has a specific responsibility with distinct error messages.


60-78: Audit logging simplified by removing bucket ID dependency.

The insertAuditLogs call has been updated to use the simplified interface without a bucket ID parameter. This is consistent with the PR's objective to streamline audit logging by using a hardcoded bucket value.

apps/dashboard/lib/trpc/routers/api/create.ts (2)

7-11: Authentication middleware refactored for better separation of concerns.

Replacing the single .auth middleware with separate .requireUser and .requireWorkspace middlewares follows good middleware design principles by enforcing single responsibility.


58-76: Audit logging simplified by removing bucket ID dependency.

The insertAuditLogs function call has been updated to use the simplified interface without the bucket ID parameter. This aligns with the PR's goal of removing cache-related logic and dynamic bucket lookups.

apps/dashboard/app/api/webhooks/stripe/route.ts (1)

60-73: Audit logging parameter simplified correctly.

The modification to insertAuditLogs removes the dependency on workspace audit log buckets, aligning with the PR's objective to streamline audit logging. This change is consistent with the broader refactoring effort that replaces dynamic bucket lookups with a hardcoded bucket value.

apps/dashboard/lib/trpc/routers/key/updateOwnerId.ts (3)

5-5: LGTM - Middleware import updated correctly.

The imports have been updated to include the more granular requireUser and requireWorkspace middlewares that replace the previous auth middleware.


7-8: Enhanced authentication with more granular middleware.

Splitting the previous auth middleware into separate requireUser and requireWorkspace middlewares improves error handling by providing more specific errors based on what's missing from the context (user or workspace).


55-73: Audit logging parameter structure simplified.

The audit logging call has been correctly updated to no longer rely on ctx.workspace.auditLogBucket.id, instead using a simplified structure that directly includes the workspace ID and other necessary information.

apps/dashboard/lib/trpc/routers/key/deleteRootKey.ts (3)

6-6: LGTM - Middleware import updated correctly.

The imports have been correctly updated to include the granular middleware functions.


8-9: Enhanced authentication with more granular middleware.

Replacing the single auth middleware with separate requireUser and requireWorkspace middlewares improves error specificity, making debugging and user communication clearer.


39-57: Audit logging correctly simplified.

The call to insertAuditLogs has been properly updated to align with the simplified audit logging approach across the codebase, removing the dependency on audit log buckets while maintaining all necessary information for comprehensive logging.

apps/dashboard/lib/trpc/routers/rbac/disconnectRoleFromKey.ts (3)

5-5: LGTM - Middleware import updated correctly.

The imports have been updated to include the more specific middleware functions.


7-8: Enhanced authentication with more granular middleware.

The replacement of a single auth middleware with separate requireUser and requireWorkspace middlewares provides better error handling and aligns with the pattern applied consistently across the codebase in this PR.


27-46: Audit logging parameter structure simplified.

The audit logging call has been properly updated to use the simplified parameter structure that no longer depends on bucket IDs, consistent with the changes made throughout the codebase.

apps/dashboard/lib/trpc/routers/ratelimit/updateOverride.ts (2)

6-9: Improved middleware organization

The previous auth middleware has been replaced with more specific requireUser and requireWorkspace middlewares. This change improves the clarity of authorization requirements and aligns with the goal of enforcing stricter user and workspace validations.


69-98: Simplified audit logging implementation

The audit logging implementation has been updated to align with the new pattern used throughout the codebase. The change removes the dependency on the workspace's audit log bucket and now directly passes the workspace ID as part of the log object.

apps/dashboard/lib/trpc/routers/ratelimit/llm-search/index.ts (2)

3-3: Comprehensive middleware imports

The updated imports include all necessary middleware components for user authentication, workspace validation, and rate limiting, making the dependencies more explicit.


15-18: Enhanced procedure definition with explicit middleware chain

The procedure definition has been restructured from using a specialized rateLimitedProcedure to a more explicit approach using t.procedure with individual middleware functions. This change:

  1. Makes the security requirements more transparent
  2. Enforces user authentication first, then workspace presence, followed by rate limiting
  3. Provides better separation of concerns with each middleware handling a specific responsibility

This aligns with the PR objective of enforcing stricter validations in TRPC endpoints.

apps/dashboard/lib/trpc/routers/rbac/connectPermissionToRole.ts (2)

5-8: Improved middleware organization

The previous auth middleware has been replaced with more granular requireUser and requireWorkspace middlewares. This enhances security by explicitly checking for both authenticated users and valid workspaces before executing the procedure.


80-99: Simplified audit logging

The audit logging implementation now follows the new pattern used throughout the codebase, which removes the dependency on workspace audit log buckets and directly incorporates the workspace ID within the log object itself.

apps/dashboard/lib/trpc/routers/ratelimit/createOverride.ts (2)

7-10: Improved authentication and authorization

The authorization mechanism has been enhanced by replacing the generic auth middleware with more explicit requireUser and requireWorkspace middlewares. This change is part of the broader initiative to strengthen validation across TRPC endpoints.


76-98: Consistent audit logging approach

The audit logging implementation follows the simplified pattern established in this PR, which:

  1. Removes dependencies on custom audit log buckets
  2. Directly incorporates workspace identification in the log object
  3. Maintains comprehensive tracking of the action, resources, and context information

This approach streamlines the audit log system while preserving its functionality.

apps/dashboard/lib/trpc/routers/ratelimit/updateNamespaceName.ts (2)

6-6: Improved security with explicit middleware requirements.

The refactoring from a generic auth middleware to specific requireUser and requireWorkspace middleware enhances security by explicitly validating both user authentication and workspace context before executing the procedure.

Also applies to: 9-10


58-58: Streamlined audit logging process.

The audit logging implementation has been simplified by removing the dynamic bucket lookup parameter (ctx.workspace.auditLogBucket.id) and instead using a hardcoded bucket value internally within the insertAuditLogs function.

apps/dashboard/lib/trpc/routers/rbac/createRole.ts (2)

6-6: Improved security with explicit middleware requirements.

The change from a generic auth middleware to specific requireUser and requireWorkspace middleware enhances security by explicitly validating both user authentication and workspace context before role creation.

Also applies to: 16-17


56-56: Streamlined audit logging process.

The audit logging implementation has been simplified by removing the dynamic bucket lookup parameter (ctx.workspace.auditLogBucket.id) previously passed to insertAuditLogs. This aligns with the broader refactoring of using a hardcoded bucket value internally within the function.

Also applies to: 87-87

apps/dashboard/lib/trpc/routers/api/keys/query-active-keys-timeseries/index.ts (1)

3-3: Enhanced security and rate limiting with explicit middleware.

The refactoring from rateLimitedProcedure(ratelimit.read) to a more explicit middleware chain using t.procedure.use(requireUser).use(requireWorkspace).use(withRatelimit(ratelimit.read)) improves security and clarity. This approach:

  1. Explicitly validates user authentication
  2. Ensures workspace context exists
  3. Applies rate limiting with the same configuration as before

The change maintains the same functionality while aligning with the standardized middleware pattern used throughout the codebase.

Also applies to: 8-11

apps/dashboard/lib/trpc/routers/ratelimit/deleteOverride.ts (2)

6-6: Improved security with explicit middleware requirements.

The refactoring from a generic auth middleware to specific requireUser and requireWorkspace middleware enhances security by explicitly validating both user authentication and workspace context before executing the delete operation.

Also applies to: 8-9


60-60: Streamlined audit logging process.

The audit logging implementation has been simplified by removing the dynamic bucket lookup parameter (ctx.workspace.auditLogBucket.id) and instead using a hardcoded bucket value internally within the insertAuditLogs function.

apps/dashboard/lib/trpc/routers/api/overview-api-search.ts (2)

4-4: Updated imports to support the new middleware approach.

The imports have been properly updated to include the necessary middleware functions (requireUser, requireWorkspace, withRatelimit) and utilities (ratelimit, t) from the TRPC module.


6-9: Good refactoring of middleware usage.

The procedure definition has been improved by replacing the monolithic rateLimitedProcedure with a more explicit chain of middleware functions. This change enhances readability and modularity by clearly separating the authentication (requireUser), workspace validation (requireWorkspace), and rate limiting (withRatelimit) concerns.

apps/dashboard/lib/audit.ts (4)

8-8: Good use of a constant for the bucket ID.

Hardcoding the audit log bucket as a constant improves maintainability and ensures consistency across the codebase.


96-99: Function signature simplified by removing the bucketId parameter.

The function signature has been simplified by removing the bucketId parameter, which is now replaced by the AUDIT_LOG_BUCKET constant. This change streamlines the API and ensures consistent bucket usage across the application.


111-111: Using the constant instead of a parameter.

Replacing the parameter with the constant aligns with the overall refactoring goal of simplifying audit logging by using a hardcoded bucket ID.


127-127: Using the constant for bucket ID consistently.

The change ensures consistent use of the AUDIT_LOG_BUCKET constant throughout the function.

apps/dashboard/lib/trpc/routers/api/updateDeleteProtection.ts (3)

7-7: Updated imports for the new middleware approach.

The imports have been updated to use the more granular middleware functions (requireUser, requireWorkspace) instead of the previous auth middleware.


10-11: Improved middleware usage for better authorization control.

Breaking down the general auth middleware into separate requireUser and requireWorkspace middlewares enhances security by ensuring both user authentication and workspace validation are explicitly enforced.


58-81: Updated audit logging call to match the new function signature.

The call to insertAuditLogs has been updated to remove the bucketId parameter, aligning with the changes made to the function in audit.ts. The audit data structure remains well-defined and comprehensive.

apps/dashboard/lib/trpc/routers/workspace/optIntoBeta.ts (3)

5-5: Updated imports for the new middleware approach.

The imports have been updated to use the more granular middleware functions (requireUser, requireWorkspace) instead of the previous auth middleware.


8-9: Improved middleware usage for better authorization control.

Breaking down the general auth middleware into separate requireUser and requireWorkspace middlewares enhances security by ensuring both user authentication and workspace validation are explicitly enforced.


34-49: Updated audit logging call to match the new function signature.

The call to insertAuditLogs has been updated to remove the bucketId parameter, aligning with the changes made to the function in audit.ts. The audit data structure provides comprehensive details about the opt-in action.

apps/dashboard/lib/trpc/routers/plain.ts (2)

2-2: Consolidated Import Statement
This line adds imports for the new middleware-based approach (requireUser, requireWorkspace, withRatelimit). It looks properly structured and consistent with the revised architecture.


10-13: Robust Procedure With Middleware Chain
These lines correctly apply user authentication, workspace checks, and rate limiting in a logical order. This follows best practices for layering security and concurrency constraints. The final mutation logic can count on validated context and rate-limited calls.

apps/dashboard/lib/trpc/routers/workspace/create.ts (3)

8-8: Refined Import Syntax
Importing requireUser and t from the local ../../trpc path is consistent with the new approach. Looks good.


10-10: User Validation Middleware
Replacing older auth checks with .use(requireUser) improves clarity and ensures the user context is properly validated before proceeding with workspace creation logic.


62-62: Consistent Audit Logging
Calling insertAuditLogs here is consistent with the simplified audit log approach. It cleanly captures workspace creation events.

apps/dashboard/lib/trpc/routers/api/keys/llm-search/index.ts (2)

3-3: Import Middleware Utilities
Importing ratelimit, requireUser, requireWorkspace, withRatelimit integrates the refined security and rate-limiting approach.


15-18: LLM Search Procedure
Applying .use(requireUser).use(requireWorkspace).use(withRatelimit(ratelimit.read)) properly enforces authentication, workspace checks, and read-based rate limits prior to query handling.

apps/dashboard/lib/trpc/routers/audit/llm-search/index.ts (2)

3-3: Expanded Import for Middleware
Bringing in ratelimit, requireUser, requireWorkspace, withRatelimit ensures the new pattern of modular checks and constraints is consistently used for audit-related searches.


15-18: Audit Logs Search Procedure
These lines add the combined middlewares for user validation, workspace context, and read operation rate limits, aligning with the new standardized approach. Everything looks correct.

apps/dashboard/lib/trpc/routers/rbac/createPermission.ts (3)

6-6: Clean import refactoring

Good update to import the new middleware functions directly from the trpc module.


16-17: Improved middleware pattern with separation of concerns

The replacement of the single auth middleware with two separate middlewares (requireUser and requireWorkspace) is a good refactoring that separates authentication concerns. This makes the code more explicit about its requirements and improves error handling by providing more specific error messages.


46-65: Simplified audit logging implementation

The audit logging has been streamlined by:

  1. Directly passing the transaction object to insertAuditLogs
  2. Removing the dependency on ctx.workspace.auditLogBucket.id

This change aligns with the PR objective of removing dynamic bucket lookups in favor of a hardcoded bucket value.

apps/dashboard/app/(app)/audit/components/controls/components/logs-filters/components/bucket-filter.tsx (2)

4-8: Simplified props interface

Good change to simplify the props by using a string array (buckets: string[]) instead of an object array. This makes the component easier to use and removes unnecessary complexity.


15-18: Streamlined bucket mapping logic

The mapping logic has been simplified to directly use string values rather than properties from objects. This makes the code more concise and easier to understand.

apps/dashboard/lib/trpc/routers/key/updateRemaining.ts (3)

5-5: Clean import refactoring

Good update to import the new middleware functions directly from the trpc module.


7-8: Improved middleware pattern with separation of concerns

The replacement of the single auth middleware with two separate middlewares (requireUser and requireWorkspace) is a good refactoring that separates authentication concerns. This makes the code more explicit about its requirements and improves error handling.


61-83: Simplified audit logging implementation

The audit logging has been streamlined by:

  1. Directly passing the transaction object to insertAuditLogs
  2. Removing the dependency on audit log bucket IDs
  3. Providing a clearer structure for the audit log data

This change aligns with the PR objective of removing dynamic bucket lookups in favor of a hardcoded bucket value.

apps/dashboard/lib/trpc/routers/key/updateExpiration.ts (3)

5-5: Clean import refactoring

Good update to import the new middleware functions directly from the trpc module.


7-8: Improved middleware pattern with separation of concerns

The replacement of the single auth middleware with two separate middlewares (requireUser and requireWorkspace) follows the same pattern implemented across the codebase. This improves error handling by providing more specific error messages based on whether the user authentication or workspace access fails.


75-97: Simplified audit logging implementation

The audit logging has been streamlined by directly passing the transaction object to insertAuditLogs and removing the dependency on audit log bucket IDs. The code now provides a clearer structure for organizing audit log data.

apps/dashboard/lib/trpc/routers/logs/query-timeseries/index.ts (2)

3-4: Clean and explicit middleware imports

The imports have been updated to include all necessary middleware components from the trpc.ts file, making dependencies clear and explicit.


8-11: Improved middleware chain with better separation of concerns

The procedure now uses a more explicit middleware chain that clearly separates user authentication, workspace validation, and rate limiting. This approach:

  1. Makes the code more maintainable
  2. Creates a consistent pattern across the application
  3. Provides better error clarity (specific error messages for each validation step)

The previous implementation likely used a combined middleware approach, but this granular structure is more flexible and easier to understand.

apps/dashboard/lib/trpc/routers/key/updateName.ts (3)

5-5: Clear middleware imports replacing auth middleware

The imports now explicitly include the specific middleware functions needed, replacing the previous auth middleware with more granular components.


7-8: Enhanced authentication and authorization flow

Replacing the generic auth middleware with separate requireUser and requireWorkspace middlewares improves the validation flow by:

  1. Checking user authentication first
  2. Validating workspace context second
  3. Providing more specific error messages for each validation step

This approach is consistent with the broader refactoring across the application.


54-54: Simplified audit logging

The audit logging call has been updated to use a simpler parameter structure, removing the need to specify the audit log bucket ID. This aligns with the broader change to use a hardcoded bucket value ("unkey_mutations") instead of dynamic bucket lookups.

apps/dashboard/lib/trpc/routers/stripe/updateSubscription.ts (3)

7-7: Explicit middleware imports replacing auth middleware

The imports have been updated to include specific middleware functions, replacing the previous auth middleware with more focused components.


9-10: Improved validation with separate middleware functions

The procedure now uses a more explicit middleware chain that separates:

  1. User authentication (requireUser)
  2. Workspace validation (requireWorkspace)

This approach provides clearer validation steps with specific error messages for each stage of validation.


117-117: Streamlined audit logging

The audit logging call has been simplified by removing the audit log bucket ID parameter. This is part of a broader change to use a hardcoded bucket value rather than dynamic bucket lookups, making the logging process more consistent across the application.

apps/dashboard/lib/trpc/routers/stripe/createSubscription.ts (3)

7-7: Clear middleware imports replacing auth middleware

The imports now explicitly include the specific middleware functions needed, replacing the previous auth middleware with more granular components.


9-10: Improved authentication and validation flow

The procedure now uses separate middleware functions that:

  1. First verify the user is authenticated (requireUser)
  2. Then confirm a valid workspace exists in the context (requireWorkspace)

This separation provides better error handling and follows the consistent pattern established across the application.


103-103: Simplified audit logging parameter structure

The audit logging call has been updated to remove the audit log bucket ID parameter, consolidating the workspace identification within the log entry object. This change is part of a broader simplification in how audit logs are managed throughout the application.

apps/dashboard/lib/trpc/routers/rbac/disconnectPermissionFromRole.ts (2)

5-5: Middleware improvements enhance security through explicit checks

The refactoring from the generic auth middleware to specific requireUser and requireWorkspace middlewares provides more explicit validation. This change ensures both user authentication and workspace context are properly validated before executing the procedure.

Also applies to: 7-8


27-46: Audit logging simplified with consolidated parameters

The audit logging implementation has been improved by consolidating parameters into a single object and removing the dependency on dynamic bucket lookups. This matches the PR's goal of streamlining audit logging across the codebase.

apps/dashboard/lib/trpc/routers/api/overview/query-timeseries/index.ts (1)

3-4: Improved middleware architecture with layered security checks

The refactoring from rateLimitedProcedure to the more modular t.procedure with distinct middleware functions enhances the security flow. This approach ensures that authentication and workspace validation occur before applying rate limiting, which is a more logical sequence of validations.

Also applies to: 7-10

apps/dashboard/lib/trpc/routers/key/updateRootKeyName.ts (2)

5-5: Enhanced procedure security with explicit validation

The refactoring from the generic auth middleware to specific requireUser and requireWorkspace middlewares ensures proper validation of both user authentication and workspace context before proceeding with key operations.

Also applies to: 7-8


48-66: Audit logging simplified with standardized parameters

The implementation now uses a more streamlined approach for audit logging by consolidating parameters into a single object and removing the dependency on dynamic bucket lookups, which aligns with the PR's goal of simplifying the logging process.

apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts (2)

8-8: Enhanced security through explicit middleware checks

The refactoring from a generic authentication middleware to specific requireUser and requireWorkspace middlewares provides more explicit validation steps, ensuring both user authentication and workspace context validation occur before executing the rate limit namespace creation.

Also applies to: 10-11


28-46: Streamlined audit logging with consolidated parameters

The audit logging has been improved by using a more direct approach with consolidated parameters in a single object. This change aligns with the PR's objective of simplifying the audit logging process by removing dynamic bucket lookups.

apps/dashboard/lib/trpc/routers/rbac/addPermissionToRootKey.ts (2)

6-10: Middleware refactor looks good

The changes replace the single auth middleware with more granular requireUser and requireWorkspace middlewares, improving error handling by providing specific error messages based on what's missing (user authentication or workspace context).


66-66: Simplified audit logging interface

The audit logging call has been simplified by removing the ctx.workspace.auditLogBucket.id parameter, which is consistent with the updated insertAuditLogs function signature. This change consolidates the audit log bucket information, eliminating redundancy.

apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts (3)

5-8: Enhanced authorization checks

Replacing the single auth middleware with separate requireUser and requireWorkspace middlewares provides more specific error handling and clearer authorization boundaries. This is a good improvement.


65-65: Audit logging simplification

The audit logging call has been refactored to remove the ctx.workspace.auditLogBucket.id parameter, simplifying the interface and eliminating redundant information.


102-102: Consistent audit logging pattern

The second audit logging call follows the same simplified pattern, maintaining consistency throughout the codebase. This helps reduce complexity and improves maintainability.

apps/dashboard/lib/trpc/routers/rbac/deletePermission.ts (2)

5-8: Improved middleware separation

The separation of user authentication and workspace validation through distinct middleware functions improves error handling and security by providing clear error messages based on what's missing.


37-37: Streamlined audit logging

The audit logging call has been simplified by removing the redundant bucket ID parameter, consistent with the updated function signature in the audit.ts file.

apps/dashboard/lib/trpc/routers/rbac/updateRole.ts (2)

5-5: Properly implemented middleware refactor

The import and usage of the new middleware functions follow the established pattern, enhancing security by explicitly validating both user authentication and workspace existence.

Also applies to: 15-16


40-40: Audit logging standardization

The audit logging interface has been standardized by removing the redundant bucket ID parameter, making the code more consistent and easier to maintain across the codebase.

apps/dashboard/lib/trpc/routers/api/updateIpWhitelist.ts (3)

7-7: Authentication middleware has been refactored.

The import now uses more specific middleware functions (requireUser, requireWorkspace) instead of a generic auth middleware, improving clarity about what authentication requirements are being enforced.


10-11: Enhanced security with explicit middleware separation.

Replacing the previous auth middleware with separate requireUser and requireWorkspace middleware improves security by ensuring both user authentication and workspace validation are explicitly enforced.


84-102: Simplified audit logging implementation.

The audit logging call has been refactored to directly pass a structured object with all necessary properties rather than using the audit log bucket ID. This simplifies the logging process and aligns with the hardcoded bucket approach mentioned in the PR summary.

apps/dashboard/lib/trpc/context.ts (2)

5-5: Simplified import statement.

The import for db has been simplified, removing unnecessary imports that were previously used for audit log bucket handling.


10-15: Streamlined workspace retrieval logic.

The workspace retrieval logic has been significantly simplified by:

  1. Removing the transaction logic
  2. Directly querying for the workspace using orgId
  3. Eliminating audit log bucket handling

This change reduces complexity and potential points of failure in the context creation process.

apps/dashboard/lib/trpc/routers/rbac/upsertPermission.ts (4)

7-11: Function signature updated to accept workspaceId parameter.

The function now accepts a workspaceId parameter directly, rather than relying on extracting it from the context. This improves flexibility and makes the function's dependencies more explicit.


15-21: Query conditions reordered and workspace relation added.

The query has been improved by:

  1. Reordering conditions to check the permission name first
  2. Adding a with clause to include workspace details
  3. Explicitly checking against the provided workspaceId

These changes enhance query precision and provide better context for the returned permission.


37-37: Direct workspaceId assignment.

The workspaceId is now directly assigned from the function parameter instead of being extracted from the context, making the code more straightforward and reducing context dependencies.


54-55: Updated audit logging to use parameter.

The audit logging now uses the workspaceId parameter directly, simplifying the code and reducing context dependencies.

apps/dashboard/lib/trpc/routers/key/updateEnabled.ts (4)

5-8: Enhanced security with explicit middleware.

The implementation now:

  1. Imports specialized middleware functions
  2. Uses requireUser and requireWorkspace instead of generic auth
  3. Explicitly enforces both user authentication and workspace validation

This improves security by ensuring proper validation before execution.


19-23: Improved key query with workspace validation.

The database query has been enhanced to include a check against the workspace ID, ensuring the key belongs to the correct workspace. This adds an important security layer to prevent accessing keys across workspaces.


32-32: Simplified error handling logic.

The key existence check has been simplified to focus solely on whether the key is found, removing unnecessary checks against tenant IDs. This makes the code more maintainable and easier to understand.


55-56: Direct use of workspaceId in audit logging.

The audit logging now directly uses key.workspaceId instead of accessing it through nested properties, streamlining the data being logged and reducing potential points of failure.

apps/dashboard/lib/trpc/routers/audit/fetch.ts (7)

3-3: No impact.


6-6: Approved - consolidated imports.

This import neatly consolidates user, workspace, and rate-limiting capabilities. Good approach.


23-26: Enforcing user & workspace checks plus rate-limiting.

The chain of middlewares is a robust approach to ensure only authorized requests proceed and the read operations are rate-limited.


31-31: Passing workspace context is consistent.

This aligns with the refactored approach to pass the workspace directly to queryAuditLogs. No issues found.


33-33: Pagination logic is well-structured.

Using omitLastItemForPagination clarifies the pagination approach without complicating the main query flow.


123-124: Pagination ordering by ID.

Descending ordering by id plus limit + 1 complements the pagination logic with omitLastItemForPagination.


127-127: Trivial return statement update.

apps/dashboard/lib/trpc/routers/vercel.ts (16)

9-9: Selective import for user-based procedures.

Importing requireUser from ../trpc clarifies the authentication requirement.


12-12: Ensuring user authentication.

Applying .use(requireUser) is a solid step to restrict unauthorized access to setupProject.


76-76: Logging changes for key creation.

Inserting an audit log for the newly created key helps maintain a clear audit trail.


127-127: Tracking integration binding creation.

This audit log ensures creation of the Vercel binding is recorded, improving traceability.


179-179: Audit log for Vercel binding creation.

This step aligns with the consistent logging strategy. No further issues noted.


202-202: User-based access control.

Restricting upsertApiId to authenticated users avoids potential misuse of the endpoint.


258-258: Recording binding updates.

The vercelBinding.update event in the audit log fosters transparency for environment-variable changes.


299-299: Logging new Vercel binding creation.

Consistent usage of insertAuditLogs ensures a thorough audit trail.


321-321: New procedure for upserting root key.

Declaring upsertNewRootKey as a separate procedure improves modularity.


322-322: Mandatory user requirement.

Enforcing .use(requireUser) ensures only authenticated users can insert a new root key.


424-424: Audit log for root key update.

This log event clarifies changes to vercel bindings referencing a key, enabling better debugging.


465-465: Audit log for root key + environment binding creation.

Keeping track of environment references is crucial for diagnosing issues.


496-496: User authorization for unbinding operation.

Using .use(requireUser) prevents unauthorized deletions of Vercel bindings.


531-531: Audit log for Vercel binding deletion.

This fosters accountability and a reliable record of unbinding actions.


550-550: Requiring authentication for disconnecting projects.

Applying .use(requireUser) ensures only valid users can remove a project’s Vercel connections.


588-589: Deleting environment variable references and logging removal.

Combining the .where(...) for the binding ID with insertAuditLogs ensures both the environment variable removal and the associated audit event happen atomically within the same transaction.

apps/dashboard/lib/trpc/routers/rbac.ts (25)

4-4: Unified import for rbac procedures.

Pulling in ratelimit, requireUser, and requireWorkspace from a single import path streamlines the approach.


20-23: Procedure secured and rate-limited.

Chaining user and workspace checks with an update rate limit ensures only authorized, non-flooding requests can modify key permissions.


81-81: Bulk audit logging for new permissions.

Calling insertAuditLogs with a dynamic list of logs helps maintain a robust audit trail.


83-86: Enforced security for removing permissions.

Adding .use(requireUser) and .use(requireWorkspace) ensures only valid requests proceed, while rate-limiting helps prevent brute force attempts.


143-143: Permission-key disconnection audit.

Capturing the removal event in the logs provides an accurate record of authorization changes.


165-168: Restricting role-permission connections.

User+workspace checks plus rate-limiting safeguard RBAC changes from unauthorized access or spam.


221-221: Logging permission-role connection.

The step ensures consistent record-keeping for newly connecting roles to permissions.


243-246: Safe permission-role disconnection.

These middlewares enforce authorized, rate-limited disconnections of roles from permissions.


274-274: Role-permission disconnection logged.

Maintaining a complete log is essential for diagnosing any unauthorized changes.


296-299: Ensuring only authenticated updates for linking roles and keys.

Applying the appropriate middlewares prevents unauthorized or excessive role-key associations.


352-352: Logging role-key connection.

Capturing the linking event keeps an auditable trail for RBAC modifications.


374-377: Enforcing user & workspace checks for role-key disconnection.

Rate-limiting also helps mitigate spamming or accidental repeated requests.


406-409: Restricted role creation flow.

Chaining .use(requireUser).use(requireWorkspace).use(withRatelimit(ratelimit.create)) ensures only authenticated, authorized requests can create new roles, preventing spam or unauthorized expansions of privileges.


436-436: Documenting new role creation details.

Ensuring role.create events are logged adds to the clarity of the security posture.


467-467: Mapping multiple permission creation logs.

Iterating over permission IDs for a bulk audit log insertion is efficient and consistent with the rest of the code.


494-497: Updating roles with controlled, rate-limited access.

The .use() chain assures only authorized, non-excessive role modifications occur.


530-530: Logging role updates.

Maintains a clear history of modifications to roles, facilitating auditing.


547-550: Secured role deletion procedure.

The addition of .use(requireUser), .use(requireWorkspace), .use(withRatelimit(ratelimit.delete)) ensures safe and controlled role removals.


585-585: Role deletion logged.

Recording deletions helps preserve a reliable history for auditing removals of roles.


602-605: Adding permissions behind user & workspace validation.

Similarly applying rate-limiting to the createPermission procedure helps prevent spamming of new permissions.


632-632: Logging newly created permission.

Consistency in logging new permission events fosters complete system traceability.


656-659: Permission updates governed by user, workspace, and rate-limits.

This approach ensures only valid update requests can modify the permission object.


699-699: Capturing permission updates.

It's essential to track changes to permission objects for accountability.


721-724: Restricted permission deletion flow.

Guaranteeing only authenticated, authorized, and rate-limited requests can delete permissions.


762-762: Documenting permission deletion.

By logging deletions, we avoid silently losing track of permission removal events.

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