The shop keeps each visitor's cart in a cookie: the browser stores it and sends it back with every request. The first version saved the cart with pickle, Python's own format, base64-encoded, and read it back with pickle.loads(base64.b64decode(raw)).
The attack: the cookie sits in the visitor's browser, so they can replace it with anything, and base64 is not a lock. Pickle can store "call this function with these arguments", and pickle.loads makes that call while it loads. The check sends a harmless cookie that calls print("owned"). The attacker gets to run any Python they like on your server: read your secret keys, change orders, delete files.
The fix: store the cart as JSON. json.loads only ever builds data: dicts, lists, text and numbers. A cookie that isn't base64 or isn't JSON raises a ValueError, and valid JSON can still be the wrong shape, which isinstance catches. On other values:
json.loads('{"theme": "dark"}') # {'theme': 'dark'}
isinstance(json.loads('["Mug"]'), dict) # False: it is a list
json.loads("not json") # raises ValueError
A cookie that can't be read, or isn't a dict, counts as an empty cart. The check uses one browser, which keeps its cookie from one request to the next:
POST /cart {"product": "Mug", "quantity": 2} → 200 {"Mug": 2}
POST /cart {"product": "Pen", "quantity": 5} → 200 {"Mug": 2, "Pen": 5}
GET /cart → 200 {"items": {"Mug": 2, "Pen": 5}, "total": 34}
GET /cart (cookie: the pickle that prints owned) → 200 {"items": {}, "total": 0}
GET /cart (cookie: ["Mug"] in base64) → 200 {"items": {}, "total": 0}
POST /cart {"product": "Teapot", "quantity": 1} → 200 {"Teapot": 1}
Your task: the starting code can't save or read a cart yet, so most requests answer 500. In add_to_cart, set value to the cart as JSON text, base64-encoded, as a string. In load_cart, read the cookie with json.loads inside a try, return {} on a ValueError, and return {} when the result is not a dict.
Assignment
Follow the Coding Tutorial to save the cart cookie as JSON and read it back safely.
Hintb64encode takes bytes and gives bytes: .encode() the JSON text before it and .decode() its answer. isinstance(cart, dict) is True only for a dict.
Free plan: 30 tutor messages. PRO is unlimited.
