Skip to content

Commit c3d9bff

Browse files
committed
Fixed a bug in Message.toPostArgs() related to UTF-8 encoded values.
In generating the argument dictionary the .toPostArgs() method (apparently) assumed that values were all Unicode objects and called ``value.encode('utf-8')`` on them unconditionally. However, the values appear to be a mixed set of Unicode objects and UTF-8 encoded strings (most being of the latter group). Calling .encode('utf-8') on a string will implicitly decode the string into a Unicode object before encoding it to the selected encoding. This automatic decoding happens using the ``sys.getdefaultencoding()`` encoding which is by default 'ascii'. The original call therefore works only as long as the values are 7-bit ASCII and breaks when they contain higher bit characters. The patch ensures that the resulting values in the returned dictionary are UTF-8 encoded strings regardless if the input values were Unicode objects or UTF-8 strings.
1 parent 0dd2e81 commit c3d9bff

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

openid/message.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,8 @@ def toPostArgs(self):
277277

278278
for (ns_uri, ns_key), value in self.args.iteritems():
279279
key = self.getKey(ns_uri, ns_key)
280-
args[key] = value.encode('UTF-8')
280+
# Ensure the resulting value is an UTF-8 encoded bytestring.
281+
args[key] = oidutil.toUnicode(value).encode('UTF-8')
281282

282283
return args
283284

openid/test/test_message.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,20 @@ def test_toPostArgs(self):
462462
'xey': 'value',
463463
})
464464

465+
def test_toPostArgs_bug_with_utf8_encoded_values(self):
466+
msg = message.Message.fromPostArgs({'openid.mode':'error',
467+
'openid.error':'unit test',
468+
'openid.ns':message.OPENID2_NS
469+
})
470+
msg.setArg(message.BARE_NS, 'ünicöde_key', 'ünicöde_välüe')
471+
self.failUnlessEqual(msg.toPostArgs(),
472+
{'openid.mode':'error',
473+
'openid.error':'unit test',
474+
'openid.ns':message.OPENID2_NS,
475+
'ünicöde_key': 'ünicöde_välüe',
476+
})
477+
478+
465479
def test_toArgs(self):
466480
# This method can't tolerate BARE_NS.
467481
self.msg.delArg(message.BARE_NS, "xey")

0 commit comments

Comments
 (0)