Skip to content
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

Add import route #65

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 121 additions & 0 deletions app/v1/installations/[installationId]/resources/import/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { provisionResource } from "@/lib/partner";
import { readRequestBodyWithSchema } from "@/lib/utils";
import { withAuth } from "@/lib/vercel/auth";
import { resourceImportRequestSchema } from "@/lib/vercel/schemas";

export const POST = withAuth(async (claims, request) => {
const result = await readRequestBodyWithSchema(
request,
resourceImportRequestSchema
);

if (!result.success) {
return Response.json({
error: {
type: "validation_error",
message: "Invalid request body",
},
});
}

const importedResources = [];

for (const resource of result.data.resources) {
const importedResource = await provisionResource(
claims.installation_id,
{
productId: result.data.productId,
name: resource.name,
metadata: {},
billingPlanId: "default",
},
resource.id
);

importedResources.push({
id: importedResource.id,
secrets: buildSecrets(result.data.productId),
status: "ready",
});
}

return Response.json({
resources: importedResources,
});
});

function buildSecrets(
productId: string
): { name: string; value: string; prefix?: string }[] {
switch (productId) {
case "postgres":
return [
{
name: "URL",
prefix: "POSTGRES",
value: "postgres://neon.tech",
},
{
name: "URL_NON_POOLING",
prefix: "POSTGRES",
value: "postgres://neon.tech?non-pooling=true",
},
{
name: "URL_NO_SSL",
prefix: "POSTGRES",
value: "postgres://neon.tech?no-ssl=true",
},
{
name: "PRISMA_URL",
prefix: "POSTGRES",
value: "postgres://neon.tech?prisma=true",
},
{
name: "USER",
prefix: "POSTGRES",
value: "foobar",
},
{
name: "USER",
prefix: "POSTGRES",
value: "foobar",
},
{
name: "PASSWORD",
prefix: "POSTGRES",
value: "password",
},
{
name: "HOST",
prefix: "POSTGRES",
value: "neon.tech",
},
{
name: "DATABASE",
prefix: "POSTGRES",
value: "verceldb",
},
{
name: "CUSTOM_ENV_VAR",
value: "my-secret",
},
];
case "redis":
return [
{ name: "URL", prefix: "KV", value: "redis://upstash.com" },
{ name: "REST_API_URL", prefix: "KV", value: "https://upstash.com" },
{ name: "REST_API_TOKEN", prefix: "KV", value: "foobar-token" },
{
name: "REST_API_READ_ONLY_TOKEN",
prefix: "KV",
value: "https://upstash.com/read-only",
},
{
name: "CUSTOM_ENV_VAR",
value: "my-secret",
},
];
default:
throw new Error(`Unsupported product id '${productId}'`);
}
}
7 changes: 5 additions & 2 deletions lib/partner/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
} from "@/lib/vercel/schemas";
import { kv } from "@vercel/kv";
import { compact } from "lodash";
import { z } from "zod";

const billingPlans: BillingPlan[] = [
{
Expand Down Expand Up @@ -112,14 +113,15 @@ export async function listInstallations(): Promise<string[]> {

export async function provisionResource(
installationId: string,
request: ProvisionResourceRequest
request: ProvisionResourceRequest,
id: string = nanoid()
): Promise<ProvisionResourceResponse> {
const billingPlan = billingPlanMap.get(request.billingPlanId);
if (!billingPlan) {
throw new Error(`Unknown billing plan ${request.billingPlanId}`);
}
const resource = {
id: nanoid(),
id,
status: "ready",
name: request.name,
billingPlan,
Expand All @@ -141,6 +143,7 @@ export async function provisionResource(
{
name: "TOP_SECRET",
value: `birds aren't real (${new Date().toISOString()})`,
prefix: "SUPER",
},
],
};
Expand Down
44 changes: 41 additions & 3 deletions lib/vercel/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { createRemoteJWKSet, jwtVerify } from "jose";
import { env } from "../env";
import { JWTExpired, JWTInvalid } from "jose/errors";
import { createDecipheriv } from "crypto";

export interface OidcClaims {
sub: string;
Expand All @@ -26,7 +27,12 @@ export function withAuth(
): (req: NextRequest, ...rest: any[]) => Promise<Response> {
return async (req: NextRequest, ...rest: any[]): Promise<Response> => {
try {
const token = getAuthorizationToken(req);
const token = await getRequestAuthJWT(req);

if (!token) {
throw new AuthError("Invalid Authorization header, no token found");
}

const claims = await verifyToken(token);

return callback(claims, req, ...rest);
Expand Down Expand Up @@ -71,15 +77,47 @@ export async function verifyToken(token: string): Promise<OidcClaims> {
}
}

function getAuthorizationToken(req: Request): string {
function getRequestAuthJWT(req: Request): string | null {
switch (req.headers.get("x-vercel-auth")) {
case "shared-secret":
return getSharedSecretAuthorizationToken(req);

default:
return getBearerAuthorizationToken(req);
}
}

function getSharedSecretAuthorizationToken(req: Request): string | null {
const token = getBearerAuthorizationToken(req);

if (!token) {
return null;
}

return decryptAuthToken(env.INTEGRATION_CLIENT_SECRET, token);
}

function getBearerAuthorizationToken(req: Request): string | null {
const authHeader = req.headers.get("Authorization");
const match = authHeader?.match(/^bearer (.+)$/i);

if (!match) {
throw new AuthError("Invalid Authorization header");
return null;
}

return match[1];
}

function decryptAuthToken(clientSecret: string, token: string): string {
const [hexIv, hexCipherText] = token.split(".");
const iv = Buffer.from(hexIv, "hex");
const decipher = createDecipheriv(
"aes-192-cbc",
Buffer.from(clientSecret),
iv
);

return decipher.update(hexCipherText, "hex", "utf8") + decipher.final("utf8");
}

class AuthError extends Error {}
19 changes: 18 additions & 1 deletion lib/vercel/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,13 @@ export type ProvisionResourceRequest = z.infer<
>;

export const provisionResourceResponseSchema = resourceSchema.extend({
secrets: z.array(z.object({ name: z.string(), value: z.string() })),
secrets: z.array(
z.object({
name: z.string(),
value: z.string(),
prefix: z.string().optional(),
})
),
});

export type ProvisionResourceResponse = z.infer<
Expand Down Expand Up @@ -532,3 +538,14 @@ export const unknownWebhookEventSchema = webhookEventBaseSchema.extend({
payload: z.unknown(),
unknown: z.boolean().optional().default(true),
});

export type ResourceImportRequest = z.infer<typeof resourceImportRequestSchema>;
export const resourceImportRequestSchema = z.object({
productId: z.string(),
resources: z.array(
z.object({
id: z.string(),
name: z.string(),
})
),
});