Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix curl, add tests, add CI actions #14

Merged
merged 1 commit into from
Feb 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: Lint

on:
push:
paths:
- '**.py'
pull_request:
paths:
- '**.py'

jobs:
flake8:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Install flake8
run: pip install flake8 flake8-async flake8-warnings
- name: Run flake8
uses: suo/flake8-github-action@releases/v1
with:
checkName: 'flake8'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
precommit:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- uses: pre-commit/action@v3.0.0
23 changes: 23 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Test

on:
push:
pull_request:

jobs:
tests:
runs-on: "ubuntu-latest"
name: Run tests
steps:
- name: Check out code
uses: "actions/checkout@v3"
- name: Set up Python 3.8
uses: "actions/setup-python@v4"
with:
python-version: 3.8
- name: Prepare test env
run: bash tests/setup.sh
- name: Run tests
run: |
pip install pytest
pytest tests
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
__pycache__/
.idea
.DS_Store
.pytest_cache
Empty file added custom_components/__init__.py
Empty file.
57 changes: 37 additions & 20 deletions custom_components/aerogarden/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
import json
import logging
import re
import urllib
Expand All @@ -9,7 +10,6 @@
import voluptuous as vol
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers.discovery import load_platform
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
from requests import RequestException

Expand All @@ -34,27 +34,38 @@
)


# cleanPassword assumes there is one or zero instances of password in the text
# replaces the password with <password>
def cleanPassword(text, password):
passwordLen = len(password)
if passwordLen == 0:
return text
replaceText = "<password>"
for i in range(len(text) + 1 - passwordLen):
if text[i : (i + passwordLen)] == password:
restOfString = text[(i + passwordLen) :]
text = text[:i] + replaceText + restOfString
break
return text


def postAndHandle(url, post_data, headers):
try:
r = requests.post(url, json=post_data, headers=headers)
r = requests.post(url, data=post_data, headers=headers)
except RequestException as ex:
_LOGGER.exception("Error communicating with aerogarden servers:\n %s", str(ex))
return False

try:
response = r.json()
except ValueError as ex:
if post_data["&userPwd"]:
# Remove password before printing
del post_data["&userPwd"]
# Remove password before printing
_LOGGER.exception(
"error: Could not marshall post request to json.\n post:\n%s\n\nexception:\n%s",
"error: Could not marshall post request to json.\nexception:\n%s",
str(r),
post_data,
ex,
)
return False
_LOGGER.debug(response)
return response


Expand Down Expand Up @@ -83,14 +94,17 @@ def error(self):
return self._error_msg

def login(self):
post_data = {
"mail": self._username,
"&userPwd": self._password,
}
post_data = "mail=" + self._username + "&userPwd=" + self._password
url = self._host + self._login_url

response = postAndHandle(url, post_data, self._headers)
_LOGGER.debug(
"Login URL: %s, post data: %s, headers: %s "
% (url, cleanPassword(str(post_data), self._password), self._headers)
Comment on lines +102 to +103

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information

This expression logs [sensitive data (password)](1) as clear text. This expression logs [sensitive data (password)](2) as clear text. This expression logs [sensitive data (password)](3) as clear text. This expression logs [sensitive data (password)](4) as clear text.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Password is filtered out

)

if not response:
_LOGGER.exception("Issue logging into aerogarden servers.")
return False

userid = response["code"]
Expand All @@ -99,6 +113,7 @@ def login(self):
else:
error_msg = "Login api call returned %s" % (response["code"])
self._error_msg = error_msg

_LOGGER.exception(error_msg)

def is_valid_login(self):
Expand Down Expand Up @@ -135,14 +150,16 @@ def light_toggle(self, macaddr):
)
return None

post_data = {
"airGuid": macaddr,
"chooseGarden": self.garden_property(macaddr, "chooseGarden"),
"userID": self._userid,
"plantConfig": '{ "lightTemp" : %d }'
% (self.garden_property(macaddr, "lightTemp"))
# TODO: Light Temp may not matter, check.
}
post_data = json.dumps(
{
"airGuid": macaddr,
"chooseGarden": self.garden_property(macaddr, "chooseGarden"),
"userID": self._userid,
"plantConfig": '{ "lightTemp" : %d }'
% (self.garden_property(macaddr, "lightTemp"))
# TODO: Light Temp may not matter, check.
}
)
url = self._host + self._update_url
_LOGGER.debug(f"Sending POST data to toggle light: {post_data}")

Expand Down
9 changes: 9 additions & 0 deletions requirements.test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
black
flake8
pytest
pytest-cov
coverage
homeassistant
requests
voluptuous
datetime
Empty file added tests/__init__.py
Empty file.
6 changes: 6 additions & 0 deletions tests/setup.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
SCRIPTPATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"

python3 -m pip install -r ${SCRIPTPATH}/../requirements.test.txt

cd "$SCRIPTPATH/../custom_components"
ln -sf ../tests test
27 changes: 27 additions & 0 deletions tests/test_password_cleaning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import pytest

from custom_components.aerogarden import cleanPassword


def test_clean_password() -> None:
"""Test function to clean passwords"""

password = ""
testText = ["", "small", "okayokay"]

for text in testText:
assert cleanPassword(text, password) == text

password = "pass"

testText = ["", "pass-in-front", "in-back-pass", "hellogoodbye", "pass"]
expectedText = [
"",
"<password>-in-front",
"in-back-<password>",
"hellogoodbye",
"<password>",
]

for i in range(len(testText)):
assert cleanPassword(testText[i], password) == expectedText[i]