Example #1
0
def test_cookie_path():
    string = make_cookie('test2', 'alpha2', path='/path/to/location')

    assert string == 'test2=alpha2; Path=/path/to/location; httponly'

    string = make_cookie('test2', 'alpha2', path='/path/to/location',
            httponly=False)

    assert string == 'test2=alpha2; Path=/path/to/location'
Example #2
0
def test_cookie_path():
    string = make_cookie('test2', 'alpha2', path='/path/to/location')

    assert string == 'test2=alpha2; Path=/path/to/location; httponly'

    string = make_cookie('test2', 'alpha2', path='/path/to/location',
            httponly=False)

    assert string == 'test2=alpha2; Path=/path/to/location'
Example #3
0
    def _success(self, environ, start_response, info):
        """
        After successful validation of an openid generate
        and send a cookie with the value of that openid.
        If this is a normal auth scenario make the name
        of the cookie the normal 'tiddlyweb_user'. If this
        is auth addition, where a fragment of 'auth:OpenID' is
        set on the redirect uri, then name the cookie
        'tiddlyweb_secondary_user'.
        """
        usersign = info.getDisplayIdentifier()
        if info.endpoint.canonicalID:
            usersign = info.endpoint.canonicalID
        # canonicolize usersign to tiddlyweb form
        if usersign.startswith('http'):
            usersign = usersign.split('://', 1)[1]
        usersign = usersign.rstrip('/')
        redirect = environ['tiddlyweb.query'].get('tiddlyweb_redirect',
                                                  ['/'])[0]
        uri = urlparse.urljoin(server_host_url(environ), redirect)

        cookie_age = environ['tiddlyweb.config'].get('cookie_age', None)

        secondary_cookie_only = False
        try:
            fragment = uri.rsplit('#', 1)[1]
        except (ValueError, IndexError):
            pass
        else:
            openid = fragment[len(FRAGMENT_PREFIX):]
            uri = uri.replace(FRAGMENT_PREFIX + openid,
                              FRAGMENT_PREFIX + usersign)
            secondary_cookie_only = True

        secret = environ['tiddlyweb.config']['secret']
        secondary_cookie_header_string = make_cookie(
            'tiddlyweb_secondary_user',
            usersign,
            mac_key=secret,
            path=self._cookie_path(environ),
            expires=cookie_age,
            domain=self._domain_path(environ))

        headers = [('Location', uri.encode('utf-8')),
                   ('Content-Type', 'text/plain'),
                   ('Set-Cookie', secondary_cookie_header_string)]

        if not secondary_cookie_only:
            cookie_header_string = make_cookie('tiddlyweb_user',
                                               usersign,
                                               mac_key=secret,
                                               path=self._cookie_path(environ),
                                               expires=cookie_age)
            headers.append(('Set-Cookie', cookie_header_string))

        start_response('303 See Other', headers)
        return [uri]
Example #4
0
    def _success(self, environ, start_response, info):
        """
        After successful validation of an openid generate
        and send a cookie with the value of that openid.
        If this is a normal auth scenario make the name
        of the cookie the normal 'tiddlyweb_user'. If this
        is auth addition, where a fragment of 'auth:OpenID' is
        set on the redirect uri, then name the cookie
        'tiddlyweb_secondary_user'.
        """
        usersign = info.getDisplayIdentifier()
        if info.endpoint.canonicalID:
            usersign = info.endpoint.canonicalID
        # canonicolize usersign to tiddlyweb form
        if usersign.startswith('http'):
            usersign = usersign.split('://', 1)[1]
        usersign = usersign.rstrip('/')
        redirect = environ['tiddlyweb.query'].get(
            'tiddlyweb_redirect', ['/'])[0]
        uri = urlparse.urljoin(server_host_url(environ), redirect)

        cookie_age = environ['tiddlyweb.config'].get('cookie_age', None)

        secondary_cookie_only = False
        try:
            fragment = uri.rsplit('#', 1)[1]
        except (ValueError, IndexError):
            pass
        else:
            openid = fragment[len(FRAGMENT_PREFIX):]
            uri = uri.replace(FRAGMENT_PREFIX + openid,
                    FRAGMENT_PREFIX + usersign)
            secondary_cookie_only = True

        secret = environ['tiddlyweb.config']['secret']
        secondary_cookie_header_string = make_cookie(
                'tiddlyweb_secondary_user', usersign,
                mac_key=secret, path=self._cookie_path(environ),
                expires=cookie_age, domain=self._domain_path(environ))

        headers = [('Location', uri.encode('utf-8')),
                    ('Content-Type', 'text/plain'),
                    ('Set-Cookie', secondary_cookie_header_string)]

        if not secondary_cookie_only:
            cookie_header_string = make_cookie('tiddlyweb_user', usersign,
                    mac_key=secret, path=self._cookie_path(environ),
                    expires=cookie_age)
            headers.append(('Set-Cookie', cookie_header_string))

        start_response('303 See Other', headers)
        return [uri]
Example #5
0
 def _validate_and_redirect(self, environ, start_response, username, password, redirect):
     """
     Check a username and password. If valid, send a cookie
     to the client. If it is not, send the form again.
     """
     status = "401 Unauthorized"
     try:
         store = environ["tiddlyweb.store"]
         secret = environ["tiddlyweb.config"]["secret"]
         cookie_age = environ["tiddlyweb.config"].get("cookie_age", None)
         user = User(username)
         user = store.get(user)
         if user.check_password(password):
             uri = "%s%s" % (server_host_url(environ), redirect)
             cookie_header_string = make_cookie(
                 "tiddlyweb_user", user.usersign, mac_key=secret, path=self._cookie_path(environ), expires=cookie_age
             )
             logging.debug("303 to %s", uri)
             start_response("303 Other", [("Set-Cookie", cookie_header_string), ("Location", uri.encode("utf-8"))])
             return [uri]
     except KeyError:
         pass
     except NoUserError:
         pass
     return self._send_cookie_form(environ, start_response, redirect, status, "User or Password no good")
Example #6
0
def register_user(environ, start_response):
    username, password, confirmation = [environ['tiddlyweb.query'][param][0] for
            param in ('username', 'password', 'password_confirmation')]

    user = User(username)
    store = environ['tiddlyweb.store']
    try:
        store.get(user)
        available = False
    except NoUserError:
        available = username not in BLACKLIST
    if not available:
        raise HTTP409('username unavailable')

    if not password == confirmation:
        raise HTTP400('passwords do not match')

    _create_wiki(store, username, username, private=True)

    user.set_password(password)
    store.put(user)

    index = Tiddler('index', username)
    index.type = 'text/x-markdown'
    index.text = "Welcome to %s's personal wiki." % username
    store.put(index)

    cookie = make_cookie('tiddlyweb_user', user.usersign,
            path=uri('front page', environ),
            mac_key=environ['tiddlyweb.config']['secret'],
            expires=environ['tiddlyweb.config'].get('cookie_age', None))

    start_response('303 See Other', [('Set-Cookie', cookie),
            ('Location', uri('dashboard', environ).encode('UTF-8'))])
    return ['']
Example #7
0
def establish_user_auth(config, store, host, username):
    user = User(username)
    mapping_username = '******' % username
    mapping_tiddler = Tiddler(mapping_username, 'MAPUSER')
    mapping_tiddler.fields['mapped_user'] = username

    try:
        store.delete(user)
    except StoreError:
        pass
    try:
        store.delete(mapping_tiddler)
    except IOError:
        pass

    user.add_role('MEMBER')
    user.note = '{}'
    store.put(user)
    ensure_bag('MAPUSER', store)
    store.put(mapping_tiddler)
    stamp = datetime.utcnow().strftime('%Y%m%d%H')
    csrf = gen_nonce(username, host, stamp, config['secret'])
    cookie = make_cookie('tiddlyweb_user', mapping_username,
            mac_key=config['secret'], httponly=False)

    return cookie, csrf
Example #8
0
def establish_user_auth(config, store, host, username):
    user = User(username)
    mapping_username = '******' % username
    mapping_tiddler = Tiddler(mapping_username, 'MAPUSER')
    mapping_tiddler.fields['mapped_user'] = username

    try:
        store.delete(user)
    except StoreError:
        pass
    try:
        store.delete(mapping_tiddler)
    except IOError:
        pass

    user.add_role('MEMBER')
    user.note = '{}'
    store.put(user)
    ensure_bag('MAPUSER', store)
    store.put(mapping_tiddler)
    stamp = datetime.utcnow().strftime('%Y%m%d%H')
    csrf = gen_nonce(username, host, stamp, config['secret'])
    cookie = make_cookie('tiddlyweb_user',
                         mapping_username,
                         mac_key=config['secret'],
                         httponly=False)

    return cookie, csrf
Example #9
0
def setup_module(module):
    module.TMPDIR = tempfile.mkdtemp()

    _initialize_app(TMPDIR)
    module.ADMIN_COOKIE = make_cookie('tiddlyweb_user', 'admin',
            mac_key=CONFIG['secret'])

    module.STORE = get_store(CONFIG)

    # register admin user
    data = {
        'username': '******',
        'password': '******',
        'password_confirmation': 'secret'
    }
    response, content = _req('POST', '/register', urlencode(data),
            headers={ 'Content-Type': 'application/x-www-form-urlencoded' })

    bag = Bag('alpha')
    bag.policy = Policy(read=['admin'], write=['admin'], create=['admin'],
            delete=['admin'], manage=['admin'])
    STORE.put(bag)

    bag = Bag('bravo')
    STORE.put(bag)

    bag = Bag('charlie')
    bag.policy = Policy(read=['nobody'], write=['nobody'], create=['nobody'],
            delete=['nobody'], manage=['nobody'])
    STORE.put(bag)

    tiddler = Tiddler('index', 'bravo')
    tiddler.text = 'lorem ipsum\ndolor *sit* amet'
    tiddler.type = 'text/x-markdown'
    STORE.put(tiddler)
 def _validate_and_redirect(self, environ, start_response, username,
         password, redirect):
     """
     Check a username and password. If valid, send a cookie
     to the client. If it is not, send the form again.
     """
     status = '401 Unauthorized'
     try:
         store = environ['tiddlyweb.store']
         secret = environ['tiddlyweb.config']['secret']
         cookie_age = environ['tiddlyweb.config'].get('cookie_age', None)
         user = User(username)
         user = store.get(user)
         if user.check_password(password):
             uri = '%s%s' % (server_host_url(environ), redirect)
             cookie_header_string = make_cookie('tiddlyweb_user',
                     user.usersign, mac_key=secret,
                     path=self._cookie_path(environ), expires=cookie_age)
             logging.debug('303 to %s', uri)
             start_response('303 Other',
                     [('Set-Cookie', cookie_header_string),
                         ('Content-Type', 'text/plain'),
                         ('Location', uri.encode('utf-8'))])
             return [uri]
     except KeyError:
         pass
     except NoUserError:
         pass
     return self._send_cookie_form(environ, start_response, redirect,
             status, 'User or Password no good')
Example #11
0
 def _validate_and_redirect(self, environ, start_response, username,
                            password, redirect):
     """
     Check a username and password. If valid, send a cookie
     to the client. If it is not, send the form again.
     """
     status = '401 Unauthorized'
     try:
         store = environ['tiddlyweb.store']
         secret = environ['tiddlyweb.config']['secret']
         cookie_age = environ['tiddlyweb.config'].get('cookie_age', None)
         user = User(username)
         user = store.get(user)
         if user.check_password(password):
             uri = '%s%s' % (server_host_url(environ), redirect)
             cookie_header_string = make_cookie(
                 'tiddlyweb_user',
                 user.usersign,
                 mac_key=secret,
                 path=self._cookie_path(environ),
                 expires=cookie_age)
             logging.debug('303 to %s', uri)
             start_response('303 Other',
                            [('Set-Cookie', cookie_header_string),
                             ('Content-Type', 'text/plain'),
                             ('Location', uri.encode('utf-8'))])
             return [uri]
     except KeyError:
         pass
     except NoUserError:
         pass
     return self._send_cookie_form(environ, start_response, redirect,
                                   status, 'User or Password no good')
 def _make_cookie(self, environ, user):
     secret = environ['tiddlyweb.config']['secret']
     cookie_age = environ['tiddlyweb.config'].get('cookie_age', None)
     return make_cookie('tiddlyweb_user',
                        user,
                        mac_key=secret,
                        path=self._cookie_path(environ),
                        expires=cookie_age)
Example #13
0
def test_cookie_mac():
    string = make_cookie('test4', 'alpha4', mac_key='secret')

    secret_string = sha('%s%s' % ('alpha4', 'secret')).hexdigest()

    if sys.version_info[0] == 2:  # Cookie changed
        assert string == 'test4="alpha4:%s"; httponly' % secret_string
    else:
        assert string == 'test4=alpha4:%s; httponly' % secret_string
Example #14
0
def test_cookie_mac():
    string = make_cookie('test4', 'alpha4', mac_key='secret')

    secret_string = sha('%s%s' % ('alpha4', 'secret')).hexdigest()

    if sys.version_info[0] == 2:  # Cookie changed
        assert string == 'test4="alpha4:%s"; httponly' % secret_string
    else:
        assert string == 'test4=alpha4:%s; httponly' % secret_string
Example #15
0
File: register.py Project: FND/tank
def register(environ, start_response):
    """
    register the user
    """
    config = environ['tiddlyweb.config']
    store = environ['tiddlyweb.store']
    query = environ['tiddlyweb.query']
    try:
        username = query['login'][0]
        name = query['name'][0]
        email = query['email'][0]
        extra = query['extra'][0]
        redirect = query['redirect'][0]
    except (KeyError, ValueError) as exc:
        raise HTTP400('Incomplete form submission: %s' % exc)

    announcements = query.get('announcements', [None])[0]

    user = User(username)
    try:
        store.get(user)
        raise HTTP400('That username is not available.')
    except StoreError:  # we expect and want this
        pass

    user.add_role(DEFAULT_ROLE)
    user.note = simplejson.dumps({
        'registered': time(),
        'name': name,
        'email': email,
        'extra': extra,
        'announcements': announcements is not None
    })

    store.put(user)

    create_wiki(environ, '_%s-data' % username, mode='private',
            username=username, desc='Data Files', validate=False)
    create_wiki(environ, '%s-notebook' % username, mode='private',
            username=username, desc='Private Notebook', validate=False)
    create_wiki(environ, '%s' % username, mode='protected',
            username=username, desc='Share Stuff', validate=False)

    redirect_uri = '%s%s' % (server_base_url(environ), redirect)
    secret = config['secret']
    cookie_age = config.get('cookie_age', None)
    cookie_header_string = make_cookie('tiddlyweb_user', user.usersign,
            mac_key=secret, path='/', expires=cookie_age)
    start_response('303 See Other',
            [('Set-Cookie', cookie_header_string),
                ('Content-Type', 'text/plain'),
                ('Location', str(redirect_uri))])
    return [redirect_uri]
def test_user_may_not_map_self():
    """Make user X can't map user Y to themselves."""
    global AUTH_COOKIE
    second_cookie = make_cookie('tiddlyweb_secondary_user',
            'cdent', mac_key=secret)
    http = httplib2.Http()
    response, content = http.request(
            'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/cdent',
            method='PUT',
            headers={'Content-Type': 'application/json',
                'Cookie': 'tiddlyweb_user="******"; %s' % (
                    AUTH_COOKIE, second_cookie)},
            body='{}')
    assert response['status'] == '409'
    assert 'username exists' in content
Example #17
0
def test_user_registration():
    headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
    data = {
        'username': '******',
        'password': '******',
        'password_confirmation': 'foo'
    }

    assert not _bag_exists('fnd')

    response, content = req('POST', '/register', urlencode(data),
            headers=headers)
    assert response.status == 303
    assert 'tiddlyweb_user="******"dummy's personal wiki" in content
def test_user_may_not_map_self():
    """Make user X can't map user Y to themselves."""
    global AUTH_COOKIE
    second_cookie = make_cookie("tiddlyweb_secondary_user", "cdent", mac_key=secret)
    http = httplib2.Http()
    response, content = http.request(
        "http://0.0.0.0:8080/bags/MAPUSER/tiddlers/cdent",
        method="PUT",
        headers={
            "Content-Type": "application/json",
            "Cookie": 'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, second_cookie),
        },
        body="{}",
    )
    assert response["status"] == "409"
    assert "username exists" in content
def test_user_may_not_map_self():
    """Make user X can't map user Y to themselves."""
    global AUTH_COOKIE
    second_cookie = make_cookie('tiddlyweb_secondary_user',
                                'cdent',
                                mac_key=secret)
    http = httplib2.Http()
    response, content = http.request(
        'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/cdent',
        method='PUT',
        headers={
            'Content-Type': 'application/json',
            'Cookie': 'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, second_cookie)
        },
        body='{}')
    assert response['status'] == '409'
    assert 'username exists' in content
Example #20
0
 def _respond_success(self, parsed_return_to, redirect, environ,
         start_response):
     """
     If the openid server validates our key checking, then
     set the cookie and redirect the user.
     """
     usersign = parsed_return_to['usersign'][0]
     if 'http' in usersign:
         usersign = usersign.split('://', 1)[1]
     uri = '%s%s' % (server_host_url(environ), redirect)
     secret = environ['tiddlyweb.config']['secret']
     cookie_age = environ['tiddlyweb.config'].get('cookie_age', None)
     cookie_header_string = make_cookie('tiddlyweb_user', usersign,
             mac_key=secret, path=self._cookie_path(environ),
             expires=cookie_age)
     logging.debug('303 to %s', uri)
     start_response('303 See Other', [('Location', uri.encode('utf-8')),
             ('Set-Cookie', cookie_header_string)])
     return [uri]
Example #21
0
def _send_cookie(environ, start_response, user):
    """
    We are authentic and a user exists, so install a cookie.
    """
    query = environ['tiddlyweb.query']
    tiddlyweb_redirect = query.get('tiddlyweb_redirect', [None])[0]
    config = environ['tiddlyweb.config']
    if not tiddlyweb_redirect:
        tiddlyweb_redirect = config.get('logged_in_redirect', '/')
    redirect_uri = '%s%s' % (server_host_url(environ), tiddlyweb_redirect)
    secret = config['secret']
    cookie_age = config.get('cookie_age', None)
    cookie_header_string = make_cookie('tiddlyweb_user', user.usersign,
            mac_key=secret, path='/', expires=cookie_age)
    start_response('303 See Other', 
            [('Set-Cookie', cookie_header_string),
                ('Content-Type', 'text/plain'),
                ('Location', str(redirect_uri))])
    return [redirect_uri]
Example #22
0
 def _success(self, environ, start_response, info):
     usersign = info.getDisplayIdentifier()
     if info.endpoint.canonicalID:
         usersign = info.endpoint.canonicalID
     # canonicolize usersign to tiddlyweb form
     if usersign.startswith('http'):
         usersign = usersign.split('://', 1)[1]
     usersign = usersign.rstrip('/')
     uri = urlparse.urljoin(server_host_url(environ),
             environ['tiddlyweb.query'].get('tiddlyweb_redirect', ['/'])[0])
     secret = environ['tiddlyweb.config']['secret']
     cookie_age = environ['tiddlyweb.config'].get('cookie_age', None)
     cookie_header_string = make_cookie('tiddlyweb_user', usersign,
             mac_key=secret, path=self._cookie_path(environ),
             expires=cookie_age)
     start_response('303 See Other',
             [('Location', uri.encode('utf-8')),
                 ('Content-Type', 'text/plain'),
                 ('Set-Cookie', cookie_header_string)])
     return [uri]
Example #23
0
def _send_cookie(environ, start_response, user):
    """
    We are authentic and a user exists, so install a cookie.
    """
    query = environ['tiddlyweb.query']
    tiddlyweb_redirect = query.get('tiddlyweb_redirect', [None])[0]
    config = environ['tiddlyweb.config']
    if not tiddlyweb_redirect:
        tiddlyweb_redirect = config.get('logged_in_redirect', '/')
    redirect_uri = '%s%s' % (server_host_url(environ), tiddlyweb_redirect)
    secret = config['secret']
    cookie_age = config.get('cookie_age', None)
    cookie_header_string = make_cookie('tiddlyweb_user',
                                       user.usersign,
                                       mac_key=secret,
                                       path='/',
                                       expires=cookie_age)
    start_response('303 See Other', [('Set-Cookie', cookie_header_string),
                                     ('Content-Type', 'text/plain'),
                                     ('Location', str(redirect_uri))])
    return [redirect_uri]
Example #24
0
 def _success(self, environ, start_response, info):
     usersign = info.getDisplayIdentifier()
     if info.endpoint.canonicalID:
         usersign = info.endpoint.canonicalID
     # canonicolize usersign to tiddlyweb form
     if usersign.startswith('http'):
         usersign = usersign.split('://', 1)[1]
     usersign = usersign.rstrip('/')
     uri = urlparse.urljoin(
         server_host_url(environ),
         environ['tiddlyweb.query'].get('tiddlyweb_redirect', ['/'])[0])
     secret = environ['tiddlyweb.config']['secret']
     cookie_age = environ['tiddlyweb.config'].get('cookie_age', None)
     cookie_header_string = make_cookie('tiddlyweb_user',
                                        usersign,
                                        mac_key=secret,
                                        path=self._cookie_path(environ),
                                        expires=cookie_age)
     start_response('303 See Other', [('Location', uri.encode('utf-8')),
                                      ('Content-Type', 'text/plain'),
                                      ('Set-Cookie', cookie_header_string)])
     return [uri]
Example #25
0
    def _validate_and_redirect(self, environ, start_response, username,
            password, redirect):
        """
        Check a username and password. If valid, send a cookie
        to the client. If it is not, send the form again.
        """
        status = '401 Unauthorized'
        try:
            store = environ['tiddlyweb.store']
            secret = environ['tiddlyweb.config']['secret']
            cookie_age = environ['tiddlyweb.config'].get('cookie_age', None)
            user = User(username)
            user = store.get(user)
            if user.check_password(password):
                uri = '%s%s' % (server_host_url(environ), redirect)
                cookie_header_string = make_cookie('tiddlyweb_user',
                        user.usersign, mac_key=secret,
                        path=self._cookie_path(environ), expires=cookie_age)
                logging.debug('303 to %s', uri)
                start_response('303 Other',
                        [('Set-Cookie', cookie_header_string),
                            ('Location', uri.encode('utf-8')),
                            ('Pragma', 'no-cache')])
                return [uri]
        except KeyError:
            pass
        except NoUserError:
            logging.debug('NoUserError for: '+username)
        template = templating.get_template(environ, 'login_form.html')
        
        start_response(status, [
            ('Content-Type', 'text/html'),
            ('Pragma', 'no-cache')
            ])

        return template.render(redirect=redirect,
                commonVars=templating.common_vars(environ), error=True)
Example #26
0
def make_instance():
    if len(INSTANCE):  # multiple instances in a single process are unsupported
        return INSTANCE

    tmpdir = os.path.abspath("tmp")
    if os.path.isdir(tmpdir):
        shutil.rmtree(tmpdir)
    os.mkdir(tmpdir)

    _initialize_app(tmpdir)
    store = get_store(CONFIG)

    # register admin user
    admin_cookie = make_cookie("tiddlyweb_user", "admin", mac_key=CONFIG["secret"])
    data = {"username": "******", "password": "******"}
    data["password_confirmation"] = data["password"]
    response, content = req(
        "POST", "/register", urlencode(data), headers={"Content-Type": "application/x-www-form-urlencoded"}
    )

    INSTANCE["tmpdir"] = tmpdir
    INSTANCE["store"] = store
    INSTANCE["admin_cookie"] = admin_cookie
    return INSTANCE
Example #27
0
def test_cookie_name_value():
    string = make_cookie('test1', 'alpha1')

    assert string == 'test1=alpha1; httponly'
Example #28
0
def test_cookie_mac():
    string = make_cookie('test4', 'alpha4', mac_key='secret')

    secret_string = sha('%s%s' % ('alpha4', 'secret')).hexdigest()

    assert string == 'test4="alpha4:%s"; httponly' % secret_string
Example #29
0
def test_cookie_expire():
    string = make_cookie('test3', 'alpha3', expires=50)

    assert string == 'test3=alpha3; Max-Age=50; httponly'
Example #30
0
def test_cookie_expire():
    string = make_cookie("test3", "alpha3", expires=50)

    assert string == "test3=alpha3; Max-Age=50"
 def _make_cookie(self, environ, user):
     secret = environ['tiddlyweb.config']['secret']
     cookie_age = environ['tiddlyweb.config'].get('cookie_age', None)
     return make_cookie('tiddlyweb_user', user, mac_key=secret, path=self._cookie_path(environ),
                        expires=cookie_age)
def test_create_map_uses_user():
    global AUTH_COOKIE
    http = httplib2.Http()
    response, content = http.request(
        'http://0.0.0.0:8080/challenge/cookie_form',
        body='user=cdent&password=cow',
        method='POST',
        headers={'Content-Type': 'application/x-www-form-urlencoded'})
    assert response.previous['status'] == '303'

    user_cookie = response.previous['set-cookie']
    cookie = Cookie.SimpleCookie()
    cookie.load(user_cookie)
    AUTH_COOKIE = cookie['tiddlyweb_user'].value

    bad_second_cookie = make_cookie('tiddlyweb_secondary_user',
                                    'x.auth.thing',
                                    mac_key='slippy')
    mismatch_second_cookie = make_cookie('tiddlyweb_secondary_user',
                                         'y.auth.thing',
                                         mac_key=secret)
    second_cookie = make_cookie('tiddlyweb_secondary_user',
                                'x.auth.thing',
                                mac_key=secret)

    # we must have the second cookie
    response, content = http.request(
        'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
        method='PUT',
        headers={
            'Content-Type': 'application/json',
            'Cookie': 'tiddlyweb_user="******"' % AUTH_COOKIE
        },
        body='{"text":"house"}')
    assert response['status'] == '409', content
    assert 'secondary cookie not present' in content

    response, content = http.request(
        'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
        method='PUT',
        headers={
            'Content-Type': 'application/json',
            'Cookie':
            'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, bad_second_cookie)
        },
        body='{"text":"house"}')
    assert response['status'] == '409', content
    assert 'secondary cookie invalid' in content

    response, content = http.request(
        'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
        method='PUT',
        headers={
            'Content-Type':
            'application/json',
            'Cookie':
            'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, mismatch_second_cookie)
        },
        body='{"text":"house"}')
    assert response['status'] == '409', content
    assert 'secondary cookie mismatch' in content

    response, content = http.request(
        'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
        method='PUT',
        headers={
            'Content-Type': 'application/json',
            'Cookie': 'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, second_cookie)
        },
        body='{"text":"house"}')
    assert response['status'] == '204'

    response, content = http.request(
        'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
        method='GET',
        headers={
            'Accept': 'application/json',
            'Cookie': 'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, second_cookie)
        })
    assert response['status'] == '403'
    assert 'may not read' in content

    tiddler = Tiddler('x.auth.thing', 'MAPUSER')
    tiddler = store.get(tiddler)
    assert tiddler.modifier == 'cdent'
    assert tiddler.text == ''
    assert 'mapped_user' in tiddler.fields
    assert tiddler.fields['mapped_user'] == 'cdent'

    response, content = http.request(
        'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
        method='PUT',
        headers={
            'Content-Type': 'application/json',
            'Cookie': 'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, second_cookie)
        },
        body='{}')
    assert response['status'] == '403'
    assert 'may not write' in content
Example #33
0
def test_cookie_name_value():
    string = make_cookie("test1", "alpha1")

    assert string == "test1=alpha1"
Example #34
0
def test_cookie_domain():
    string = make_cookie('test5', 'alpha5', domain=".tiddlyspace.com")

    assert string == 'test5=alpha5; Domain=.tiddlyspace.com; httponly'
Example #35
0
def register(environ, start_response):
    """
    register the user
    """
    config = environ['tiddlyweb.config']
    store = environ['tiddlyweb.store']
    query = environ['tiddlyweb.query']
    try:
        server_name = query['server_name'][0]
        server_name_sig = query['server_name_sig'][0]
        server_login = query['server_login'][0]
        server_login_sig = query['server_login_sig'][0]
        username = query['login'][0]
        name = query['name'][0]
        email = query['email'][0]
        extra = query['extra'][0]
        redirect = query['redirect'][0]
    except (KeyError, ValueError) as exc:
        raise HTTP400('Incomplete form submission: %s' % exc)

    announcements = query.get('announcements', [None])[0]

    # Bail out if someone corrupted the form input.
    secret = config['secret']
    name_sig = sha('%s%s' % (server_name, secret)).hexdigest()
    login_sig = sha('%s%s' % (server_login, secret)).hexdigest()
    if name_sig != server_name_sig or login_sig != server_login_sig:
        raise HTTP400('Invalid request')

    user = User(username)
    try:
        store.get(user)
        raise HTTP400('That username is not available.')
    except StoreError:  # we expect and want this
        pass

    user.add_role(DEFAULT_ROLE)
    user.note = simplejson.dumps({
        'registered': time(),
        'name': name,
        'email': email,
        'extra': extra,
        'announcements': announcements is not None
    })

    map_bag_name = config.get('magicuser.map', 'MAPUSER')
    ensure_bag(map_bag_name, store, policy_dict=MAP_USER_POLICY)
    tiddler = Tiddler(server_login, map_bag_name)
    try:
        store.get(tiddler)
        raise HTTP400('That remote user is already mapped')
    except StoreError:
        pass
    tiddler.fields['mapped_user'] = username

    store.put(tiddler)
    store.put(user)

    create_wiki(environ,
                '_%s-data' % username,
                mode='private',
                username=username,
                desc='Data Files',
                validate=False)
    create_wiki(environ,
                '%s-notebook' % username,
                mode='private',
                username=username,
                desc='Private Notebook',
                validate=False)
    create_wiki(environ,
                '%s' % username,
                mode='protected',
                username=username,
                desc='Share Stuff',
                validate=False)

    redirect_uri = '%s%s' % (server_base_url(environ), redirect)
    secret = config['secret']
    cookie_age = config.get('cookie_age', None)
    cookie_header_string = make_cookie('tiddlyweb_user',
                                       server_login,
                                       mac_key=secret,
                                       path='/',
                                       expires=cookie_age)
    start_response('303 See Other', [('Set-Cookie', cookie_header_string),
                                     ('Content-Type', 'text/plain'),
                                     ('Location', str(redirect_uri))])
    return [redirect_uri]
def test_create_map_uses_user():
    global AUTH_COOKIE
    http = httplib2.Http()
    response, content = http.request(
        "http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form",
        body="user=cdent&password=cow",
        method="POST",
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    )
    assert response.previous["status"] == "303"

    user_cookie = response.previous["set-cookie"]
    cookie = Cookie.SimpleCookie()
    cookie.load(user_cookie)
    AUTH_COOKIE = cookie["tiddlyweb_user"].value

    bad_second_cookie = make_cookie("tiddlyweb_secondary_user", "x.auth.thing", mac_key="slippy")
    mismatch_second_cookie = make_cookie("tiddlyweb_secondary_user", "y.auth.thing", mac_key=secret)
    second_cookie = make_cookie("tiddlyweb_secondary_user", "x.auth.thing", mac_key=secret)

    # we must have the second cookie
    response, content = http.request(
        "http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing",
        method="PUT",
        headers={"Content-Type": "application/json", "Cookie": 'tiddlyweb_user="******"' % AUTH_COOKIE},
        body='{"text":"house"}',
    )
    assert response["status"] == "409", content
    assert "secondary cookie not present" in content

    response, content = http.request(
        "http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing",
        method="PUT",
        headers={
            "Content-Type": "application/json",
            "Cookie": 'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, bad_second_cookie),
        },
        body='{"text":"house"}',
    )
    assert response["status"] == "409", content
    assert "secondary cookie invalid" in content

    response, content = http.request(
        "http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing",
        method="PUT",
        headers={
            "Content-Type": "application/json",
            "Cookie": 'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, mismatch_second_cookie),
        },
        body='{"text":"house"}',
    )
    assert response["status"] == "409", content
    assert "secondary cookie mismatch" in content

    response, content = http.request(
        "http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing",
        method="PUT",
        headers={
            "Content-Type": "application/json",
            "Cookie": 'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, second_cookie),
        },
        body='{"text":"house"}',
    )
    assert response["status"] == "204"

    response, content = http.request(
        "http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing",
        method="GET",
        headers={"Accept": "application/json", "Cookie": 'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, second_cookie)},
    )
    assert response["status"] == "403"
    assert "may not read" in content

    tiddler = Tiddler("x.auth.thing", "MAPUSER")
    tiddler = store.get(tiddler)
    assert tiddler.modifier == "cdent"
    assert tiddler.text == ""
    assert "mapped_user" in tiddler.fields
    assert tiddler.fields["mapped_user"] == "cdent"

    response, content = http.request(
        "http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing",
        method="PUT",
        headers={
            "Content-Type": "application/json",
            "Cookie": 'tiddlyweb_user="******"; %s' % (AUTH_COOKIE, second_cookie),
        },
        body="{}",
    )
    assert response["status"] == "403"
    assert "may not write" in content
Example #37
0
def test_cookie_expire():
    string = make_cookie('test3', 'alpha3', expires=50)

    assert string == 'test3=alpha3; Max-Age=50; httponly'
Example #38
0
def test_cookie_mac():
    string = make_cookie('test4', 'alpha4', mac_key='secret')

    secret_string = sha('%s%s' % ('alpha4', 'secret')).hexdigest()

    assert string == 'test4="alpha4:%s"; httponly' % secret_string
Example #39
0
def test_cookie_domain():
    string = make_cookie('test5', 'alpha5', domain=".tiddlyspace.com")

    assert string == 'test5=alpha5; Domain=.tiddlyspace.com; httponly'
Example #40
0
def test_unicode_cookie_value():
    string = make_cookie('tiddlyweb', u'\u3454')
    assert string == 'tiddlyweb=%E3%91%94; httponly'
def test_create_map_uses_user():
    global AUTH_COOKIE
    http = httplib2.Http()
    response, content = http.request(
            'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
            body='user=cdent&password=cow',
            method='POST',
            headers={'Content-Type': 'application/x-www-form-urlencoded'})
    assert response.previous['status'] == '303'

    user_cookie = response.previous['set-cookie']
    cookie = Cookie.SimpleCookie()
    cookie.load(user_cookie)
    AUTH_COOKIE = cookie['tiddlyweb_user'].value

    bad_second_cookie = make_cookie('tiddlyweb_secondary_user',
            'x.auth.thing', mac_key='slippy')
    mismatch_second_cookie = make_cookie('tiddlyweb_secondary_user',
            'y.auth.thing', mac_key=secret)
    second_cookie = make_cookie('tiddlyweb_secondary_user',
            'x.auth.thing', mac_key=secret)

# we must have the second cookie
    response, content = http.request(
            'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
            method='PUT',
            headers={'Content-Type': 'application/json',
                'Cookie': 'tiddlyweb_user="******"' % AUTH_COOKIE},
            body='{"text":"house"}')
    assert response['status'] == '409', content
    assert 'secondary cookie not present' in content

    response, content = http.request(
            'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
            method='PUT',
            headers={'Content-Type': 'application/json',
                'Cookie': 'tiddlyweb_user="******"; %s' % (
                    AUTH_COOKIE, bad_second_cookie)},
            body='{"text":"house"}')
    assert response['status'] == '409', content
    assert 'secondary cookie invalid' in content

    response, content = http.request(
            'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
            method='PUT',
            headers={'Content-Type': 'application/json',
                'Cookie': 'tiddlyweb_user="******"; %s' % (
                    AUTH_COOKIE, mismatch_second_cookie)},
            body='{"text":"house"}')
    assert response['status'] == '409', content
    assert 'secondary cookie mismatch' in content

    response, content = http.request(
            'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
            method='PUT',
            headers={'Content-Type': 'application/json',
                'Cookie': 'tiddlyweb_user="******"; %s' % (
                    AUTH_COOKIE, second_cookie)},
            body='{"text":"house"}')
    assert response['status'] == '204'

    response, content = http.request(
            'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
            method='GET',
            headers={'Accept': 'application/json',
                'Cookie': 'tiddlyweb_user="******"; %s' % (
                    AUTH_COOKIE, second_cookie)})
    assert response['status'] == '403'
    assert 'may not read' in content 

    tiddler = Tiddler('x.auth.thing', 'MAPUSER')
    tiddler = store.get(tiddler)
    assert tiddler.modifier == 'cdent'
    assert tiddler.text == ''
    assert 'mapped_user' in tiddler.fields
    assert tiddler.fields['mapped_user'] == 'cdent'

    response, content = http.request(
            'http://0.0.0.0:8080/bags/MAPUSER/tiddlers/x.auth.thing',
            method='PUT',
            headers={'Content-Type': 'application/json',
                'Cookie': 'tiddlyweb_user="******"; %s' % (
                    AUTH_COOKIE, second_cookie)},
            body='{}')
    assert response['status'] == '403'
    assert 'may not write' in content
Example #42
0
def test_cookie_path():
    string = make_cookie("test2", "alpha2", path="/path/to/location")

    assert string == "test2=alpha2; Path=/path/to/location"
Example #43
0
def test_cookie_mac():
    string = make_cookie("test4", "alpha4", mac_key="secret")

    secret_string = sha("%s%s" % ("alpha4", "secret")).hexdigest()

    assert string == 'test4="alpha4:%s"' % secret_string
Example #44
0
def test_cookie_name_value():
    string = make_cookie('test1', 'alpha1')

    assert string == 'test1=alpha1; httponly'