This commit is contained in:
Paulus Schoutsen committed 2019-07-31 12:25:30 -07:00
1 parent da05dfe708
commit 4de97abc3a
2676 files changed
+163166 -140084

No files matched your search

+20 -18
View File
@@ -5,30 +5,32 @@ from homeassistant.setup import async_setup_component
from tests.common import ensure_auth_manager_loaded
BASE_CONFIG = [{
'name': 'Example',
'type': 'insecure_example',
'users': [{
'username': 'test-user',
'password': 'test-pass',
'name': 'Test Name'
}]
}]
BASE_CONFIG = [
{
"name": "Example",
"type": "insecure_example",
"users": [
{"username": "test-user", "password": "test-pass", "name": "Test Name"}
],
}
]
EMPTY_CONFIG = []
async def async_setup_auth(hass, aiohttp_client, provider_configs=BASE_CONFIG,
module_configs=EMPTY_CONFIG, setup_api=False):
async def async_setup_auth(
hass,
aiohttp_client,
provider_configs=BASE_CONFIG,
module_configs=EMPTY_CONFIG,
setup_api=False,
):
"""Set up authentication and create an HTTP client."""
hass.auth = await auth.auth_manager_from_config(
hass, provider_configs, module_configs)
hass, provider_configs, module_configs
)
ensure_auth_manager_loaded(hass.auth)
await async_setup_component(hass, 'auth', {
'http': {
'api_password': 'bla'
}
})
await async_setup_component(hass, "auth", {"http": {"api_password": "bla"}})
if setup_api:
await async_setup_component(hass, 'api', {})
await async_setup_component(hass, "api", {})
return await aiohttp_client(hass.http.app)
+65 -66
View File
@@ -15,127 +15,128 @@ def mock_session():
"""Mock aiohttp.ClientSession."""
mocker = AiohttpClientMocker()
with patch('aiohttp.ClientSession',
side_effect=lambda *args, **kwargs:
mocker.create_session(asyncio.get_event_loop())):
with patch(
"aiohttp.ClientSession",
side_effect=lambda *args, **kwargs: mocker.create_session(
asyncio.get_event_loop()
),
):
yield mocker
def test_client_id_scheme():
"""Test we enforce valid scheme."""
assert indieauth._parse_client_id('http://ex.com/')
assert indieauth._parse_client_id('https://ex.com/')
assert indieauth._parse_client_id("http://ex.com/")
assert indieauth._parse_client_id("https://ex.com/")
with pytest.raises(ValueError):
indieauth._parse_client_id('ftp://ex.com')
indieauth._parse_client_id("ftp://ex.com")
def test_client_id_path():
"""Test we enforce valid path."""
assert indieauth._parse_client_id('http://ex.com').path == '/'
assert indieauth._parse_client_id('http://ex.com/hello').path == '/hello'
assert indieauth._parse_client_id(
'http://ex.com/hello/.world').path == '/hello/.world'
assert indieauth._parse_client_id(
'http://ex.com/hello./.world').path == '/hello./.world'
assert indieauth._parse_client_id("http://ex.com").path == "/"
assert indieauth._parse_client_id("http://ex.com/hello").path == "/hello"
assert (
indieauth._parse_client_id("http://ex.com/hello/.world").path == "/hello/.world"
)
assert (
indieauth._parse_client_id("http://ex.com/hello./.world").path
== "/hello./.world"
)
with pytest.raises(ValueError):
indieauth._parse_client_id('http://ex.com/.')
indieauth._parse_client_id("http://ex.com/.")
with pytest.raises(ValueError):
indieauth._parse_client_id('http://ex.com/hello/./yo')
indieauth._parse_client_id("http://ex.com/hello/./yo")
with pytest.raises(ValueError):
indieauth._parse_client_id('http://ex.com/hello/../yo')
indieauth._parse_client_id("http://ex.com/hello/../yo")
def test_client_id_fragment():
"""Test we enforce valid fragment."""
with pytest.raises(ValueError):
indieauth._parse_client_id('http://ex.com/#yoo')
indieauth._parse_client_id("http://ex.com/#yoo")
def test_client_id_user_pass():
"""Test we enforce valid username/password."""
with pytest.raises(ValueError):
indieauth._parse_client_id('http://user@ex.com/')
indieauth._parse_client_id("http://user@ex.com/")
with pytest.raises(ValueError):
indieauth._parse_client_id('http://user:pass@ex.com/')
indieauth._parse_client_id("http://user:pass@ex.com/")
def test_client_id_hostname():
"""Test we enforce valid hostname."""
assert indieauth._parse_client_id('http://www.home-assistant.io/')
assert indieauth._parse_client_id('http://[::1]')
assert indieauth._parse_client_id('http://127.0.0.1')
assert indieauth._parse_client_id('http://10.0.0.0')
assert indieauth._parse_client_id('http://10.255.255.255')
assert indieauth._parse_client_id('http://172.16.0.0')
assert indieauth._parse_client_id('http://172.31.255.255')
assert indieauth._parse_client_id('http://192.168.0.0')
assert indieauth._parse_client_id('http://192.168.255.255')
assert indieauth._parse_client_id("http://www.home-assistant.io/")
assert indieauth._parse_client_id("http://[::1]")
assert indieauth._parse_client_id("http://127.0.0.1")
assert indieauth._parse_client_id("http://10.0.0.0")
assert indieauth._parse_client_id("http://10.255.255.255")
assert indieauth._parse_client_id("http://172.16.0.0")
assert indieauth._parse_client_id("http://172.31.255.255")
assert indieauth._parse_client_id("http://192.168.0.0")
assert indieauth._parse_client_id("http://192.168.255.255")
with pytest.raises(ValueError):
assert indieauth._parse_client_id('http://255.255.255.255/')
assert indieauth._parse_client_id("http://255.255.255.255/")
with pytest.raises(ValueError):
assert indieauth._parse_client_id('http://11.0.0.0/')
assert indieauth._parse_client_id("http://11.0.0.0/")
with pytest.raises(ValueError):
assert indieauth._parse_client_id('http://172.32.0.0/')
assert indieauth._parse_client_id("http://172.32.0.0/")
with pytest.raises(ValueError):
assert indieauth._parse_client_id('http://192.167.0.0/')
assert indieauth._parse_client_id("http://192.167.0.0/")
def test_parse_url_lowercase_host():
"""Test we update empty paths."""
assert indieauth._parse_url('http://ex.com/hello').path == '/hello'
assert indieauth._parse_url('http://EX.COM/hello').hostname == 'ex.com'
assert indieauth._parse_url("http://ex.com/hello").path == "/hello"
assert indieauth._parse_url("http://EX.COM/hello").hostname == "ex.com"
parts = indieauth._parse_url('http://EX.COM:123/HELLO')
assert parts.netloc == 'ex.com:123'
assert parts.path == '/HELLO'
parts = indieauth._parse_url("http://EX.COM:123/HELLO")
assert parts.netloc == "ex.com:123"
assert parts.path == "/HELLO"
def test_parse_url_path():
"""Test we update empty paths."""
assert indieauth._parse_url('http://ex.com').path == '/'
assert indieauth._parse_url("http://ex.com").path == "/"
async def test_verify_redirect_uri():
"""Test that we verify redirect uri correctly."""
assert await indieauth.verify_redirect_uri(
None,
'http://ex.com',
'http://ex.com/callback'
None, "http://ex.com", "http://ex.com/callback"
)
with patch.object(indieauth, 'fetch_redirect_uris',
side_effect=lambda *_: mock_coro([])):
with patch.object(
indieauth, "fetch_redirect_uris", side_effect=lambda *_: mock_coro([])
):
# Different domain
assert not await indieauth.verify_redirect_uri(
None,
'http://ex.com',
'http://different.com/callback'
None, "http://ex.com", "http://different.com/callback"
)
# Different scheme
assert not await indieauth.verify_redirect_uri(
None,
'http://ex.com',
'https://ex.com/callback'
None, "http://ex.com", "https://ex.com/callback"
)
# Different subdomain
assert not await indieauth.verify_redirect_uri(
None,
'https://sub1.ex.com',
'https://sub2.ex.com/callback'
None, "https://sub1.ex.com", "https://sub2.ex.com/callback"
)
async def test_find_link_tag(hass, mock_session):
"""Test finding link tag."""
mock_session.get("http://127.0.0.1:8000", text="""
mock_session.get(
"http://127.0.0.1:8000",
text="""
<!doctype html>
<html>
<head>
@@ -145,25 +146,23 @@ async def test_find_link_tag(hass, mock_session):
</head>
...
</html>
""")
redirect_uris = await indieauth.fetch_redirect_uris(
hass, "http://127.0.0.1:8000")
""",
)
redirect_uris = await indieauth.fetch_redirect_uris(hass, "http://127.0.0.1:8000")
assert redirect_uris == [
"hass://oauth2_redirect",
"http://127.0.0.1:8000/beer",
]
assert redirect_uris == ["hass://oauth2_redirect", "http://127.0.0.1:8000/beer"]
async def test_find_link_tag_max_size(hass, mock_session):
"""Test finding link tag."""
text = ''.join([
'<link rel="redirect_uri" href="/wine">',
("0" * 1024 * 10),
'<link rel="redirect_uri" href="/beer">',
])
text = "".join(
[
'<link rel="redirect_uri" href="/wine">',
("0" * 1024 * 10),
'<link rel="redirect_uri" href="/beer">',
]
)
mock_session.get("http://127.0.0.1:8000", text=text)
redirect_uris = await indieauth.fetch_redirect_uris(
hass, "http://127.0.0.1:8000")
redirect_uris = await indieauth.fetch_redirect_uris(hass, "http://127.0.0.1:8000")
assert redirect_uris == ["http://127.0.0.1:8000/wine"]
+187 -185
View File
@@ -16,360 +16,362 @@ from . import async_setup_auth
async def test_login_new_user_and_trying_refresh_token(hass, aiohttp_client):
"""Test logging in with new user and refreshing tokens."""
client = await async_setup_auth(hass, aiohttp_client, setup_api=True)
resp = await client.post('/auth/login_flow', json={
'client_id': CLIENT_ID,
'handler': ['insecure_example', None],
'redirect_uri': CLIENT_REDIRECT_URI,
})
resp = await client.post(
"/auth/login_flow",
json={
"client_id": CLIENT_ID,
"handler": ["insecure_example", None],
"redirect_uri": CLIENT_REDIRECT_URI,
},
)
assert resp.status == 200
step = await resp.json()
resp = await client.post(
'/auth/login_flow/{}'.format(step['flow_id']), json={
'client_id': CLIENT_ID,
'username': 'test-user',
'password': 'test-pass',
})
"/auth/login_flow/{}".format(step["flow_id"]),
json={"client_id": CLIENT_ID, "username": "test-user", "password": "test-pass"},
)
assert resp.status == 200
step = await resp.json()
code = step['result']
code = step["result"]
# Exchange code for tokens
resp = await client.post('/auth/token', data={
'client_id': CLIENT_ID,
'grant_type': 'authorization_code',
'code': code
})
resp = await client.post(
"/auth/token",
data={"client_id": CLIENT_ID, "grant_type": "authorization_code", "code": code},
)
assert resp.status == 200
tokens = await resp.json()
assert (
await hass.auth.async_validate_access_token(tokens['access_token'])
is not None
await hass.auth.async_validate_access_token(tokens["access_token"]) is not None
)
# Use refresh token to get more tokens.
resp = await client.post('/auth/token', data={
'client_id': CLIENT_ID,
'grant_type': 'refresh_token',
'refresh_token': tokens['refresh_token']
})
resp = await client.post(
"/auth/token",
data={
"client_id": CLIENT_ID,
"grant_type": "refresh_token",
"refresh_token": tokens["refresh_token"],
},
)
assert resp.status == 200
tokens = await resp.json()
assert 'refresh_token' not in tokens
assert "refresh_token" not in tokens
assert (
await hass.auth.async_validate_access_token(tokens['access_token'])
is not None
await hass.auth.async_validate_access_token(tokens["access_token"]) is not None
)
# Test using access token to hit API.
resp = await client.get('/api/')
resp = await client.get("/api/")
assert resp.status == 401
resp = await client.get('/api/', headers={
'authorization': 'Bearer {}'.format(tokens['access_token'])
})
resp = await client.get(
"/api/", headers={"authorization": "Bearer {}".format(tokens["access_token"])}
)
assert resp.status == 200
def test_auth_code_store_expiration():
"""Test that the auth code store will not return expired tokens."""
store, retrieve = auth._create_auth_code_store()
client_id = 'bla'
user = MockUser(id='mock_user')
client_id = "bla"
user = MockUser(id="mock_user")
now = utcnow()
with patch('homeassistant.util.dt.utcnow', return_value=now):
with patch("homeassistant.util.dt.utcnow", return_value=now):
code = store(client_id, user)
with patch('homeassistant.util.dt.utcnow',
return_value=now + timedelta(minutes=10)):
with patch(
"homeassistant.util.dt.utcnow", return_value=now + timedelta(minutes=10)
):
assert retrieve(client_id, RESULT_TYPE_USER, code) is None
with patch('homeassistant.util.dt.utcnow', return_value=now):
with patch("homeassistant.util.dt.utcnow", return_value=now):
code = store(client_id, user)
with patch('homeassistant.util.dt.utcnow',
return_value=now + timedelta(minutes=9, seconds=59)):
with patch(
"homeassistant.util.dt.utcnow",
return_value=now + timedelta(minutes=9, seconds=59),
):
assert retrieve(client_id, RESULT_TYPE_USER, code) == user
async def test_ws_current_user(hass, hass_ws_client, hass_access_token):
"""Test the current user command with homeassistant creds."""
assert await async_setup_component(hass, 'auth', {
'http': {
'api_password': 'bla'
}
})
assert await async_setup_component(hass, "auth", {"http": {"api_password": "bla"}})
refresh_token = await hass.auth.async_validate_access_token(
hass_access_token)
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
user = refresh_token.user
credential = Credentials(auth_provider_type='homeassistant',
auth_provider_id=None,
data={}, id='test-id')
credential = Credentials(
auth_provider_type="homeassistant", auth_provider_id=None, data={}, id="test-id"
)
user.credentials.append(credential)
assert len(user.credentials) == 1
client = await hass_ws_client(hass, hass_access_token)
await client.send_json({
'id': 5,
'type': auth.WS_TYPE_CURRENT_USER,
})
await client.send_json({"id": 5, "type": auth.WS_TYPE_CURRENT_USER})
result = await client.receive_json()
assert result['success'], result
assert result["success"], result
user_dict = result['result']
user_dict = result["result"]
assert user_dict['name'] == user.name
assert user_dict['id'] == user.id
assert user_dict['is_owner'] == user.is_owner
assert len(user_dict['credentials']) == 1
assert user_dict["name"] == user.name
assert user_dict["id"] == user.id
assert user_dict["is_owner"] == user.is_owner
assert len(user_dict["credentials"]) == 1
hass_cred = user_dict['credentials'][0]
assert hass_cred['auth_provider_type'] == 'homeassistant'
assert hass_cred['auth_provider_id'] is None
assert 'data' not in hass_cred
hass_cred = user_dict["credentials"][0]
assert hass_cred["auth_provider_type"] == "homeassistant"
assert hass_cred["auth_provider_id"] is None
assert "data" not in hass_cred
async def test_cors_on_token(hass, aiohttp_client):
"""Test logging in with new user and refreshing tokens."""
client = await async_setup_auth(hass, aiohttp_client)
resp = await client.options('/auth/token', headers={
'origin': 'http://example.com',
'Access-Control-Request-Method': 'POST',
})
assert resp.headers['Access-Control-Allow-Origin'] == 'http://example.com'
assert resp.headers['Access-Control-Allow-Methods'] == 'POST'
resp = await client.options(
"/auth/token",
headers={
"origin": "http://example.com",
"Access-Control-Request-Method": "POST",
},
)
assert resp.headers["Access-Control-Allow-Origin"] == "http://example.com"
assert resp.headers["Access-Control-Allow-Methods"] == "POST"
resp = await client.post('/auth/token', headers={
'origin': 'http://example.com'
})
assert resp.headers['Access-Control-Allow-Origin'] == 'http://example.com'
resp = await client.post("/auth/token", headers={"origin": "http://example.com"})
assert resp.headers["Access-Control-Allow-Origin"] == "http://example.com"
async def test_refresh_token_system_generated(hass, aiohttp_client):
"""Test that we can get access tokens for system generated user."""
client = await async_setup_auth(hass, aiohttp_client)
user = await hass.auth.async_create_system_user('Test System')
user = await hass.auth.async_create_system_user("Test System")
refresh_token = await hass.auth.async_create_refresh_token(user, None)
resp = await client.post('/auth/token', data={
'client_id': 'https://this-is-not-allowed-for-system-users.com/',
'grant_type': 'refresh_token',
'refresh_token': refresh_token.token,
})
resp = await client.post(
"/auth/token",
data={
"client_id": "https://this-is-not-allowed-for-system-users.com/",
"grant_type": "refresh_token",
"refresh_token": refresh_token.token,
},
)
assert resp.status == 400
result = await resp.json()
assert result['error'] == 'invalid_request'
assert result["error"] == "invalid_request"
resp = await client.post('/auth/token', data={
'grant_type': 'refresh_token',
'refresh_token': refresh_token.token,
})
resp = await client.post(
"/auth/token",
data={"grant_type": "refresh_token", "refresh_token": refresh_token.token},
)
assert resp.status == 200
tokens = await resp.json()
assert (
await hass.auth.async_validate_access_token(tokens['access_token'])
is not None
await hass.auth.async_validate_access_token(tokens["access_token"]) is not None
)
async def test_refresh_token_different_client_id(hass, aiohttp_client):
"""Test that we verify client ID."""
client = await async_setup_auth(hass, aiohttp_client)
user = await hass.auth.async_create_user('Test User')
user = await hass.auth.async_create_user("Test User")
refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID)
# No client ID
resp = await client.post('/auth/token', data={
'grant_type': 'refresh_token',
'refresh_token': refresh_token.token,
})
resp = await client.post(
"/auth/token",
data={"grant_type": "refresh_token", "refresh_token": refresh_token.token},
)
assert resp.status == 400
result = await resp.json()
assert result['error'] == 'invalid_request'
assert result["error"] == "invalid_request"
# Different client ID
resp = await client.post('/auth/token', data={
'client_id': 'http://example-different.com',
'grant_type': 'refresh_token',
'refresh_token': refresh_token.token,
})
resp = await client.post(
"/auth/token",
data={
"client_id": "http://example-different.com",
"grant_type": "refresh_token",
"refresh_token": refresh_token.token,
},
)
assert resp.status == 400
result = await resp.json()
assert result['error'] == 'invalid_request'
assert result["error"] == "invalid_request"
# Correct
resp = await client.post('/auth/token', data={
'client_id': CLIENT_ID,
'grant_type': 'refresh_token',
'refresh_token': refresh_token.token,
})
resp = await client.post(
"/auth/token",
data={
"client_id": CLIENT_ID,
"grant_type": "refresh_token",
"refresh_token": refresh_token.token,
},
)
assert resp.status == 200
tokens = await resp.json()
assert (
await hass.auth.async_validate_access_token(tokens['access_token'])
is not None
await hass.auth.async_validate_access_token(tokens["access_token"]) is not None
)
async def test_revoking_refresh_token(hass, aiohttp_client):
"""Test that we can revoke refresh tokens."""
client = await async_setup_auth(hass, aiohttp_client)
user = await hass.auth.async_create_user('Test User')
user = await hass.auth.async_create_user("Test User")
refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID)
# Test that we can create an access token
resp = await client.post('/auth/token', data={
'client_id': CLIENT_ID,
'grant_type': 'refresh_token',
'refresh_token': refresh_token.token,
})
resp = await client.post(
"/auth/token",
data={
"client_id": CLIENT_ID,
"grant_type": "refresh_token",
"refresh_token": refresh_token.token,
},
)
assert resp.status == 200
tokens = await resp.json()
assert (
await hass.auth.async_validate_access_token(tokens['access_token'])
is not None
await hass.auth.async_validate_access_token(tokens["access_token"]) is not None
)
# Revoke refresh token
resp = await client.post('/auth/token', data={
'token': refresh_token.token,
'action': 'revoke',
})
resp = await client.post(
"/auth/token", data={"token": refresh_token.token, "action": "revoke"}
)
assert resp.status == 200
# Old access token should be no longer valid
assert (
await hass.auth.async_validate_access_token(tokens['access_token'])
is None
)
assert await hass.auth.async_validate_access_token(tokens["access_token"]) is None
# Test that we no longer can create an access token
resp = await client.post('/auth/token', data={
'client_id': CLIENT_ID,
'grant_type': 'refresh_token',
'refresh_token': refresh_token.token,
})
resp = await client.post(
"/auth/token",
data={
"client_id": CLIENT_ID,
"grant_type": "refresh_token",
"refresh_token": refresh_token.token,
},
)
assert resp.status == 400
async def test_ws_long_lived_access_token(hass, hass_ws_client,
hass_access_token):
async def test_ws_long_lived_access_token(hass, hass_ws_client, hass_access_token):
"""Test generate long-lived access token."""
assert await async_setup_component(hass, 'auth', {'http': {}})
assert await async_setup_component(hass, "auth", {"http": {}})
ws_client = await hass_ws_client(hass, hass_access_token)
# verify create long-lived access token
await ws_client.send_json({
'id': 5,
'type': auth.WS_TYPE_LONG_LIVED_ACCESS_TOKEN,
'client_name': 'GPS Logger',
'lifespan': 365,
})
await ws_client.send_json(
{
"id": 5,
"type": auth.WS_TYPE_LONG_LIVED_ACCESS_TOKEN,
"client_name": "GPS Logger",
"lifespan": 365,
}
)
result = await ws_client.receive_json()
assert result['success'], result
assert result["success"], result
long_lived_access_token = result['result']
long_lived_access_token = result["result"]
assert long_lived_access_token is not None
refresh_token = await hass.auth.async_validate_access_token(
long_lived_access_token)
refresh_token = await hass.auth.async_validate_access_token(long_lived_access_token)
assert refresh_token.client_id is None
assert refresh_token.client_name == 'GPS Logger'
assert refresh_token.client_name == "GPS Logger"
assert refresh_token.client_icon is None
async def test_ws_refresh_tokens(hass, hass_ws_client, hass_access_token):
"""Test fetching refresh token metadata."""
assert await async_setup_component(hass, 'auth', {'http': {}})
assert await async_setup_component(hass, "auth", {"http": {}})
ws_client = await hass_ws_client(hass, hass_access_token)
await ws_client.send_json({
'id': 5,
'type': auth.WS_TYPE_REFRESH_TOKENS,
})
await ws_client.send_json({"id": 5, "type": auth.WS_TYPE_REFRESH_TOKENS})
result = await ws_client.receive_json()
assert result['success'], result
assert len(result['result']) == 1
token = result['result'][0]
refresh_token = await hass.auth.async_validate_access_token(
hass_access_token)
assert token['id'] == refresh_token.id
assert token['type'] == refresh_token.token_type
assert token['client_id'] == refresh_token.client_id
assert token['client_name'] == refresh_token.client_name
assert token['client_icon'] == refresh_token.client_icon
assert token['created_at'] == refresh_token.created_at.isoformat()
assert token['is_current'] is True
assert token['last_used_at'] == refresh_token.last_used_at.isoformat()
assert token['last_used_ip'] == refresh_token.last_used_ip
assert result["success"], result
assert len(result["result"]) == 1
token = result["result"][0]
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
assert token["id"] == refresh_token.id
assert token["type"] == refresh_token.token_type
assert token["client_id"] == refresh_token.client_id
assert token["client_name"] == refresh_token.client_name
assert token["client_icon"] == refresh_token.client_icon
assert token["created_at"] == refresh_token.created_at.isoformat()
assert token["is_current"] is True
assert token["last_used_at"] == refresh_token.last_used_at.isoformat()
assert token["last_used_ip"] == refresh_token.last_used_ip
async def test_ws_delete_refresh_token(hass, hass_ws_client,
hass_access_token):
async def test_ws_delete_refresh_token(hass, hass_ws_client, hass_access_token):
"""Test deleting a refresh token."""
assert await async_setup_component(hass, 'auth', {'http': {}})
assert await async_setup_component(hass, "auth", {"http": {}})
refresh_token = await hass.auth.async_validate_access_token(
hass_access_token)
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
ws_client = await hass_ws_client(hass, hass_access_token)
# verify create long-lived access token
await ws_client.send_json({
'id': 5,
'type': auth.WS_TYPE_DELETE_REFRESH_TOKEN,
'refresh_token_id': refresh_token.id
})
await ws_client.send_json(
{
"id": 5,
"type": auth.WS_TYPE_DELETE_REFRESH_TOKEN,
"refresh_token_id": refresh_token.id,
}
)
result = await ws_client.receive_json()
assert result['success'], result
refresh_token = await hass.auth.async_validate_access_token(
hass_access_token)
assert result["success"], result
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
assert refresh_token is None
async def test_ws_sign_path(hass, hass_ws_client, hass_access_token):
"""Test signing a path."""
assert await async_setup_component(hass, 'auth', {'http': {}})
assert await async_setup_component(hass, "auth", {"http": {}})
ws_client = await hass_ws_client(hass, hass_access_token)
refresh_token = await hass.auth.async_validate_access_token(
hass_access_token)
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
with patch('homeassistant.components.auth.async_sign_path',
return_value='hello_world') as mock_sign:
await ws_client.send_json({
'id': 5,
'type': auth.WS_TYPE_SIGN_PATH,
'path': '/api/hello',
'expires': 20
})
with patch(
"homeassistant.components.auth.async_sign_path", return_value="hello_world"
) as mock_sign:
await ws_client.send_json(
{
"id": 5,
"type": auth.WS_TYPE_SIGN_PATH,
"path": "/api/hello",
"expires": 20,
}
)
result = await ws_client.receive_json()
assert result['success'], result
assert result['result'] == {'path': 'hello_world'}
assert result["success"], result
assert result["result"] == {"path": "hello_world"}
assert len(mock_sign.mock_calls) == 1
hass, p_refresh_token, path, expires = mock_sign.mock_calls[0][1]
assert p_refresh_token == refresh_token.id
assert path == '/api/hello'
assert path == "/api/hello"
assert expires.total_seconds() == 20
+65 -67
View File
@@ -6,121 +6,119 @@ from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI
async def async_get_code(hass, aiohttp_client):
"""Return authorization code for link user tests."""
config = [{
'name': 'Example',
'type': 'insecure_example',
'users': [{
'username': 'test-user',
'password': 'test-pass',
'name': 'Test Name'
}]
}, {
'name': 'Example',
'id': '2nd auth',
'type': 'insecure_example',
'users': [{
'username': '2nd-user',
'password': '2nd-pass',
'name': '2nd Name'
}]
}]
config = [
{
"name": "Example",
"type": "insecure_example",
"users": [
{"username": "test-user", "password": "test-pass", "name": "Test Name"}
],
},
{
"name": "Example",
"id": "2nd auth",
"type": "insecure_example",
"users": [
{"username": "2nd-user", "password": "2nd-pass", "name": "2nd Name"}
],
},
]
client = await async_setup_auth(hass, aiohttp_client, config)
user = await hass.auth.async_create_user(name='Hello')
user = await hass.auth.async_create_user(name="Hello")
refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID)
access_token = hass.auth.async_create_access_token(refresh_token)
# Now authenticate with the 2nd flow
resp = await client.post('/auth/login_flow', json={
'client_id': CLIENT_ID,
'handler': ['insecure_example', '2nd auth'],
'redirect_uri': CLIENT_REDIRECT_URI,
'type': 'link_user',
})
resp = await client.post(
"/auth/login_flow",
json={
"client_id": CLIENT_ID,
"handler": ["insecure_example", "2nd auth"],
"redirect_uri": CLIENT_REDIRECT_URI,
"type": "link_user",
},
)
assert resp.status == 200
step = await resp.json()
resp = await client.post(
'/auth/login_flow/{}'.format(step['flow_id']), json={
'client_id': CLIENT_ID,
'username': '2nd-user',
'password': '2nd-pass',
})
"/auth/login_flow/{}".format(step["flow_id"]),
json={"client_id": CLIENT_ID, "username": "2nd-user", "password": "2nd-pass"},
)
assert resp.status == 200
step = await resp.json()
return {
'user': user,
'code': step['result'],
'client': client,
'access_token': access_token,
"user": user,
"code": step["result"],
"client": client,
"access_token": access_token,
}
async def test_link_user(hass, aiohttp_client):
"""Test linking a user to new credentials."""
info = await async_get_code(hass, aiohttp_client)
client = info['client']
code = info['code']
client = info["client"]
code = info["code"]
# Link user
resp = await client.post('/auth/link_user', json={
'client_id': CLIENT_ID,
'code': code
}, headers={
'authorization': 'Bearer {}'.format(info['access_token'])
})
resp = await client.post(
"/auth/link_user",
json={"client_id": CLIENT_ID, "code": code},
headers={"authorization": "Bearer {}".format(info["access_token"])},
)
assert resp.status == 200
assert len(info['user'].credentials) == 1
assert len(info["user"].credentials) == 1
async def test_link_user_invalid_client_id(hass, aiohttp_client):
"""Test linking a user to new credentials."""
info = await async_get_code(hass, aiohttp_client)
client = info['client']
code = info['code']
client = info["client"]
code = info["code"]
# Link user
resp = await client.post('/auth/link_user', json={
'client_id': 'invalid',
'code': code
}, headers={
'authorization': 'Bearer {}'.format(info['access_token'])
})
resp = await client.post(
"/auth/link_user",
json={"client_id": "invalid", "code": code},
headers={"authorization": "Bearer {}".format(info["access_token"])},
)
assert resp.status == 400
assert len(info['user'].credentials) == 0
assert len(info["user"].credentials) == 0
async def test_link_user_invalid_code(hass, aiohttp_client):
"""Test linking a user to new credentials."""
info = await async_get_code(hass, aiohttp_client)
client = info['client']
client = info["client"]
# Link user
resp = await client.post('/auth/link_user', json={
'client_id': CLIENT_ID,
'code': 'invalid'
}, headers={
'authorization': 'Bearer {}'.format(info['access_token'])
})
resp = await client.post(
"/auth/link_user",
json={"client_id": CLIENT_ID, "code": "invalid"},
headers={"authorization": "Bearer {}".format(info["access_token"])},
)
assert resp.status == 400
assert len(info['user'].credentials) == 0
assert len(info["user"].credentials) == 0
async def test_link_user_invalid_auth(hass, aiohttp_client):
"""Test linking a user to new credentials."""
info = await async_get_code(hass, aiohttp_client)
client = info['client']
code = info['code']
client = info["client"]
code = info["code"]
# Link user
resp = await client.post('/auth/link_user', json={
'client_id': CLIENT_ID,
'code': code,
}, headers={'authorization': 'Bearer invalid'})
resp = await client.post(
"/auth/link_user",
json={"client_id": CLIENT_ID, "code": code},
headers={"authorization": "Bearer invalid"},
)
assert resp.status == 401
assert len(info['user'].credentials) == 0
assert len(info["user"].credentials) == 0
+53 -44
View File
@@ -9,98 +9,107 @@ from tests.common import CLIENT_ID, CLIENT_REDIRECT_URI
async def test_fetch_auth_providers(hass, aiohttp_client):
"""Test fetching auth providers."""
client = await async_setup_auth(hass, aiohttp_client)
resp = await client.get('/auth/providers')
resp = await client.get("/auth/providers")
assert resp.status == 200
assert await resp.json() == [{
'name': 'Example',
'type': 'insecure_example',
'id': None
}]
assert await resp.json() == [
{"name": "Example", "type": "insecure_example", "id": None}
]
async def test_fetch_auth_providers_onboarding(hass, aiohttp_client):
"""Test fetching auth providers."""
client = await async_setup_auth(hass, aiohttp_client)
with patch('homeassistant.components.onboarding.async_is_user_onboarded',
return_value=False):
resp = await client.get('/auth/providers')
with patch(
"homeassistant.components.onboarding.async_is_user_onboarded",
return_value=False,
):
resp = await client.get("/auth/providers")
assert resp.status == 400
assert await resp.json() == {
'message': 'Onboarding not finished',
'code': 'onboarding_required',
"message": "Onboarding not finished",
"code": "onboarding_required",
}
async def test_cannot_get_flows_in_progress(hass, aiohttp_client):
"""Test we cannot get flows in progress."""
client = await async_setup_auth(hass, aiohttp_client, [])
resp = await client.get('/auth/login_flow')
resp = await client.get("/auth/login_flow")
assert resp.status == 405
async def test_invalid_username_password(hass, aiohttp_client):
"""Test we cannot get flows in progress."""
client = await async_setup_auth(hass, aiohttp_client)
resp = await client.post('/auth/login_flow', json={
'client_id': CLIENT_ID,
'handler': ['insecure_example', None],
'redirect_uri': CLIENT_REDIRECT_URI
})
resp = await client.post(
"/auth/login_flow",
json={
"client_id": CLIENT_ID,
"handler": ["insecure_example", None],
"redirect_uri": CLIENT_REDIRECT_URI,
},
)
assert resp.status == 200
step = await resp.json()
# Incorrect username
resp = await client.post(
'/auth/login_flow/{}'.format(step['flow_id']), json={
'client_id': CLIENT_ID,
'username': 'wrong-user',
'password': 'test-pass',
})
"/auth/login_flow/{}".format(step["flow_id"]),
json={
"client_id": CLIENT_ID,
"username": "wrong-user",
"password": "test-pass",
},
)
assert resp.status == 200
step = await resp.json()
assert step['step_id'] == 'init'
assert step['errors']['base'] == 'invalid_auth'
assert step["step_id"] == "init"
assert step["errors"]["base"] == "invalid_auth"
# Incorrect password
resp = await client.post(
'/auth/login_flow/{}'.format(step['flow_id']), json={
'client_id': CLIENT_ID,
'username': 'test-user',
'password': 'wrong-pass',
})
"/auth/login_flow/{}".format(step["flow_id"]),
json={
"client_id": CLIENT_ID,
"username": "test-user",
"password": "wrong-pass",
},
)
assert resp.status == 200
step = await resp.json()
assert step['step_id'] == 'init'
assert step['errors']['base'] == 'invalid_auth'
assert step["step_id"] == "init"
assert step["errors"]["base"] == "invalid_auth"
async def test_login_exist_user(hass, aiohttp_client):
"""Test logging in with exist user."""
client = await async_setup_auth(hass, aiohttp_client, setup_api=True)
cred = await hass.auth.auth_providers[0].async_get_or_create_credentials(
{'username': 'test-user'})
{"username": "test-user"}
)
await hass.auth.async_get_or_create_user(cred)
resp = await client.post('/auth/login_flow', json={
'client_id': CLIENT_ID,
'handler': ['insecure_example', None],
'redirect_uri': CLIENT_REDIRECT_URI,
})
resp = await client.post(
"/auth/login_flow",
json={
"client_id": CLIENT_ID,
"handler": ["insecure_example", None],
"redirect_uri": CLIENT_REDIRECT_URI,
},
)
assert resp.status == 200
step = await resp.json()
resp = await client.post(
'/auth/login_flow/{}'.format(step['flow_id']), json={
'client_id': CLIENT_ID,
'username': 'test-user',
'password': 'test-pass',
})
"/auth/login_flow/{}".format(step["flow_id"]),
json={"client_id": CLIENT_ID, "username": "test-user", "password": "test-pass"},
)
assert resp.status == 200
step = await resp.json()
assert step['type'] == 'create_entry'
assert len(step['result']) > 1
assert step["type"] == "create_entry"
assert len(step["result"]) > 1
+77 -62
View File
@@ -10,90 +10,105 @@ from tests.common import MockUser, CLIENT_ID, ensure_auth_manager_loaded
async def test_ws_setup_depose_mfa(hass, hass_ws_client):
"""Test set up mfa module for current user."""
hass.auth = await auth_manager_from_config(
hass, provider_configs=[{
'type': 'insecure_example',
'users': [{
'username': 'test-user',
'password': 'test-pass',
'name': 'Test Name',
}]
}], module_configs=[{
'type': 'insecure_example',
'id': 'example_module',
'data': [{'user_id': 'mock-user', 'pin': '123456'}]
}])
hass,
provider_configs=[
{
"type": "insecure_example",
"users": [
{
"username": "test-user",
"password": "test-pass",
"name": "Test Name",
}
],
}
],
module_configs=[
{
"type": "insecure_example",
"id": "example_module",
"data": [{"user_id": "mock-user", "pin": "123456"}],
}
],
)
ensure_auth_manager_loaded(hass.auth)
await async_setup_component(hass, 'auth', {'http': {}})
await async_setup_component(hass, "auth", {"http": {}})
user = MockUser(id='mock-user').add_to_hass(hass)
user = MockUser(id="mock-user").add_to_hass(hass)
cred = await hass.auth.auth_providers[0].async_get_or_create_credentials(
{'username': 'test-user'})
{"username": "test-user"}
)
await hass.auth.async_link_user(user, cred)
refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID)
access_token = hass.auth.async_create_access_token(refresh_token)
client = await hass_ws_client(hass, access_token)
await client.send_json({
'id': 10,
'type': mfa_setup_flow.WS_TYPE_SETUP_MFA,
})
await client.send_json({"id": 10, "type": mfa_setup_flow.WS_TYPE_SETUP_MFA})
result = await client.receive_json()
assert result['id'] == 10
assert result['success'] is False
assert result['error']['code'] == 'no_module'
assert result["id"] == 10
assert result["success"] is False
assert result["error"]["code"] == "no_module"
await client.send_json({
'id': 11,
'type': mfa_setup_flow.WS_TYPE_SETUP_MFA,
'mfa_module_id': 'example_module',
})
await client.send_json(
{
"id": 11,
"type": mfa_setup_flow.WS_TYPE_SETUP_MFA,
"mfa_module_id": "example_module",
}
)
result = await client.receive_json()
assert result['id'] == 11
assert result['success']
assert result["id"] == 11
assert result["success"]
flow = result['result']
assert flow['type'] == data_entry_flow.RESULT_TYPE_FORM
assert flow['handler'] == 'example_module'
assert flow['step_id'] == 'init'
assert flow['data_schema'][0] == {'type': 'string', 'name': 'pin'}
flow = result["result"]
assert flow["type"] == data_entry_flow.RESULT_TYPE_FORM
assert flow["handler"] == "example_module"
assert flow["step_id"] == "init"
assert flow["data_schema"][0] == {"type": "string", "name": "pin"}
await client.send_json({
'id': 12,
'type': mfa_setup_flow.WS_TYPE_SETUP_MFA,
'flow_id': flow['flow_id'],
'user_input': {'pin': '654321'},
})
await client.send_json(
{
"id": 12,
"type": mfa_setup_flow.WS_TYPE_SETUP_MFA,
"flow_id": flow["flow_id"],
"user_input": {"pin": "654321"},
}
)
result = await client.receive_json()
assert result['id'] == 12
assert result['success']
assert result["id"] == 12
assert result["success"]
flow = result['result']
assert flow['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert flow['handler'] == 'example_module'
assert flow['data']['result'] is None
flow = result["result"]
assert flow["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert flow["handler"] == "example_module"
assert flow["data"]["result"] is None
await client.send_json({
'id': 13,
'type': mfa_setup_flow.WS_TYPE_DEPOSE_MFA,
'mfa_module_id': 'invalid_id',
})
await client.send_json(
{
"id": 13,
"type": mfa_setup_flow.WS_TYPE_DEPOSE_MFA,
"mfa_module_id": "invalid_id",
}
)
result = await client.receive_json()
assert result['id'] == 13
assert result['success'] is False
assert result['error']['code'] == 'disable_failed'
assert result["id"] == 13
assert result["success"] is False
assert result["error"]["code"] == "disable_failed"
await client.send_json({
'id': 14,
'type': mfa_setup_flow.WS_TYPE_DEPOSE_MFA,
'mfa_module_id': 'example_module',
})
await client.send_json(
{
"id": 14,
"type": mfa_setup_flow.WS_TYPE_DEPOSE_MFA,
"mfa_module_id": "example_module",
}
)
result = await client.receive_json()
assert result['id'] == 14
assert result['success']
assert result['result'] == 'done'
assert result["id"] == 14
assert result["success"]
assert result["result"] == "done"