0

I have the following Joi schema validation in my node project, which I am planning to convert into python using marshmallow library.

Joi Schema:

aws_access_key: Joi.string().label('AWS ACCESS KEY').required().token().min(20),
aws_secret_key: Joi.string().label('AWS SECRET KEY').required().base64().min(40),
encryption: Joi.string().label('AWS S3 server-side encryption').valid('SSE_S3', 'SSE_KMS', 'CSE_KMS').optional(),
kmsKey: Joi.string().label('AWS S3 server-side encryption KMS key').when('encryption', { is: Joi.valid('SSE_KMS', 'CSE_KMS'), then: Joi.string().required() })

Here is what I did so far using marshmallow in python

from marshmallow import Schema, fields
from marshmallow.validate import OneOf, Length


class AWSSchema(Schema):
   aws_access_key = fields.String("title", required=True, validate=Length(min=20))
   aws_secret_key = fields.String(required=True, validate=Length(min=40))
   encryption = fields.String(required=False, validate=OneOf(['SSE_S3', 'SSE_KMS', 'CSE_KMS']))
   kmskey = fields.String(validate=lambda obj: fields.String(required=True) if obj['encryption'] in ('SSE_KMS', 'CSE_KMS') else fields.String(required=False))


demo = {
 "aws_access_key": "AKXXXXXXXXXXXXXXXXXXX",
 "aws_secret_key": "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
 "encryption_type": "SSE_KMS"
}


schema = AWSSchema()
print(schema.dump(demo))

if encryption_type value is set to SSE_KMS or CSE_KMS, then I need kmskey field should be required field. But the validation is not working as expected. Any help is appreciated?

thotam
  • 941
  • 2
  • 16
  • 31
  • What do you mean by validation is not working? How are you trying to validate? – PoP Sep 16 '18 at 05:50
  • It should be possible to check the existence and value of ksmkey, and then the existence of kmskey, with a top level validator. See https://stackoverflow.com/a/40900980/5781248 – J.J. Hakala Sep 28 '18 at 08:54

1 Answers1

0

Marshmallow has methods you can overwrite to do top-level validation at various points in the dump or load process. The documentation for pre_dump can be found here. Also checkout pre_load and post_dump.

https://marshmallow.readthedocs.io/en/stable/api_reference.html#marshmallow.decorators.pre_dump

Lucas Scott
  • 455
  • 3
  • 10