Search code examples
djangoaws-lambdaapple-push-notificationszappa

Upload APNs certificate to AWS Lambda


I am using Django with Zappa to connect to serverless AWS Lambda. To get APNs (Apple Push Notification services) up and running, I originally had to upload my certificate file to the server, so that my backend can access it whenever it needs to. But now that I migrated to AWS Lambda, I am not sure how to upload the certificate file.

I use this package django-push-notifications to use APNs and in my Django settings, I have

PUSH_NOTIFICATIONS_SETTINGS = { "APNS_CERTIFICATE": os.path.join(BASE_DIR, "../../Certificates_and_keys/prod_pushcert.pem"), "APNS_TOPIC": "org.reactjs.native.example.Spap", "UPDATE_ON_DUPLICATE_REG_ID": True, "USER_MODEL": "social.User", }

Where the value for APNS_CERTIFICATE is the path of the APNs certificate file. Before using AWS Lambda, I had another server where I uploaded the certificate file with ftp. I don't know how to do that with AWS Lambda. Any suggestions?


Solution

  • I don't know off the top of my head how long APNs certificates are, but if they're less than 4 KB, then you could add it as a Lambda environment variable and read it into a temporary file on startup (in settings.py).

    If they're larger than 4 KB, you could store the certificate in S3 and then download it to a temporary file on startup:

    import boto3
    from tempfile import NamedTemporaryFile
    
    s3 = boto3.client("s3")
    
    with NamedTemporaryFile(delete=False) as f:
        s3.download_fileobj("mybucket", "mykey", f)
    
    APNS_CERTIFICATE = f.name
    

    (Disclaimer: I haven't tested this exact code)

    This could get expensive, though, because you're fetching the file from S3 every time the Lambda is invoked. Zappa's keep_warm feature might help with this, but I'm not completely sure how it works so take that with a grain of salt.

    You'll probably also want to disable this unless DEBUG or another indicator that you're developing locally is set, so you don't try to fetch your production APNs cert during development.