]> git.mxchange.org Git - fba.git/blob - fba/csrf.py
Continued:
[fba.git] / fba / csrf.py
1 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
2 # Copyright (C) 2023 Free Software Foundation
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published
6 # by the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17 import logging
18
19 from urllib.parse import urlparse
20
21 import bs4
22 import reqto
23 import requests
24
25 from fba.helpers import config
26 from fba.helpers import cookies
27 from fba.helpers import domain as domain_helper
28
29 from fba.http import network
30
31 from fba.models import instances
32
33 logging.basicConfig(level=logging.INFO)
34 logger = logging.getLogger(__name__)
35
36 def determine(domain: str, headers: dict) -> dict:
37     logger.debug("domain='%s',headers()=%d - CALLED!", domain, len(headers))
38     domain_helper.raise_on(domain)
39
40     if not isinstance(headers, dict):
41         raise ValueError(f"Parameter headers[]='{type(headers)}' is not 'dict'")
42
43     # Default headers with no CSRF
44     reqheaders = headers
45
46     # Fetch / to check for meta tag indicating csrf
47     logger.debug("Fetching / from domain='%s' for CSRF check ...", domain)
48     response = reqto.get(
49         f"https://{domain}/",
50         headers=network.web_headers,
51         timeout=(config.get("connection_timeout"), config.get("read_timeout"))
52     )
53     components = urlparse(response.url)
54
55     logger.debug("response.ok='%s',response.status_code=%d,response.text()=%d", response.ok, response.status_code, len(response.text))
56     if response.ok and response.status_code < 300 and response.text.strip() != "" and response.text.find("<html") > 0 and domain == components.netloc:
57         # Save cookies
58         logger.debug("Parsing response.text()=%d Bytes ...", len(response.text))
59         cookies.store(domain, response.cookies.get_dict())
60
61         # Parse text
62         meta = bs4.BeautifulSoup(
63             response.text,
64             "html.parser"
65         )
66         logger.debug("meta[]='%s'", type(meta))
67         tag = meta.find("meta", attrs={"name": "csrf-token"})
68
69         logger.debug("tag[%s]='%s'", type(tag), tag)
70         if tag is not None:
71             logger.debug("Adding CSRF token='%s' for domain='%s'", tag["content"], domain)
72             reqheaders["X-CSRF-Token"] = tag["content"]
73     elif domain != components.netloc:
74         logger.warning("domain='%s' doesn't match components.netloc='%s', maybe redirect to other domain?", domain, components.netloc)
75         message = f"Redirect from domain='{domain}' to components.netloc='{components.netloc}'"
76         instances.set_last_error(domain, message)
77         raise requests.exceptions.TooManyRedirects(message)
78
79     logger.debug("reqheaders()=%d - EXIT!", len(reqheaders))
80     return reqheaders