@@ -300,20 +300,31 @@ def value(self):
300300 def coded_value (self ):
301301 return self ._coded_value
302302
303+ def _check_attribute (self , key , val ):
304+ """Normalize and validate an attribute name and value
305+
306+ Raise `CookieError` if the key is not a recognized attribute name or
307+ value contains illegal characters. Otherwise return the canonicalized
308+ key.
309+ """
310+ key = key .lower ()
311+ val_str = str (val )
312+ if key not in self ._reserved :
313+ raise CookieError (f"Invalid attribute { key !r} " )
314+ if _has_control_character (key , val_str ):
315+ raise CookieError (f"Control characters are not allowed in cookies { key !r} { val !r} " )
316+ # Comment is quoted like a cookie value so semicolons can be escaped.
317+ # No other attribute expects `;` in the value, so refuse it.
318+ if key != 'comment' and ';' in val_str :
319+ raise CookieError (f"Reserved character ';' is not allowed in cookie attribute value { key !r} { val !r} " )
320+ return key
321+
303322 def __setitem__ (self , K , V ):
304- K = K .lower ()
305- if not K in self ._reserved :
306- raise CookieError ("Invalid attribute %r" % (K ,))
307- if _has_control_character (K , V ):
308- raise CookieError (f"Control characters are not allowed in cookies { K !r} { V !r} " )
323+ K = self ._check_attribute (K , V )
309324 dict .__setitem__ (self , K , V )
310325
311326 def setdefault (self , key , val = None ):
312- key = key .lower ()
313- if key not in self ._reserved :
314- raise CookieError ("Invalid attribute %r" % (key ,))
315- if _has_control_character (key , val ):
316- raise CookieError ("Control characters are not allowed in cookies %r %r" % (key , val ,))
327+ key = self ._check_attribute (key , val )
317328 return dict .setdefault (self , key , val )
318329
319330 def __eq__ (self , morsel ):
@@ -335,12 +346,7 @@ def copy(self):
335346 def update (self , values ):
336347 data = {}
337348 for key , val in dict (values ).items ():
338- key = key .lower ()
339- if key not in self ._reserved :
340- raise CookieError ("Invalid attribute %r" % (key ,))
341- if _has_control_character (key , val ):
342- raise CookieError ("Control characters are not allowed in "
343- f"cookies { key !r} { val !r} " )
349+ key = self ._check_attribute (key , val )
344350 data [key ] = val
345351 dict .update (self , data )
346352
0 commit comments