-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
feat(database,rbac): add multiple environment API key foundations #4388
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
carderne
wants to merge
5
commits into
main
Choose a base branch
from
feat/multi-keys-foundations
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
af05aea
fix(core,sdk): correct public token expirationTime docs
carderne e15a789
feat(database,rbac): add multiple environment API key foundations
carderne 0d0f794
refactor(rbac): make API key policy methods optional on the controller
carderne 51e1189
fix(webapp): use _sk_ additional API key infix
carderne 89167bc
add changeset
carderne File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@trigger.dev/core": patch | ||
| --- | ||
|
|
||
| Expose helpers for identifying public JWTs and reading their subject claim. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@trigger.dev/sdk": patch | ||
| --- | ||
|
|
||
| Correct the `expirationTime` docs on `auth.createPublicToken` and the trigger-token helpers: a number is a Unix timestamp in seconds, not milliseconds. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import { describe, expect, test } from "vitest"; | ||
| import { | ||
| apiKeyPrefix, | ||
| generateAdditionalApiKey, | ||
| generateRootApiKey, | ||
| hashApiKey, | ||
| obfuscateApiKey, | ||
| } from "./apiKeys"; | ||
|
|
||
| describe("API key utilities", () => { | ||
| test.each([ | ||
| ["DEVELOPMENT", "tr_dev_"], | ||
| ["STAGING", "tr_stg_"], | ||
| ["PRODUCTION", "tr_prod_"], | ||
| ["PREVIEW", "tr_preview_"], | ||
| ] as const)("generates %s keys", (environmentType, prefix) => { | ||
| const root = generateRootApiKey(environmentType); | ||
| const additional = generateAdditionalApiKey(environmentType); | ||
|
|
||
| expect(root.apiKey).toMatch(new RegExp(`^${prefix}[A-Za-z0-9]{24}$`)); | ||
| expect(root.keyHash).toBe(hashApiKey(root.apiKey)); | ||
| expect(root.lastFour).toBe(root.apiKey.slice(-4)); | ||
| expect(additional.apiKey).toMatch(new RegExp(`^${prefix}sk_[A-Za-z0-9]{24}$`)); | ||
| expect(additional.keyHash).toBe(hashApiKey(additional.apiKey)); | ||
| expect(additional.lastFour).toBe(additional.apiKey.slice(-4)); | ||
| expect(apiKeyPrefix(environmentType)).toBe(prefix); | ||
| expect(obfuscateApiKey(environmentType, root.lastFour)).toBe( | ||
| `${prefix}••••••••${root.lastFour}` | ||
| ); | ||
| expect(obfuscateApiKey(environmentType, additional.lastFour, "additional")).toBe( | ||
| `${prefix}sk_••••••••${additional.lastFour}` | ||
| ); | ||
| }); | ||
|
|
||
| test("generates unique keys", () => { | ||
| const keys = new Set( | ||
| Array.from({ length: 100 }, () => generateAdditionalApiKey("PRODUCTION").apiKey) | ||
| ); | ||
|
|
||
| expect(keys.size).toBe(100); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import { createHash } from "node:crypto"; | ||
| import type { RuntimeEnvironmentType } from "@trigger.dev/database"; | ||
| import { customAlphabet } from "nanoid"; | ||
|
|
||
| const apiKeyId = customAlphabet( | ||
| "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", | ||
| 24 | ||
| ); | ||
|
|
||
| export function hashApiKey(apiKey: string): string { | ||
| return createHash("sha256").update(apiKey, "utf8").digest("hex"); | ||
| } | ||
|
|
||
| function generatedApiKey(apiKey: string) { | ||
| return { | ||
| apiKey, | ||
| keyHash: hashApiKey(apiKey), | ||
| lastFour: apiKey.slice(-4), | ||
| }; | ||
| } | ||
|
|
||
| export function generateRootApiKey(environmentType: RuntimeEnvironmentType) { | ||
| // Root keys intentionally use the same 24-character entropy as additional keys. | ||
| return generatedApiKey(`${apiKeyPrefix(environmentType)}${apiKeyId()}`); | ||
| } | ||
|
|
||
| export function generateAdditionalApiKey(environmentType: RuntimeEnvironmentType) { | ||
| return generatedApiKey(`${apiKeyPrefix(environmentType)}sk_${apiKeyId()}`); | ||
| } | ||
|
|
||
| export function apiKeyPrefix(environmentType: RuntimeEnvironmentType): string { | ||
| switch (environmentType) { | ||
| case "DEVELOPMENT": | ||
| return "tr_dev_"; | ||
| case "STAGING": | ||
| return "tr_stg_"; | ||
| case "PRODUCTION": | ||
| return "tr_prod_"; | ||
| case "PREVIEW": | ||
| return "tr_preview_"; | ||
| } | ||
| } | ||
|
|
||
| export function obfuscateApiKey( | ||
| environmentType: RuntimeEnvironmentType, | ||
| lastFour: string, | ||
| kind: "root" | "additional" = "root" | ||
| ): string { | ||
| const discriminator = kind === "additional" ? "sk_" : ""; | ||
| return `${apiKeyPrefix(environmentType)}${discriminator}••••••••${lastFour}`; | ||
| } | ||
30 changes: 30 additions & 0 deletions
30
...packages/database/prisma/migrations/20260723112558_add_environment_api_keys/migration.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| -- CreateTable | ||
| CREATE TABLE "public"."api_keys" ( | ||
| "id" TEXT NOT NULL, | ||
| "name" TEXT NOT NULL, | ||
| "key_hash" TEXT NOT NULL, | ||
| "last_four" TEXT NOT NULL, | ||
| "runtime_environment_id" TEXT NOT NULL, | ||
| "created_by_user_id" TEXT, | ||
| "preset_id" TEXT, | ||
| "scopes" TEXT[] NOT NULL, | ||
| "last_used_at" TIMESTAMP(3), | ||
| "revoked_at" TIMESTAMP(3), | ||
| "expires_at" TIMESTAMP(3), | ||
| "updated_at" TIMESTAMP(3) NOT NULL, | ||
| "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
|
|
||
| CONSTRAINT "api_keys_pkey" PRIMARY KEY ("id") | ||
| ); | ||
|
|
||
| -- CreateIndex | ||
| CREATE UNIQUE INDEX "api_keys_key_hash_key" ON "public"."api_keys"("key_hash"); | ||
|
|
||
| -- CreateIndex | ||
| CREATE INDEX "api_keys_runtime_environment_id_revoked_at_created_at_idx" ON "public"."api_keys"("runtime_environment_id", "revoked_at", "created_at" DESC); | ||
|
|
||
| -- AddForeignKey | ||
| ALTER TABLE "public"."api_keys" ADD CONSTRAINT "api_keys_runtime_environment_id_fkey" FOREIGN KEY ("runtime_environment_id") REFERENCES "public"."RuntimeEnvironment"("id") ON DELETE CASCADE ON UPDATE CASCADE; | ||
|
|
||
| -- AddForeignKey | ||
| ALTER TABLE "public"."api_keys" ADD CONSTRAINT "api_keys_created_by_user_id_fkey" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."User"("id") ON DELETE SET NULL ON UPDATE CASCADE; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import type { PrismaClient } from "@trigger.dev/database"; | ||
| import { describe, expect, it, vi } from "vitest"; | ||
|
|
||
| // The API-key policy methods are OPTIONAL on RoleBaseAccessController so a | ||
| // plugin compiled against an older OSS commit still satisfies the contract | ||
| // (the plugin is built against whichever OSS source its base image carries). | ||
| // LazyController is what turns that partial surface into a total one, and these | ||
| // tests pin the defaults it substitutes — in particular that a missing | ||
| // prepareApiKeyPolicy fails CLOSED rather than resolving to full access. | ||
| // | ||
| // A stand-in for the cloud plugin, which isn't installed in this repo. The | ||
| // factory supplies the specifier, so no real module has to resolve. | ||
| vi.mock("@triggerdotdev/plugins/rbac", () => ({ | ||
| default: { | ||
| create: () => ({ | ||
| // Deliberately omits apiKeyPresets / prepareApiKeyPolicy / | ||
| // describeApiKeyPolicy — this is a pre-contract plugin. | ||
| isUsingPlugin: async () => true, | ||
| }), | ||
| }, | ||
| })); | ||
|
|
||
| const prismaPlaceholder = {} as unknown as PrismaClient; | ||
|
|
||
| describe("LazyController API-key policy defaults (plugin predates the contract)", () => { | ||
| async function controller() { | ||
| const loader = (await import("./index.js")).default; | ||
| const instance = loader.create(prismaPlaceholder); | ||
| // Guard against a silent fallback: if the mock didn't take, these | ||
| // assertions would be checking the fallback's real implementations. | ||
| await expect(instance.isUsingPlugin()).resolves.toBe(true); | ||
| return instance; | ||
| } | ||
|
|
||
| it("reports no preset catalogue rather than throwing", async () => { | ||
| await expect((await controller()).apiKeyPresets("org_123")).resolves.toBeNull(); | ||
| }); | ||
|
|
||
| it("refuses to prepare a policy — including FULL_ACCESS", async () => { | ||
| const result = await ( | ||
| await controller() | ||
| ).prepareApiKeyPolicy({ | ||
| organizationId: "org_123", | ||
| presetId: "FULL_ACCESS", | ||
| }); | ||
|
|
||
| // The critical assertion: absence must never resolve to `{ ok: true }` with | ||
| // an admin scope. A plugin below the contract cannot mint any credential. | ||
| expect(result.ok).toBe(false); | ||
| expect(result).not.toHaveProperty("policy"); | ||
| }); | ||
|
|
||
| it("describes a policy as having nothing extra to show", async () => { | ||
| await expect( | ||
| (await controller()).describeApiKeyPolicy({ presetId: "TRIGGER_ONLY", scopes: ["read:runs"] }) | ||
| ).resolves.toEqual({}); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.