You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Provide access keys used for a SSL connection #1673
I would like to use a ssl protected db with my application, which is deployed on Zeit Now. I am not sure how to get my p12 and my .pem file into the serverless function though.
I fount this issue: vercel/vercel#749 , but I think it's not possible that way, since we can't combine env vars
changed the title [-]Explain how to provide access keys used for a ssl connection[/-][+]Provide access keys used for a SSL connection[/+]on Mar 13, 2020
Just posting here to bump this back up the priority level.
This was quite a pain to hack around and will be a problem for almost anyone needing to use Prisma in production with a serverless environment.
I am using CloudSQL with SSL from Google Cloud for my database and Vercel (like OP) for my deployment provider. This is how I hacked around it for now:
I store both the server-ca.pem and client-identity.p12 in ENV variables (this gets tricky with the .p12 file and requires some base64 encoding) and then before the Prisma client is initialised I write them to the /tmp folder which is available to vercel deployments:
import { tmpdir } from 'os'
import fs from 'fs'
fs.writeFile(
`${tmpdir()}/server-ca.pem`,
process.env.CLIENT_CERTIFICATE,
err => {
if (err) return console.log(err)
}
)
fs.writeFile(
`${tmpdir()}/client-identity.p12`,
process.env.CLIENT_IDENTITY,
//important to re-encode it correctly
'base64',
err => {
if (err) return console.log(err)
}
)
...
global.prisma = new PrismaClient()
NOTE: Once you have encoded the client-identity.p12 into base64 it will exceed the size limit for ENVs in Vercel so you need to follow the guide mentioned here to encrypt it and then decrypt it before writing the file to disk.
For completeness here is my context.js where I initialise the Prisma client:
import { PrismaClient } from '@prisma/client'
import { tmpdir } from 'os'
import fs from 'fs'
import crypto from 'crypto'
// nextjs dev server reloads files on page navigation, so new Prisma Clients were being spawned everytime
let prisma
if (!global.prisma) {
if (process.env.NODE_ENV !== 'development') {
fs.writeFile(
`${tmpdir()}/server-ca.pem`,
process.env.CLIENT_CERTIFICATE,
err => {
if (err) return console.log(err)
}
)
const algorithm = 'aes-128-cbc'
const decipher = crypto.createDecipheriv(
algorithm,
process.env.CLIENT_IDENTITY_KEY,
process.env.CLIENT_IDENTITY_IV
)
const getDecryptedSecret = () => {
let decrypted = decipher.update(
process.env.ENCRYPTED_CLIENT_IDENTITY,
'base64',
'utf8'
)
decrypted += decipher.final('utf8')
return decrypted
}
fs.writeFile(
`${tmpdir()}/client-identity.p12`,
getDecryptedSecret(),
'base64',
err => {
if (err) return console.log(err)
}
)
}
global.prisma = new PrismaClient({})
}
prisma = global.prisma
export default prisma
Reacted by Björn Rave, MasonHM, Daniel Salvadori, Luis Alfredo Lorenzo and Nitesh Srivats
Reacted by Björn Rave, Stephane Leandre Paul, dewildio, Andrea Dito, Ovidiu Bodea, Facundo Martin Gordillo, MasonHM, Rafael T. Ballestiero, Andy Young, Luis Alfredo Lorenzo and 3 more
So I think just being able to read the secrets from environment variables would cut out a lot of the hassle. The main point of fragility to me is that I have to write to an OS dependant temp folder (/tmp) and then reference that in my connection string.
This has several drawbacks:
If Vercel ever changes which OS their serverless environments use my connection will fail. Not super likely but not something I should need to know about.
I only need to do this in production and not locally which means if it fails I might not catch it.
It also just kinda feels gross to be writing to the file system of a serverless environment.
You are right about the size limit though. I believe that's an upstream limit so it's likely coming from Amazon or whichever infrastructure they use and could effect other serverless platforms. But the solution I outlined above works well enough to get around that.
Being able to reference the certificates from a .env file in the connection string would take at least part of the problem away. If I could do this for instance:
For the other part of the issue of accepting a certificate's content as an environment variable. We probably won't support this workflow directly, but recommend using the workaround @danhollick suggested. The main reason is that it's easy enough to create a library in userland for handling this and environment variables have size limits.
If we get burned by /tmp not being writable in some serverless environment or enough people want this feature, we may revisit.
Closing, but happy to re-open if this workflow doesn't work for you. Thanks!
For the other part of the issue of accepting a certificate's content as an environment variable. We probably won't support this workflow directly, but recommend using the workaround #1673 (comment). The main reason is that it's easy enough to create a library in userland for handling this and environment variables have size limits.
If we get burned by /tmp not being writable in some serverless environment or enough people want this feature, we may revisit.
I really want that feature. Look at the workaround, it is definitely not a maintainable solution and requires quite a lot of unnecessary blumbing, googling and banging head against the wall.
Using many resources posted in this thread (especially that by @danhollick) I created a project that helps get large environment variables into Vercel deployments in a somewhat elegant way that can be community maintained. I'm using it at my organization to get my Remix app deployed in Vercel to connect to a Google Cloud SQL instance (MySQL) via Prisma. I'll drop it here in case it can help anyone else or maybe others can find their way to it to improve it's reach.
Just posting here to bump this back up the priority level.
This was quite a pain to hack around and will be a problem for almost anyone needing to use Prisma in production with a serverless environment.
I am using CloudSQL with SSL from Google Cloud for my database and Vercel (like OP) for my deployment provider. This is how I hacked around it for now:
I store both the server-ca.pem and client-identity.p12 in ENV variables (this gets tricky with the .p12 file and requires some base64 encoding) and then before the Prisma client is initialised I write them to the /tmp folder which is available to vercel deployments:
import { tmpdir } from 'os'
import fs from 'fs'
fs.writeFile(
`${tmpdir()}/server-ca.pem`,
process.env.CLIENT_CERTIFICATE,
err => {
if (err) return console.log(err)
}
)
fs.writeFile(
`${tmpdir()}/client-identity.p12`,
process.env.CLIENT_IDENTITY,
//important to re-encode it correctly
'base64',
err => {
if (err) return console.log(err)
}
)
...
global.prisma = new PrismaClient()
NOTE: Once you have encoded the client-identity.p12 into base64 it will exceed the size limit for ENVs in Vercel so you need to follow the guide mentioned here to encrypt it and then decrypt it before writing the file to disk.
For completeness here is my context.js where I initialise the Prisma client:
import { PrismaClient } from '@prisma/client'
import { tmpdir } from 'os'
import fs from 'fs'
import crypto from 'crypto'
// nextjs dev server reloads files on page navigation, so new Prisma Clients were being spawned everytime
let prisma
if (!global.prisma) {
if (process.env.NODE_ENV !== 'development') {
fs.writeFile(
`${tmpdir()}/server-ca.pem`,
process.env.CLIENT_CERTIFICATE,
err => {
if (err) return console.log(err)
}
)
const algorithm = 'aes-128-cbc'
const decipher = crypto.createDecipheriv(
algorithm,
process.env.CLIENT_IDENTITY_KEY,
process.env.CLIENT_IDENTITY_IV
)
const getDecryptedSecret = () => {
let decrypted = decipher.update(
process.env.ENCRYPTED_CLIENT_IDENTITY,
'base64',
'utf8'
)
decrypted += decipher.final('utf8')
return decrypted
}
fs.writeFile(
`${tmpdir()}/client-identity.p12`,
getDecryptedSecret(),
'base64',
err => {
if (err) return console.log(err)
}
)
}
global.prisma = new PrismaClient({})
}
prisma = global.prisma
export default prisma
it's much easier to just store the cert like this in the file:
Just posting here to bump this back up the priority level.
This was quite a pain to hack around and will be a problem for almost anyone needing to use Prisma in production with a serverless environment.
I am using CloudSQL with SSL from Google Cloud for my database and Vercel (like OP) for my deployment provider. This is how I hacked around it for now:
I store both the server-ca.pem and client-identity.p12 in ENV variables (this gets tricky with the .p12 file and requires some base64 encoding) and then before the Prisma client is initialised I write them to the /tmp folder which is available to vercel deployments:
import { tmpdir } from 'os'
import fs from 'fs'
fs.writeFile(
`${tmpdir()}/server-ca.pem`,
process.env.CLIENT_CERTIFICATE,
err => {
if (err) return console.log(err)
}
)
fs.writeFile(
`${tmpdir()}/client-identity.p12`,
process.env.CLIENT_IDENTITY,
//important to re-encode it correctly
'base64',
err => {
if (err) return console.log(err)
}
)
...
global.prisma = new PrismaClient()
NOTE: Once you have encoded the client-identity.p12 into base64 it will exceed the size limit for ENVs in Vercel so you need to follow the guide mentioned here to encrypt it and then decrypt it before writing the file to disk.
For completeness here is my context.js where I initialise the Prisma client:
import { PrismaClient } from '@prisma/client'
import { tmpdir } from 'os'
import fs from 'fs'
import crypto from 'crypto'
// nextjs dev server reloads files on page navigation, so new Prisma Clients were being spawned everytime
let prisma
if (!global.prisma) {
if (process.env.NODE_ENV !== 'development') {
fs.writeFile(
`${tmpdir()}/server-ca.pem`,
process.env.CLIENT_CERTIFICATE,
err => {
if (err) return console.log(err)
}
)
const algorithm = 'aes-128-cbc'
const decipher = crypto.createDecipheriv(
algorithm,
process.env.CLIENT_IDENTITY_KEY,
process.env.CLIENT_IDENTITY_IV
)
const getDecryptedSecret = () => {
let decrypted = decipher.update(
process.env.ENCRYPTED_CLIENT_IDENTITY,
'base64',
'utf8'
)
decrypted += decipher.final('utf8')
return decrypted
}
fs.writeFile(
`${tmpdir()}/client-identity.p12`,
getDecryptedSecret(),
'base64',
err => {
if (err) return console.log(err)
}
)
}
global.prisma = new PrismaClient({})
}
prisma = global.prisma
export default prisma
This saved me quite some time, thank you @danhollick!
Earlier this year, Vercel increased the limit for environment variables to 64KB from 5KB so the base64 encoded client identity (~3.5KB in my case) can be directly used.
Adding the commands to create the client identity p12 file and encode it in base64 below to save a little time Googling it.
Can confirm this thread is still relevant. I'm using NextJS and tRPC deployed on Vercel, and Postgres hosted on Google CloudSQL. I adapted @danhollick's code (thanks Dan!) to work with SSL certificates and took advantage of the recently increased environment variable size limits to store the certificates in base64 before decoding them back into .pem files and storing them in tmp.
The code I used:
// Function to write the decoded content to a file
function writeDecodedFile(filename: string, base64Content: string) {
const filePath = `${tmpdir()}/${filename}`;
const contentBuffer = Buffer.from(base64Content, 'base64');
console.log(filePath)
fs.writeFile(filePath, contentBuffer, (err) => {
if (err) {
console.log(`Error writing ${filename}:`, err);
} else {
console.log(`${filename} successfully written to temp directory`);
}
});
}
if (process.env.NODE_ENV === "production"){
// Decode and write client-cert.pem
if (process.env.CLIENT_CERT_BASE64) {
writeDecodedFile('client-cert.pem', process.env.CLIENT_CERT_BASE64);
} else {
console.log('CLIENT_CERT_BASE64 environment variable is not set.');
}
// Decode and write client-key.pem
if (process.env.CLIENT_KEY_BASE64) {
writeDecodedFile('client-key.pem', process.env.CLIENT_KEY_BASE64);
} else {
console.log('CLIENT_KEY_BASE64 environment variable is not set.');
}
// Decode and write server-ca.pem
if (process.env.SERVER_CA_BASE64) {
writeDecodedFile('server-ca.pem', process.env.SERVER_CA_BASE64);
} else {
console.log('SERVER_CA_BASE64 environment variable is not set.');
}
}
DATABASE_URL as deployed on Vercel: postgresql://USER:PASSWORD@PUBLIC_IP:POST/DB_NAME?sslmode=require&sslcert=/tmp/client-cert.pem&sslkey=/tmp/client-key.pem&sslrootcert=/tmp/server-ca.pem
Also key here is to configure a new authorized network on the SQL deployment with the IP set to 0.0.0.0/0, which allows any public IP to access the database (as long as they have the SSL certificates! Which is what we provided with ^).
To access the database in my local environment I just use cloud sql proxy.
Activity
pantharshit00 commentedon Feb 21, 2020
Hi @BjoernRave,
Right now this is not possible as we allow some SSL only to be a file path. I went ahead and opened the spec issue to change the behaviour: https://github.com/prisma/specs/issues/428
After that, you should be able to generate a large connection string that can have the contents of the files in it.
If you don't want a large connection string, you can pass one to the client directly like so:
But, I also went ahead and created a specs issue for templating support: https://github.com/prisma/specs/issues/429
So you will need to wait while we work on the above-mentioned things.
[-]Explain how to provide access keys used for a ssl connection[/-][+]Provide access keys used for a SSL connection[/+]danhollick commentedon Jun 21, 2020
Just posting here to bump this back up the priority level.
This was quite a pain to hack around and will be a problem for almost anyone needing to use Prisma in production with a serverless environment.
I am using CloudSQL with SSL from Google Cloud for my database and Vercel (like OP) for my deployment provider. This is how I hacked around it for now:
I store both the
server-ca.pemandclient-identity.p12in ENV variables (this gets tricky with the .p12 file and requires some base64 encoding) and then before the Prisma client is initialised I write them to the/tmpfolder which is available to vercel deployments:Then my database url for production looks like :
NOTE: Once you have encoded the
client-identity.p12into base64 it will exceed the size limit for ENVs in Vercel so you need to follow the guide mentioned here to encrypt it and then decrypt it before writing the file to disk.For completeness here is my
context.jswhere I initialise the Prisma client:1 remaining item
danhollick commentedon Aug 27, 2020
Hey @matthewmueller
So I think just being able to read the secrets from environment variables would cut out a lot of the hassle. The main point of fragility to me is that I have to write to an OS dependant temp folder (/tmp) and then reference that in my connection string.
This has several drawbacks:
You are right about the size limit though. I believe that's an upstream limit so it's likely coming from Amazon or whichever infrastructure they use and could effect other serverless platforms. But the solution I outlined above works well enough to get around that.
matthewmueller commentedon Aug 27, 2020
@danhollick thanks for taking the time to explain the problem better. I definitely can feel the concern about fragility.
I feel like I'm still missing a piece of the issue though.
Given the following Prisma schema:
In development you have:
In production you have:
I see this as being somewhat acceptable because the production
DATABASE_URLis specifically for a Vercel environment.This is a very common problem indeed. You might be able to use something like https://github.com/FiloSottile/mkcert to simulate SSL in development.
This feels like a Vercel / Lambda issue unfortunately. Any ideas how Prisma could clean this up?
danhollick commentedon Aug 27, 2020
@matthewmueller no worries, happy to help as much as I can.
Being able to reference the certificates from a .env file in the connection string would take at least part of the problem away. If I could do this for instance:
Obviously not a practical suggestion.
matthewmueller commentedon Aug 28, 2020
Thanks for your patience @danhollick!
We've been talking about adding template literals. Would this work for you?
danhollick commentedon Aug 28, 2020
@matthewmueller I think that would be a great improvement! 😍
matthewmueller commentedon Jan 11, 2021
Composing your .env is doable now. We didn't implement it in the schema, but instead support .env template expansion: https://www.prisma.io/docs/concepts/components/prisma-schema#accessing-environment-variables-from-the-schema
So in your
.envfile:Then in production you can load a different .env or do it programmatically as @pantharshit00 suggested.
For the other part of the issue of accepting a certificate's content as an environment variable. We probably won't support this workflow directly, but recommend using the workaround @danhollick suggested. The main reason is that it's easy enough to create a library in userland for handling this and environment variables have size limits.
If we get burned by
/tmpnot being writable in some serverless environment or enough people want this feature, we may revisit.Closing, but happy to re-open if this workflow doesn't work for you. Thanks!
villesau commentedon Mar 27, 2022
I really want that feature. Look at the workaround, it is definitely not a maintainable solution and requires quite a lot of unnecessary blumbing, googling and banging head against the wall.
brian-dlee commentedon Jul 26, 2022
Using many resources posted in this thread (especially that by @danhollick) I created a project that helps get large environment variables into Vercel deployments in a somewhat elegant way that can be community maintained. I'm using it at my organization to get my Remix app deployed in Vercel to connect to a Google Cloud SQL instance (MySQL) via Prisma. I'll drop it here in case it can help anyone else or maybe others can find their way to it to improve it's reach.
https://github.com/brian-dlee/smuggler
arch-user-france1 commentedon Jan 18, 2023
it's much easier to just store the cert like this in the file:
You definitely don't have to encrypt it.
And then:
and
But seriously, hacky workarounds shouldn't have to be.
You would then do that:
But in my opinion, it's too risky.
niteshsrivats commentedon Aug 8, 2023
This saved me quite some time, thank you @danhollick!
Earlier this year, Vercel increased the limit for environment variables to 64KB from 5KB so the base64 encoded client identity (~3.5KB in my case) can be directly used.
Adding the commands to create the client identity p12 file and encode it in base64 below to save a little time Googling it.
Generate Client Identity P12 file
openssl pkcs12 -export -out client-identity.p12 -inkey client-key.pem -in client-cert.pemEncode it in base64
base64 -i client-identity.p12 -o client-identity-base64flawnson commentedon Mar 3, 2024
Can confirm this thread is still relevant. I'm using NextJS and tRPC deployed on Vercel, and Postgres hosted on Google CloudSQL. I adapted @danhollick's code (thanks Dan!) to work with SSL certificates and took advantage of the recently increased environment variable size limits to store the certificates in base64 before decoding them back into .pem files and storing them in tmp.
The code I used:
DATABASE_URL as deployed on Vercel:
postgresql://USER:PASSWORD@PUBLIC_IP:POST/DB_NAME?sslmode=require&sslcert=/tmp/client-cert.pem&sslkey=/tmp/client-key.pem&sslrootcert=/tmp/server-ca.pemAlso key here is to configure a new authorized network on the SQL deployment with the IP set to
0.0.0.0/0, which allows any public IP to access the database (as long as they have the SSL certificates! Which is what we provided with ^).To access the database in my local environment I just use cloud sql proxy.