1#! /usr/bin/env python
2# -*- coding: utf-8 -*-
3# vi:ts=4:et
4
5import unittest
6import pycurl
7import pytest
8
9from . import util
10
11sftp_server = 'sftp://web.sourceforge.net'
12
13@pytest.mark.online
14@pytest.mark.ssh
15class SshKeyCbTest(unittest.TestCase):
16    '''This test requires Internet access.'''
17
18    def setUp(self):
19        self.curl = util.DefaultCurl()
20        self.curl.setopt(pycurl.URL, sftp_server)
21        self.curl.setopt(pycurl.VERBOSE, True)
22
23    def tearDown(self):
24        self.curl.close()
25
26    @util.min_libcurl(7, 19, 6)
27    # curl compiled with libssh doesn't support
28    # CURLOPT_SSH_KNOWNHOSTS and CURLOPT_SSH_KEYFUNCTION
29    @util.guard_unknown_libcurl_option
30    def test_keyfunction(self):
31        # with keyfunction returning ok
32
33        def keyfunction(known_key, found_key, match):
34            return pycurl.KHSTAT_FINE
35
36        self.curl.setopt(pycurl.SSH_KNOWNHOSTS, '.known_hosts')
37        self.curl.setopt(pycurl.SSH_KEYFUNCTION, keyfunction)
38
39        try:
40            self.curl.perform()
41            self.fail('should have raised')
42        except pycurl.error as e:
43            self.assertEqual(pycurl.E_LOGIN_DENIED, e.args[0])
44
45        # with keyfunction returning not ok
46
47        def keyfunction(known_key, found_key, match):
48            return pycurl.KHSTAT_REJECT
49
50        self.curl.setopt(pycurl.SSH_KNOWNHOSTS, '.known_hosts')
51        self.curl.setopt(pycurl.SSH_KEYFUNCTION, keyfunction)
52
53        try:
54            self.curl.perform()
55            self.fail('should have raised')
56        except pycurl.error as e:
57            self.assertEqual(pycurl.E_PEER_FAILED_VERIFICATION, e.args[0])
58
59    @util.min_libcurl(7, 19, 6)
60    @util.guard_unknown_libcurl_option
61    def test_keyfunction_bogus_return(self):
62        def keyfunction(known_key, found_key, match):
63            return 'bogus'
64
65        self.curl.setopt(pycurl.SSH_KNOWNHOSTS, '.known_hosts')
66        self.curl.setopt(pycurl.SSH_KEYFUNCTION, keyfunction)
67
68        try:
69            self.curl.perform()
70            self.fail('should have raised')
71        except pycurl.error as e:
72            self.assertEqual(pycurl.E_PEER_FAILED_VERIFICATION, e.args[0])
73
74
75@pytest.mark.ssh
76class SshKeyCbUnsetTest(unittest.TestCase):
77    def setUp(self):
78        self.curl = util.DefaultCurl()
79        self.curl.setopt(pycurl.URL, sftp_server)
80        self.curl.setopt(pycurl.VERBOSE, True)
81
82    @util.min_libcurl(7, 19, 6)
83    @util.guard_unknown_libcurl_option
84    def test_keyfunction_none(self):
85        self.curl.setopt(pycurl.SSH_KEYFUNCTION, None)
86
87    @util.min_libcurl(7, 19, 6)
88    @util.guard_unknown_libcurl_option
89    def test_keyfunction_unset(self):
90        self.curl.unsetopt(pycurl.SSH_KEYFUNCTION)
91