From 826cacfa2d71af9350ea94f269ec90514305d15e Mon Sep 17 00:00:00 2001
From: Benjamin Dauvergne <bdauvergne@entrouvert.com>
Date: Tue, 23 Sep 2014 11:40:16 +0200
Subject: [PATCH 2/2] Add tests for get_user_from_api_query_string()

---
 tests/test_api.py |  149 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 149 insertions(+)
 create mode 100644 tests/test_api.py

diff --git a/tests/test_api.py b/tests/test_api.py
new file mode 100644
index 0000000..2b42f8c
--- /dev/null
+++ b/tests/test_api.py
@@ -0,0 +1,149 @@
+import urlparse
+import tempfile
+import shutil
+import json
+import os
+import hmac
+import base64
+import hashlib
+import urllib
+import datetime
+
+from quixote import cleanup, get_publisher
+from wcs import publisher
+from qommon import sessions
+from wcs.qommon.http_request import HTTPRequest
+from wcs.users import User
+from wcs.categories import Category
+
+pub, req, app_dir, user = None, None, None, None
+
+def setup_module(module):
+    cleanup()
+
+    global pub, req, app_dir, user
+    app_dir = tempfile.mkdtemp() 
+    publisher.WcsPublisher.APP_DIR = app_dir
+    pub = publisher.WcsPublisher.create_publisher()
+
+    req = HTTPRequest(None, {'SCRIPT_NAME': '/', 'SERVER_NAME': 'example.net'})
+    req._user = None
+    req.language = 'en'
+    pub._set_request(req)
+    req.session = sessions.Session(id=1)
+    category = Category()
+    category.name = 'category'
+    category.store()
+
+
+def visit_page(url, body=None):
+    global req
+
+    parsed = urlparse.urlparse(url)
+    environ = {}
+    environ['SCRIPT_NAME'] = '/'
+    environ['SERVER_NAME'] = 'example.net'
+    environ['PATH_INFO'] = parsed.path
+    if parsed.query:
+        environ['QUERY_STRING'] = parsed.query
+    req = HTTPRequest(body, environ)
+    return get_publisher().process_request(req)
+
+def teardown_module(module):
+    global pub
+    shutil.rmtree(pub.APP_DIR)
+
+def test_get_user_from_api_query_string():
+    global user
+
+    import sys
+    output = visit_page('/user')
+    assert output.headers.get('location') == 'http://example.net//myspace/'
+    user = User()
+    user.name = 'Jean Darmette'
+    user.email = 'jean.darmette@triffouilis.fr'
+    user.store()
+    output = visit_page('/user?format=json')
+    content = ''.join(output.generate_body_chunks())
+    assert content == '???'
+    output = visit_page('/user?format=json&signature=xxx')
+    content = ''.join(output.generate_body_chunks())
+    result = json.loads(content)
+    assert result['err_desc'] == 'missing/multiple orig field'
+    output = visit_page('/user?format=json&orig=coin&signature=xxx')
+    content = ''.join(output.generate_body_chunks())
+    result = json.loads(content)
+    assert result['err_desc'] == 'invalid orig'
+    file(os.path.join(app_dir, 'example.net', 'site-options.cfg'), 'w').write('''\
+[api-secrets]
+coucou = 1234
+''')
+    output = visit_page('/user?format=json&orig=coucou&signature=xxx')
+    content = ''.join(output.generate_body_chunks())
+    result = json.loads(content)
+    assert result['err_desc'] == 'missing/multiple algo field'
+    output = visit_page('/user?format=json&orig=coucou&signature=xxx&algo=coin')
+    content = ''.join(output.generate_body_chunks())
+    result = json.loads(content)
+    assert result['err_desc'] == 'invalid algo'
+    output = visit_page('/user?format=json&orig=coucou&signature=xxx&algo=sha1')
+    content = ''.join(output.generate_body_chunks())
+    result = json.loads(content)
+    assert result['err_desc'] == 'invalid signature'
+    signature = urllib.quote(
+            base64.b64encode(
+                hmac.new('1234',
+                    'format=json&orig=coucou&algo=sha1', 
+                    hashlib.sha1).digest()))
+    output = visit_page('/user?format=json&orig=coucou&algo=sha1&signature=%s' % signature)
+    content = ''.join(output.generate_body_chunks())
+    result = json.loads(content)
+    assert result['err_desc'] == 'missing/multiple timestamp field'
+
+    timestamp = datetime.datetime.utcnow().isoformat()[:19] + 'Z'
+    query = 'format=json&orig=coucou&algo=sha1&timestamp=' + timestamp
+    signature = urllib.quote(
+            base64.b64encode(
+                hmac.new('1234',
+                    query, 
+                    hashlib.sha1).digest()))
+    output = visit_page('/user?%s&signature=%s' % (query, signature))
+    content = ''.join(output.generate_body_chunks())
+    result = json.loads(content)
+    assert result['err_desc'] == 'missing email or NameID fields'
+
+    timestamp = datetime.datetime.utcnow().isoformat()[:19] + 'Z'
+    query = 'format=json&orig=coucou&algo=sha1&email=' + urllib.quote(user.email) + '&timestamp=' + timestamp
+    signature = urllib.quote(
+            base64.b64encode(
+                hmac.new('1234',
+                    query, 
+                    hashlib.sha1).digest()))
+    output = visit_page('/user?%s&signature=%s' % (query, signature))
+    content = ''.join(output.generate_body_chunks())
+    result = json.loads(content)
+    assert result['user_display_name'] == u'Jean Darmette'
+
+    timestamp = datetime.datetime.utcnow().isoformat()[:19] + 'Z'
+    query = 'format=json&orig=coucou&algo=sha256&email=' + urllib.quote(user.email) + '&timestamp=' + timestamp
+    signature = urllib.quote(
+            base64.b64encode(
+                hmac.new('1234',
+                    query, 
+                    hashlib.sha1).digest()))
+    output = visit_page('/user?%s&signature=%s' % (query, signature))
+    content = ''.join(output.generate_body_chunks())
+    result = json.loads(content)
+    assert result['err_desc'] == 'invalid signature'
+
+    timestamp = datetime.datetime.utcnow().isoformat()[:19] + 'Z'
+    query = 'format=json&orig=coucou&algo=sha256&email=' + urllib.quote(user.email) + '&timestamp=' + timestamp
+    signature = urllib.quote(
+            base64.b64encode(
+                hmac.new('1234',
+                    query, 
+                    hashlib.sha256).digest()))
+    output = visit_page('/user?%s&signature=%s' % (query, signature))
+    content = ''.join(output.generate_body_chunks())
+    result = json.loads(content)
+    assert result['user_display_name'] == u'Jean Darmette'
-- 
1.7.10.4

