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

Identity Provider/External OAuth #323

Merged
merged 32 commits into from
Dec 1, 2024
Merged
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
2 changes: 2 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"typescript.tsdk": "node_modules/typescript/lib",
"editor.tabSize": 2,
"cSpell.words": [
"Cdfc",
"cjsx",
"clsx",
"cmdk",
Expand Down Expand Up @@ -44,6 +45,7 @@
"pkcco",
"PKCE",
"posthog",
"preconfigured",
"Proxied",
"psql",
"qrcode",
Expand Down
4 changes: 3 additions & 1 deletion apps/backend/.env
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Basic
STACK_BASE_URL=# enter the URL of the backend here. For local development, use `http://localhost:8102`.
STACK_BASE_URL=# the base URL of Stack's backend/API. For local development, this is `http://localhost:8102`; for the managed service, this is `https://api.stack-auth.com`.
NEXT_PUBLIC_STACK_DASHBOARD_URL=# the URL of Stack's dashboard. For local development, this is `http://localhost:8101`; for the managed service, this is `https://app.stack-auth.com`.
STACK_SERVER_SECRET=# enter a secret key generated by `pnpm generate-keys` here. This is used to sign the JWT tokens.

# OAuth mock provider settings
Expand Down Expand Up @@ -37,3 +38,4 @@ STACK_SVIX_API_KEY=# enter the API key for the Svix webhook service here. Use `e
STACK_ACCESS_TOKEN_EXPIRATION_TIME=# enter the expiration time for the access token here. Optional, don't specify it for default value
STACK_SETUP_ADMIN_GITHUB_ID=# enter the account ID of the admin user here, and after running the seed script they will be able to access the internal project in the Stack dashboard. Optional, don't specify it for default value
OTEL_EXPORTER_OTLP_ENDPOINT=# enter the OpenTelemetry endpoint here. Optional, default is `http://localhost:4318`
STACK_NEON_INTEGRATION_CLIENTS_CONFIG=# a list of oidc-provider clients for the Neon integration. If not provided, disables Neon integration
3 changes: 3 additions & 0 deletions apps/backend/.env.development
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
STACK_BASE_URL=http://localhost:8102
NEXT_PUBLIC_STACK_DASHBOARD_URL=http://localhost:8101
STACK_SERVER_SECRET=23-wuNpik0gIW4mruTz25rbIvhuuvZFrLOLtL7J4tyo

STACK_OAUTH_MOCK_URL=http://localhost:8114
Expand Down Expand Up @@ -28,3 +29,5 @@ STACK_SVIX_API_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2NTUxNDA2Mzks
STACK_ARTIFICIAL_DEVELOPMENT_DELAY_MS=100

STACK_ENABLE_HARDCODED_PASSKEY_CHALLENGE_FOR_TESTING=yes

STACK_NEON_INTEGRATION_CLIENTS_CONFIG=[{"client_id": "neon-local", "client_secret": "neon-local-secret", "id_token_signed_response_alg": "ES256", "redirect_uris": ["http://localhost:30000/api/v2/identity/authorize"]}]
2 changes: 2 additions & 0 deletions apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"jose": "^5.2.2",
"next": "^14.2.5",
"nodemailer": "^6.9.10",
"oidc-provider": "^8.5.1",
"openid-client": "^5.6.4",
"oslo": "^1.2.1",
"pg": "^8.11.3",
Expand All @@ -72,6 +73,7 @@
"@simplewebauthn/types": "^11.0.0",
"@types/node": "^20.8.10",
"@types/nodemailer": "^6.4.14",
"@types/oidc-provider": "^8.5.1",
"@types/react": "^18.3.12",
"@types/semver": "^7.5.8",
"concurrently": "^8.2.2",
Expand Down
45 changes: 45 additions & 0 deletions apps/backend/prisma/migrations/20241201043500_idp/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
-- CreateTable
CREATE TABLE "IdPAccountToCdfcResultMapping" (
"idpId" TEXT NOT NULL,
"id" TEXT NOT NULL,
"idpAccountId" UUID NOT NULL,
"cdfcResult" JSONB NOT NULL,

CONSTRAINT "IdPAccountToCdfcResultMapping_pkey" PRIMARY KEY ("idpId","id")
);

-- CreateTable
CREATE TABLE "ProjectWrapperCodes" (
"idpId" TEXT NOT NULL,
"id" UUID NOT NULL,
"interactionUid" TEXT NOT NULL,
"authorizationCode" TEXT NOT NULL,
"cdfcResult" JSONB NOT NULL,

CONSTRAINT "ProjectWrapperCodes_pkey" PRIMARY KEY ("idpId","id")
);

-- CreateTable
CREATE TABLE "IdPAdapterData" (
"idpId" TEXT NOT NULL,
"model" TEXT NOT NULL,
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"payload" JSONB NOT NULL,
"expiresAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "IdPAdapterData_pkey" PRIMARY KEY ("idpId","model","id")
);

-- CreateIndex
CREATE UNIQUE INDEX "IdPAccountToCdfcResultMapping_idpAccountId_key" ON "IdPAccountToCdfcResultMapping"("idpAccountId");

-- CreateIndex
CREATE UNIQUE INDEX "ProjectWrapperCodes_authorizationCode_key" ON "ProjectWrapperCodes"("authorizationCode");

-- CreateIndex
CREATE INDEX "IdPAdapterData_payload_idx" ON "IdPAdapterData" USING GIN ("payload" jsonb_path_ops);

-- CreateIndex
CREATE INDEX "IdPAdapterData_expiresAt_idx" ON "IdPAdapterData"("expiresAt");
40 changes: 40 additions & 0 deletions apps/backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,46 @@ model StandardEmailServiceConfig {

//#endregion

//#region IdP
model IdPAccountToCdfcResultMapping {
idpId String
id String

idpAccountId String @db.Uuid @unique
cdfcResult Json

@@id([idpId, id])
}

model ProjectWrapperCodes {
idpId String
id String @default(uuid()) @db.Uuid

interactionUid String
authorizationCode String @unique

cdfcResult Json

@@id([idpId, id])
}

model IdPAdapterData {
idpId String
model String
id String

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

payload Json
expiresAt DateTime

@@id([idpId, model, id])
@@index([payload(ops: JsonbPathOps)], type: Gin)
@@index([expiresAt])
}
//#endregion

//#region Events

model Event {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { createApiKeySet } from "@/lib/api-keys";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { adaptSchema, clientOrHigherAuthTypeSchema, yupBoolean, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { adaptSchema, adminAuthTypeSchema, yupBoolean, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { apiKeyCrudHandlers } from "./crud";


export const GET = apiKeyCrudHandlers.listHandler;

export const POST = createSmartRouteHandler({
Expand All @@ -11,7 +12,7 @@ export const POST = createSmartRouteHandler({
},
request: yupObject({
auth: yupObject({
type: clientOrHigherAuthTypeSchema,
type: adminAuthTypeSchema,
project: adaptSchema.defined(),
}).defined(),
body: yupObject({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { prismaClient } from "@/prisma-client";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { serverOrHigherAuthTypeSchema, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { generateSecureRandomString } from "@stackframe/stack-shared/dist/utils/crypto";

export const POST = createSmartRouteHandler({
metadata: {
hidden: true,
},
request: yupObject({
url: yupString().defined(),
auth: yupObject({
project: yupObject({
id: yupString().oneOf(["internal"]).defined(),
}).defined(),
type: serverOrHigherAuthTypeSchema.defined(),
}).defined(),
body: yupObject({
interaction_uid: yupString().defined(),
project_id: yupString().defined(),
}).defined(),
}),
response: yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: yupObject({
authorization_code: yupString().defined(),
}).defined(),
}),
handler: async (req) => {
// Create an admin API key for the project
const set = await prismaClient.apiKeySet.create({
data: {
projectId: req.body.project_id,
description: "API key for Neon x Stack Auth integration",
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 100),
superSecretAdminKey: `sak_${generateSecureRandomString()}`,
},
});

// Create authorization code
const authorizationCode = generateSecureRandomString();
await prismaClient.projectWrapperCodes.create({
data: {
idpId: "stack-preconfigured-idp:integrations/neon",
interactionUid: req.body.interaction_uid,
authorizationCode,
cdfcResult: {
access_token: set.superSecretAdminKey,
token_type: "api_key",
project_id: req.body.project_id,
},
},
});

return {
statusCode: 200,
bodyType: "json",
body: {
authorization_code: authorizationCode,
},
};
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { jsonStringSchema, yupNever, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { StackAssertionError } from "@stackframe/stack-shared/dist/utils/errors";
import { redirect } from "next/navigation";

export const GET = createSmartRouteHandler({
metadata: {
hidden: true,
},
request: yupObject({
url: yupString().defined(),
query: yupObject({
client_id: yupString().defined(),
redirect_uri: yupString().defined(),
state: jsonStringSchema.defined(),
code_challenge: yupString().defined(),
code_challenge_method: yupString().oneOf(["S256"]).defined(),
response_type: yupString().oneOf(["code"]).defined(),
}).defined(),
}),
response: yupNever(),
handler: async (req) => {
const url = new URL(req.url);
if (url.pathname !== "/api/v1/integrations/neon/oauth/authorize") {
throw new StackAssertionError(`Expected pathname to be authorize endpoint but got ${JSON.stringify(url.pathname)}`, { url });
}
url.pathname = "/api/v1/integrations/neon/oauth/idp/auth";
url.search = new URLSearchParams({ ...req.query, scope: "openid" }).toString();
redirect(url.toString());
},
});
Loading