firebase-admin-python icon indicating copy to clipboard operation
firebase-admin-python copied to clipboard

Able to send nested dict in APNS payload but not in android and webpush payload

Open adihat opened this issue 7 years ago • 6 comments

Environment

  • Operating System version: mac os x mojave 10.14.3
  • Firebase SDK version: firebase-admin-2.16.0
  • Firebase Product: cloud messaging

Problem description

I am able to send payload having dict as value in APNS and not in Android or Webpush notifications i.e; I am able to send payload of the form:

{
     "key1": "value1",
     "key2": "value2",
     "key3": {
           "key3.1": "value3.1"
      }
}

Relevant Code

For Android:

import firebase_admin
from firebase_admin import messaging
from firebase_admin import credentials

#initialize firebase admin sdk
creds = credentials.Certificate('path/to/certificate.json')
firebase_admin.initialize_app(creds)


def send(token):
    message = messaging.Message(
        android=messaging.AndroidConfig(
            priority='high',
            notification=messaging.AndroidNotification(
                title='title',
                body='body'
            ),
            data={
                'a': {'b': '1'}
            }
        ),
        token=token,
    )
    response = messaging.send(message)
    print(response)

your_token = 'registration_token'
send(your_token)

Traceback:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 18, in send
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/messaging.py", line 88, in send
    return _get_messaging_service(app).send(message, dry_run)
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/messaging.py", line 246, in send
    data = {'message': _MessagingService.encode_message(message)}
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/messaging.py", line 243, in encode_message
    return cls.JSON_ENCODER.default(message)
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/_messaging_utils.py", line 760, in default
    'android': MessageEncoder.encode_android(obj.android),
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/_messaging_utils.py", line 440, in encode_android
    'AndroidConfig.data', android.data),
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/_messaging_utils.py", line 406, in check_string_dict
    raise ValueError('{0} must not contain non-string values.'.format(label))
ValueError: AndroidConfig.data must not contain non-string values.

For web:

def send(token):
    message = messaging.Message(
        webpush=messaging.WebpushConfig(
            headers={
                'Urgency': 'high'
            },
            notification=messaging.WebpushNotification(
                title='title',
                body='body'
            ),
            data={
                'a': {'b': '1'}
            }
        ),
    token=token)
    response = messaging.send(message)
    print(response)

your_token = 'registration_token'
send(your_token)

Traceback:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 16, in send
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/messaging.py", line 88, in send
    return _get_messaging_service(app).send(message, dry_run)
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/messaging.py", line 246, in send
    data = {'message': _MessagingService.encode_message(message)}
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/messaging.py", line 243, in encode_message
    return cls.JSON_ENCODER.default(message)
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/_messaging_utils.py", line 768, in default
    'webpush': MessageEncoder.encode_webpush(obj.webpush),
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/_messaging_utils.py", line 528, in encode_webpush
    'WebpushConfig.data', webpush.data),
  File "/Users/adarsh/virtualenvs/py3.6/lib/python3.6/site-packages/firebase_admin/_messaging_utils.py", line 406, in check_string_dict
    raise ValueError('{0} must not contain non-string values.'.format(label))
ValueError: WebpushConfig.data must not contain non-string values.

For APNS:

def send(token):
    message = messaging.Message(
        apns=messaging.APNSConfig(
            headers={
                'apns-priority': '10',
            },
            payload=messaging.APNSPayload(
                aps=messaging.Aps(
                    alert=messaging.ApsAlert(
                        title='title1',
                        subtitle='subtitle1',
                        body='body'
                    ),
                    content_available=1,
                    mutable_content=1
                ),
                data={
                    'a': {'b': '1'}
                }
            ),
        ),
        token=token
    )
    response = messaging.send(message)
    print(response)

your_token = 'registration_token'
send(your_token)

No errors...... This is valid.

Quick observations

  • MessageEncoder class in _messaging_utils.py file has the following class methods:
    • encode_android_notification()
    • encode_webpush_notification()
    • encode_apns()
  • _Validators.check_string() is used to check if value is a string and _Validators.check_string_dict() is used to check if the dict values are strings.
  • encode_apns_payload() checks the validity of aps but not the custom_data. Hence its possible to send nested dict in custom data

Possible solution

In line 646:

 for key, value in payload.custom_data.items():
    result[key] = _Validators.check_string('APNSConfig.payload.custom_data', value)

(or)

custom_data = _Validators.check_string_dict('APNSConfig.payload.custom_data', payload.custom_data)
for key, value in custom_data.items():
    result[key] = value

This ensures there is uniformity across all platforms.

adihat avatar Mar 28 '19 20:03 adihat

I found a few problems with this issue:

  • I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.
  • This issue does not seem to follow the issue template. Make sure you provide all the required information.

google-oss-bot avatar Mar 28 '19 20:03 google-oss-bot

This is working as intended. Both AndroidConfig.data and WebpushConfig.data must be specified as dictionaries with string keys and values. See the documentation of the underlying REST API:

https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#AndroidConfig https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#WebpushConfig

The SDK is doing the right thing here. It's ensuring that the message format adheres to what the backend server expects.

hiranya911 avatar Mar 28 '19 20:03 hiranya911

Assigning to @chong-shao to see if there's anything to be done with this. Otherwise, please close.

hiranya911 avatar Mar 28 '19 20:03 hiranya911

@hiranya911 Yes the SDK is doing the right thing in case of android and webpush. In case of APNS, its adding the kwargs as custom_data in the payload which is not validated if the values in the dict are strings. Is this by design?

adihat avatar Mar 29 '19 06:03 adihat

Yes, it's by design. As you can see here ApnsConfig.payload accepts arbitrary key-value pairs:

https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#apnsconfig

In case of AndroidConfig and WebpushConfig, data is defined as part of the schema.

hiranya911 avatar Mar 29 '19 16:03 hiranya911

@hiranya911 Ok then please close this issue.

adihat avatar Mar 30 '19 10:03 adihat