@@ -297,20 +297,31 @@ def value(self):
297297 def coded_value (self ):
298298 return self ._coded_value
299299
300+ def _check_attribute (self , key , val ):
301+ """Normalize and validate an attribute name and value
302+
303+ Raise `CookieError` if the key is not a recognized attribute name or
304+ value contains illegal characters. Otherwise return the canonicalized
305+ key.
306+ """
307+ key = key .lower ()
308+ val_str = str (val )
309+ if key not in self ._reserved :
310+ raise CookieError (f"Invalid attribute { key !r} " )
311+ if _has_control_character (key , val_str ):
312+ raise CookieError (f"Control characters are not allowed in cookies { key !r} { val !r} " )
313+ # Comment is quoted like a cookie value so semicolons can be escaped.
314+ # No other attribute expects `;` in the value, so refuse it.
315+ if key != 'comment' and ';' in val_str :
316+ raise CookieError (f"Reserved character ';' is not allowed in cookie attribute value { key !r} { val !r} " )
317+ return key
318+
300319 def __setitem__ (self , K , V ):
301- K = K .lower ()
302- if not K in self ._reserved :
303- raise CookieError ("Invalid attribute %r" % (K ,))
304- if _has_control_character (K , V ):
305- raise CookieError (f"Control characters are not allowed in cookies { K !r} { V !r} " )
320+ K = self ._check_attribute (K , V )
306321 dict .__setitem__ (self , K , V )
307322
308323 def setdefault (self , key , val = None ):
309- key = key .lower ()
310- if key not in self ._reserved :
311- raise CookieError ("Invalid attribute %r" % (key ,))
312- if _has_control_character (key , val ):
313- raise CookieError ("Control characters are not allowed in cookies %r %r" % (key , val ,))
324+ key = self ._check_attribute (key , val )
314325 return dict .setdefault (self , key , val )
315326
316327 def __eq__ (self , morsel ):
@@ -332,12 +343,7 @@ def copy(self):
332343 def update (self , values ):
333344 data = {}
334345 for key , val in dict (values ).items ():
335- key = key .lower ()
336- if key not in self ._reserved :
337- raise CookieError ("Invalid attribute %r" % (key ,))
338- if _has_control_character (key , val ):
339- raise CookieError ("Control characters are not allowed in "
340- f"cookies { key !r} { val !r} " )
346+ key = self ._check_attribute (key , val )
341347 data [key ] = val
342348 dict .update (self , data )
343349
0 commit comments