Skip to content

Provide access keys used for a SSL connection #1673

Closed

Description

@BjoernRave

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

Activity

  1. added
    kind/feature
    on Feb 21, 2020
  2. pantharshit00 commented on Feb 21, 2020

    @pantharshit00
    Contributor

    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:

    const prisma = new PrismaClient({
      datasources: {
        db: `postgres://${process.env.USERNAME}:${process.env.PASSWORD}@somehost/mydb?sslidentity=${process.env.SSL_IDENTITY}`
      }
    });

    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.

  3. added this to the Preview 24 New milestone on Mar 3, 2020
  4. 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
  5. danhollick commented on Jun 21, 2020

    @danhollick

    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()
    

    Then my database url for production looks like :

    postgresql://USER:XXX@DBCONNECTION?&sslmode=require&sslaccept=accept_invalid_certs&sslidentity=/tmp/client-identity.p12&sslpassword=XXX&sslcert=/tmp/server-ca.pem
    

    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
    
  6. 1 remaining item

  7. danhollick commented on Aug 27, 2020

    @danhollick

    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:

    • 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.

  8. matthewmueller commented on Aug 27, 2020

    @matthewmueller
    Contributor

    @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:

    datasource pg {
      provider = "postgres"
      url = env("DATABASE_URL")
    }

    In development you have:

    DATABASE_URL = "postgres://user@localhost:5432/db"
    

    In production you have:

    DATABASE_URL = "postgresql://USER:XXX@DBCONNECTION?&sslmode=require&sslaccept=accept_invalid_certs&sslidentity=/tmp/client-identity.p12&sslpassword=XXX&sslcert=/tmp/server-ca.pem"
    

    I see this as being somewhat acceptable because the production DATABASE_URL is specifically for a Vercel environment.

    I only need to do this in production and not locally which means if it fails I might not catch it.

    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.

    It also just kinda feels gross to be writing to the file system of a serverless environment.

    This feels like a Vercel / Lambda issue unfortunately. Any ideas how Prisma could clean this up?

  9. danhollick commented on Aug 27, 2020

    @danhollick

    @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:

    datasource pg {
      provider = "postgres"
      url = env("DATABASE_URL")
      sslidentity = file("/tmp/client-identity")
      sslcert = env("SERVER_CA")
    }
    

    Obviously not a practical suggestion.

  10. matthewmueller commented on Aug 28, 2020

    @matthewmueller
    Contributor

    Thanks for your patience @danhollick!

    We've been talking about adding template literals. Would this work for you?

    datasource pg {
      provider = "postgres"
      url = "${env("DATABASE_URL")}?sslidentity=/tmp/client-identity&sslcert=${env("SERVER_CA")}"
    }
  11. danhollick commented on Aug 28, 2020

    @danhollick

    @matthewmueller I think that would be a great improvement! 😍

  12. matthewmueller commented on Jan 11, 2021

    @matthewmueller
    Contributor

    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 .env file:

    SSL_CA="./path/to/ca.crt"
    DATABASE_URL="postgresql://user:xxx@host?&sslmode=require&sslcert=${SERVER_CA}"

    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 /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!

  13. villesau commented on Mar 27, 2022

    @villesau

    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.

  14. brian-dlee commented on Jul 26, 2022

    @brian-dlee
    Contributor

    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

  15. arch-user-france1 commented on Jan 18, 2023

    @arch-user-france1

    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()
    

    Then my database url for production looks like :

    postgresql://USER:XXX@DBCONNECTION?&sslmode=require&sslaccept=accept_invalid_certs&sslidentity=/tmp/client-identity.p12&sslpassword=XXX&sslcert=/tmp/server-ca.pem
    

    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:

    module.exports = `-----BEGIN CERTIFICATE-----
    MII....
    -----END CERTIFICATE-----
    `
    

    You definitely don't have to encrypt it.
    And then:

    import dbCert from './dbCert';
    

    and

    function createCertificate() {
      console.log("This server's tmp:",tmpdir()) // I didn't use tmpdir() because MacOS returns weird paths
      fs.writeFileSync(
        `/tmp/dbCertificate.pem`,
        dbCert,
        err => {
          if (err) return console.log(err)
        }
      )
    }
    

    But seriously, hacky workarounds shouldn't have to be.

    You would then do that:

    let prisma;
    
    if (process.env.NODE_ENV === 'production') {
      createCertificate()
    
      prisma = new PrismaClient();
    } else {
      if (!global.prisma) {
        createCertificate()
        global.prisma = new PrismaClient();
      }
      prisma = global.prisma;
    }
    
    export default prisma;
    

    But in my opinion, it's too risky.

  16. niteshsrivats commented on Aug 8, 2023

    @niteshsrivats

    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()
    

    Then my database url for production looks like :

    postgresql://USER:XXX@DBCONNECTION?&sslmode=require&sslaccept=accept_invalid_certs&sslidentity=/tmp/client-identity.p12&sslpassword=XXX&sslcert=/tmp/server-ca.pem
    

    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.

    Generate Client Identity P12 file
    openssl pkcs12 -export -out client-identity.p12 -inkey client-key.pem -in client-cert.pem

    Encode it in base64
    base64 -i client-identity.p12 -o client-identity-base64

  17. flawnson commented on Mar 3, 2024

    @flawnson

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions