💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add URLRetrieve pipeline, closes #1100
davidmezzetti32e098af847b
diff --git a/src/python/txtai/pipeline/data/__init__.py b/src/python/txtai/pipeline/data/__init__.pyindex ccc18fb5..d82698cd 100644--- a/src/python/txtai/pipeline/data/__init__.py+++ b/src/python/txtai/pipeline/data/__init__.py@@ -8,3 +8,4 @@ from .segmentation import Segmentationfrom .tabular import Tabularfrom .textractor import Textractorfrom .tokenizer import Tokenizer+from .urlretrieve import URLRetrievediff --git a/src/python/txtai/pipeline/data/textractor.py b/src/python/txtai/pipeline/data/textractor.pyindex cb4f13e7..ed802ac1 100644--- a/src/python/txtai/pipeline/data/textractor.py+++ b/src/python/txtai/pipeline/data/textractor.py@@ -2,18 +2,15 @@Textractor module"""-import contextlib-import ipaddressimport os-import socketimport tempfilefrom urllib.parse import urlparse-from urllib.request import urlopen, Requestfrom .filetohtml import FileToHTMLfrom .htmltomd import HTMLToMarkdownfrom .segmentation import Segmentation+from .urlretrieve import URLRetrieveclass Textractor(Segmentation):@@ -54,6 +51,9 @@ class Textractor(Segmentation):# Safe open mode. When set only local temp urls (or a specified directory) and non-private URLs are supportedself.safeopen = os.path.realpath(tempfile.gettempdir() if isinstance(safeopen, bool) else safeopen) if safeopen else safeopen+ # URL retriever+ self.urlretrieve = URLRetrieve(self.headers, self.safeopen)+def text(self, text):# Check if text is a valid file path or urlpath, exists = self.valid(text)@@ -104,7 +104,8 @@ class Textractor(Segmentation):# Safe open validationif not self.safecheck(path):- raise IOError(f"Safeopen URL validation failed: path={os.path.realpath(path)}, safeopen={self.safeopen}")+ path = path if urlparse(path).scheme else os.path.realpath(path)+ raise IOError(f"Safeopen URL validation failed: path={path}, safeopen={self.safeopen}")# Consider local files and HTTP urls validreturn (path if exists or urlparse(path).scheme in ("http", "https") else None, exists)@@ -145,8 +146,7 @@ class Textractor(Segmentation):return f.read()# Remote file- with contextlib.closing(urlopen(Request(url, headers=self.headers))) as connection:- return connection.read()+ return self.urlretrieve(url)def safecheck(self, url):"""@@ -171,35 +171,6 @@ class Textractor(Segmentation):valid = prefix == self.safeopenelse:# URL validation- valid = url.lower().startswith("http") and not self.isprivateurl(url)+ valid = url.lower().startswith("http") and not self.urlretrieve.isprivateurl(url)return valid-- def isprivateurl(self, url):- """- Checks if URL refers to a private/internal IP address.-- Args:- url: input url-- Returns:- True if this is a private url, false otherwise- """-- # Assume the url is private until proven otherwise- private = True-- try:- host = urlparse(url).hostname- if host:- # Resolve IP Address- ip = ipaddress.ip_address(socket.gethostbyname(host))-- # Check if it's private- private = ip.is_private or ip.is_loopback-- # pylint: disable=W0718- except Exception:- pass-- return privatediff --git a/src/python/txtai/pipeline/data/urlretrieve.py b/src/python/txtai/pipeline/data/urlretrieve.pynew file mode 100644index 00000000..09a55a5c--- /dev/null+++ b/src/python/txtai/pipeline/data/urlretrieve.py@@ -0,0 +1,237 @@+"""+URLRetrieve module+"""++import contextlib+import ipaddress+import socket++from http.client import HTTPConnection, HTTPSConnection+from urllib.parse import urlparse, splitport+from urllib.request import (+ HTTPDefaultErrorHandler,+ HTTPErrorProcessor,+ HTTPHandler,+ HTTPSHandler,+ HTTPRedirectHandler,+ OpenerDirector,+ Request,+ UnknownHandler,+)++from ..base import Pipeline+++class URLRetrieve(Pipeline):+ """+ Retrieves content from HTTP(s) URLs.+ """++ def __init__(self, headers=None, safeopen=False):+ """+ Creates a new URLRetrieve pipeline.++ Args:+ headers: http headers+ safeopen: if safe validation checks should be enabled+ """++ # HTTP headers+ self.headers = headers if headers else {}++ # Safeopen mode+ self.safeopen = safeopen++ # Create a blank opener+ self.opener = OpenerDirector()++ # Register handlers+ for handler in [+ UnknownHandler(),+ HTTPDefaultErrorHandler(),+ HTTPErrorProcessor(),+ SafeHTTPHandler(self),+ SafeHTTPSHandler(self),+ SafeRedirectHandler(self),+ ]:+ self.opener.add_handler(handler)++ def __call__(self, url):+ """+ Retrieves content from url.++ Args:+ url: input url++ Returns:+ data+ """++ with contextlib.closing(self.opener.open(Request(url, headers=self.headers))) as connection:+ return connection.read()++ def isprivateurl(self, url):+ """+ Checks if URL refers to a private/internal IP address.++ Args:+ url: input url++ Returns:+ True if this is a private url, false otherwise+ """++ # Assume the url is private until proven otherwise+ private = True++ try:+ host = urlparse(url).hostname+ if host:+ _, private = self.resolveip(host)++ # pylint: disable=W0718+ except Exception:+ pass++ return private++ def resolveip(self, host):+ """+ Resolves the IP Address for host.++ Args:+ host: host name++ Returns:+ (ip address, True if this is a private ip)+ """++ # Resolve IP Address+ ip = socket.gethostbyname(host)++ # Check if it's private+ return (ip, not ipaddress.ip_address(ip).is_global)+++class SafeHTTPConnection(HTTPConnection):+ """+ HTTPConnection that pins to a supplied IP.+ """++ def __init__(self, host, ip, **kwargs):+ super().__init__(host, **kwargs)+ self.ip = ip++ def connect(self):+ self.sock = socket.create_connection(+ (self.ip, self.port),+ self.timeout or 5,+ self.source_address,+ )+++class SafeHTTPSConnection(HTTPSConnection):+ """+ HTTPSConnection that pins to a supplied IP.+ """++ def __init__(self, host, ip, **kwargs):+ super().__init__(host, **kwargs)+ self.ip = ip++ def connect(self):+ raw = socket.create_connection(+ (self.ip, self.port),+ self.timeout or 5,+ self.source_address,+ )++ self.sock = self._context.wrap_socket(raw, server_hostname=self.host)+++class SafeHTTPHandler(HTTPHandler):+ """+ SafeHTTPHandler that validates and pins a connection to an IP.+ """++ def __init__(self, instance):+ """+ Stores the current instance.++ Args:+ instance: validation instance+ """++ # Call parent constructor+ super().__init__()++ self.instance = instance++ def http_open(self, req):+ host = splitport(req.host)[0]++ # Validate and pin the IP Address+ ip, private = self.instance.resolveip(host)+ if self.instance.safeopen and private:+ raise IOError(f"Safeopen URL validation failed: host={host}")++ return self.do_open(+ lambda host, **kwargs: SafeHTTPConnection(host, ip, **kwargs),+ req,+ )+++class SafeHTTPSHandler(HTTPSHandler):+ """+ SafeHTTPSHandler that validates and pins a connection to an IP.+ """++ def __init__(self, instance):+ """+ Stores the current instance.++ Args:+ instance: validation instance+ """++ # Call parent constructor+ super().__init__()++ self.instance = instance++ def https_open(self, req):+ host = splitport(req.host)[0]++ # Validate and pin the IP Address+ ip, private = self.instance.resolveip(host)+ if self.instance.safeopen and private:+ raise IOError(f"Safeopen URL validation failed: host={host}")++ return self.do_open(+ lambda host, **kwargs: SafeHTTPSConnection(host, ip, **kwargs),+ req,+ )+++class SafeRedirectHandler(HTTPRedirectHandler):+ """+ Custom HTTPRedirectHandler that runs safe open url validation for each redirect hop.+ """++ def __init__(self, instance):+ """+ Stores the current instance.++ Args:+ instance: validation instance+ """++ self.instance = instance++ def redirect_request(self, req, fp, code, msg, headers, newurl):+ # Validate redirects are safe+ if self.instance.safeopen and self.instance.isprivateurl(newurl):+ raise IOError(f"Safeopen URL validation failed: url={newurl}")++ # Pass through when URL is safe+ return super().redirect_request(req, fp, code, msg, headers, newurl)diff --git a/test/python/testpipeline/testdata/testurlretrieve.py b/test/python/testpipeline/testdata/testurlretrieve.pynew file mode 100644index 00000000..11e06b34--- /dev/null+++ b/test/python/testpipeline/testdata/testurlretrieve.py@@ -0,0 +1,112 @@+"""+URLRetrieve module tests+"""++import contextlib+import unittest++from http.server import HTTPServer, BaseHTTPRequestHandler+from threading import Thread+from urllib.request import build_opener++from txtai.pipeline import URLRetrieve+from txtai.pipeline.data.urlretrieve import SafeRedirectHandler+++class RequestHandler(BaseHTTPRequestHandler):+ """+ Test HTTP handler.+ """++ def do_GET(self):+ """+ GET request handler.+ """++ if self.path == "/valid":+ redirect = "https://github.com/neuml/txtai"+ elif self.path == "/invalid":+ redirect = "http://127.0.0.1"+ else:+ redirect = None++ if redirect:+ self.send_response(301)+ self.send_header("Location", redirect)+ self.end_headers()+ else:+ response = "test".encode("utf-8")++ self.send_response(200)+ self.send_header("content-type", "text/plain")+ self.send_header("content-length", len(response))+ self.end_headers()++ self.wfile.write(response)+ self.wfile.flush()+++class TestURLRetrieve(unittest.TestCase):+ """+ URLRetrieve tests.+ """++ @classmethod+ def setUpClass(cls):+ """+ Create mock http server+ """++ cls.httpd = HTTPServer(("127.0.0.1", 8006), RequestHandler)++ server = Thread(target=cls.httpd.serve_forever, daemon=True)+ server.start()++ @classmethod+ def tearDownClass(cls):+ """+ Shutdown mock http server.+ """++ cls.httpd.shutdown()++ def testRedirect(self):+ """+ Test redirects+ """++ urlretrieve = URLRetrieve(safeopen=True)++ # Test redirect handler+ opener = build_opener(SafeRedirectHandler(urlretrieve))++ # Test valid direct+ with contextlib.closing(opener.open("http://127.0.0.1:8006/valid")) as connection:+ self.assertTrue("txtai is an all-in-one AI framework" in str(connection.read()))++ # Test invalid redirect+ with self.assertRaises(IOError):+ contextlib.closing(opener.open("http://127.0.0.1:8006/invalid"))++ def testRetrieve(self):+ """+ Test retrieval+ """++ urlretrieve = URLRetrieve()+ data = urlretrieve("http://127.0.0.1:8006/data")+ self.assertEqual(data, b"test")++ def testSafeopen(self):+ """+ Test safeopen checks+ """++ urlretrieve = URLRetrieve(safeopen=True)++ # Verify that local ip addresses fail+ with self.assertRaises(IOError):+ urlretrieve("http://127.0.0.1")++ with self.assertRaises(IOError):+ urlretrieve("https://127.0.0.1")