Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Add safeopen option for retrieve task, closes #1166

davidmezzetti3beea7f4bf0a
diff --git a/docs/api/security.md b/docs/api/security.md
index cbe4a791..6cadfe01 100644
--- a/docs/api/security.md
+++ b/docs/api/security.md
@@ -6,9 +6,9 @@ The default implementation of an API service runs via HTTP and is fully open. If
The default API service command starts a Uvicorn server as a HTTP service on port 8000. To run a HTTPS service, consider the following options.
-- [TLS Proxy Server](https://fastapi.tiangolo.com/deployment/https/). *Recommended choice*. With this configuration, the txtai API service runs as a HTTP service only accessible on the localhost/local network. The proxy server handles all encryption and redirects requests to local services. See this [example configuration](https://www.uvicorn.org/deployment/#running-behind-nginx) for more.
+- [TLS Proxy Server](https://fastapi.tiangolo.com/deployment/https/). *Recommended choice*. With this configuration, the txtai API service runs as a HTTP service only accessible on the localhost/local network. The proxy server handles all encryption and redirects requests to local services. See this [example configuration](https://www.uvicorn.dev/deployment/#running-behind-nginx) for more.
-- [Uvicorn SSL Certificate](https://www.uvicorn.org/deployment/). Another option is setting the SSL certificate on the Uvicorn service. This works in simple situations but gets complex when hosting multiple txtai or other related services.
+- [Uvicorn SSL Certificate](https://www.uvicorn.dev/deployment/). Another option is setting the SSL certificate on the Uvicorn service. This works in simple situations but gets complex when hosting multiple txtai or other related services.
## Authorization
@@ -31,3 +31,44 @@ curl \
It's important to note that HTTPS **must** be enabled using one of the methods mentioned above. Otherwise, tokens will be exchanged as clear text.
Authentication and Authorization can be fully customized. See the [dependencies](../customization#dependencies) section for more.
+
+## Safe Open
+
+Many components in txtai work with local files and have no restrictions on what files and urls can be accessed. The [textractor pipeline](../../pipeline/data/textractor) and [retrieve](../../workflow/task/retrieve) tasks both have a built-in option called `safeopen` which is enabled by default when running the API and applications. It enforces the following rules:
+
+- Local files must be in the safeopen directory (defaults to temp dir)
+- URLs must be public URLs (also has checks for redirects and DNS rebind attempts)
+
+The following workflow only allows accessing files stored in a specific directory along with public urls.
+
+```yaml
+workflow:
+ textract:
+ tasks:
+ - action: textractor
+```
+
+A number of of pipelines support reading local files. For these it's recommended to wrap those pipelines as workflows with a `retrieve` task. Note that pipelines can be created in-line and don't need to be exposed via the API.
+
+```yaml
+workflow:
+ caption:
+ tasks:
+ - task: retrieve
+ action: caption
+```
+
+Additionally, internal pipelines can be created but not exposed via the API.
+
+```yaml
+routes:
+ caption: False
+
+caption:
+
+workflow:
+ caption:
+ tasks:
+ - task: retrieve
+ action: caption
+```
diff --git a/src/python/txtai/app/base.py b/src/python/txtai/app/base.py
index 6e868978..c65af04a 100644
--- a/src/python/txtai/app/base.py
+++ b/src/python/txtai/app/base.py
@@ -291,6 +291,10 @@ class Application:
# Save resolved action(s)
task["action"] = actions[0] if not isinstance(action, list) else actions
+ if "task" in task and task["task"] == "retrieve":
+ # Default to safeopen enabled
+ task["safeopen"] = task.get("safeopen", True)
+
# Resolve initializer
if "initialize" in task and isinstance(task["initialize"], str):
task["initialize"] = self.function(task["initialize"])
@@ -350,6 +354,9 @@ class Application:
resolved function
"""
+ # Function configuration
+ config = {}
+
# Check if function is a pipeline
if function in self.pipelines:
return self.pipelines[function]
@@ -358,8 +365,12 @@ class Application:
if function in self.workflows:
return self.workflows[function]
+ if function in ("textractor", "urlretrieve"):
+ # Default to safeopen enabled
+ config["safeopen"] = config.get("safeopen", True)
+
# Attempt to resolve action as a callable function
- return PipelineFactory.create({}, function)
+ return PipelineFactory.create(config, function)
def search(self, query, limit=10, weights=None, index=None, parameters=None, graph=False):
"""
diff --git a/src/python/txtai/pipeline/data/__init__.py b/src/python/txtai/pipeline/data/__init__.py
index d82698cd..f63a7feb 100644
--- a/src/python/txtai/pipeline/data/__init__.py
+++ b/src/python/txtai/pipeline/data/__init__.py
@@ -4,6 +4,7 @@ Segment imports
from .filetohtml import FileToHTML
from .htmltomd import HTMLToMarkdown
+from .safeopen import SafeOpen
from .segmentation import Segmentation
from .tabular import Tabular
from .textractor import Textractor
diff --git a/src/python/txtai/pipeline/data/safeopen.py b/src/python/txtai/pipeline/data/safeopen.py
new file mode 100644
index 00000000..af95520c
--- /dev/null
+++ b/src/python/txtai/pipeline/data/safeopen.py
@@ -0,0 +1,108 @@
+"""
+SafeOpen module
+"""
+
+import os
+import tempfile
+
+from urllib.parse import urlparse
+
+from .urlretrieve import URLRetrieve
+
+
+class SafeOpen:
+ """
+ Safely open a local file or URL. When `safeopen` is enabled, the following rules are applied.
+
+ - Local files must be in the safeopen directory (defaults to temp dir)
+ - URLs must be public URLs (also has checks for redirects and DNS rebind attempts)
+ """
+
+ def __init__(self, headers=None, safeopen=False):
+ """
+ Creates a new safeopen instance.
+
+ Args:
+ safeopen: if safe validation checks should be enabled
+ """
+
+ # HTTP headers
+ self.headers = headers if headers else {}
+
+ # Safe open mode. When set only local temp urls (or a specified directory) and non-private URLs are supported
+ self.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 valid(self, path):
+ """
+ Checks if path is a valid local file or web url. Returns path if valid along with a flag
+ denoting if the path exists locally.
+
+ Args:
+ path: path to check
+
+ Returns:
+ (path, exists)
+ """
+
+ # Convert file urls to local paths
+ path = path.replace("file://", "")
+
+ # Check if this is a local file path or local file url
+ exists = os.path.exists(path)
+
+ # Safe open validation
+ if not self.safecheck(path):
+ 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 valid
+ return (path if exists or urlparse(path).scheme in ("http", "https") else None, exists)
+
+ def retrieve(self, url):
+ """
+ Retrieves content from url.
+
+ Args:
+ url: input url
+
+ Returns:
+ data
+ """
+
+ # Local file
+ if os.path.exists(url):
+ with open(url, "rb") as f:
+ return f.read()
+
+ # Remote file
+ return self.urlretrieve(url)
+
+ def safecheck(self, url):
+ """
+ Safe open url validation. Validates a local path is within the safeopen directory and
+ that URLs are a public HTTP(s) URLs.
+
+ Args:
+ url: input url
+
+ Returns:
+ True if url is valid, false otherwise
+ """
+
+ # Default to allow all urls when safe open is disabled
+ valid = True
+
+ if self.safeopen:
+ if os.path.exists(url):
+ # Validate local file is in safe path
+ path = os.path.realpath(url)
+ prefix = os.path.commonpath([self.safeopen, path])
+ valid = prefix == self.safeopen
+ else:
+ # URL validation
+ valid = url.lower().startswith("http") and not self.urlretrieve.isprivateurl(url)
+
+ return valid
diff --git a/src/python/txtai/pipeline/data/textractor.py b/src/python/txtai/pipeline/data/textractor.py
index e4ee99ad..4cfc3132 100644
--- a/src/python/txtai/pipeline/data/textractor.py
+++ b/src/python/txtai/pipeline/data/textractor.py
@@ -5,12 +5,10 @@ Textractor module
import os
import tempfile
-from urllib.parse import urlparse
-
from .filetohtml import FileToHTML
from .htmltomd import HTMLToMarkdown
+from .safeopen import SafeOpen
from .segmentation import Segmentation
-from .urlretrieve import URLRetrieve
class Textractor(Segmentation):
@@ -45,18 +43,12 @@ class Textractor(Segmentation):
# HTML to Markdown pipeline
self.markdown = HTMLToMarkdown(self.paragraphs, self.sections)
- # HTTP headers
- self.headers = headers if headers else {}
-
# Safe open mode. When set only local temp urls (or a specified directory) and non-private URLs are supported
- self.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)
+ self.safeopen = SafeOpen(headers, safeopen)
def text(self, text):
# Check if text is a valid file path or url
- path, exists = self.valid(text)
+ path, exists = self.safeopen.valid(text)
if not path:
# Not a valid file path, treat input as data
@@ -71,7 +63,7 @@ class Textractor(Segmentation):
html = self.html(path)
# FiletoHTML pipeline returns None when input is already HTML
- html = html if html else self.retrieve(path)
+ html = html if html else self.safeopen.retrieve(path)
# Delete temporary file
if not exists:
@@ -79,37 +71,11 @@ class Textractor(Segmentation):
else:
# Read data from url/path
- html = self.retrieve(path)
+ html = self.safeopen.retrieve(path)
# HTML to Markdown
return self.markdown(html)
- def valid(self, path):
- """
- Checks if path is a valid local file or web url. Returns path if valid along with a flag
- denoting if the path exists locally.
-
- Args:
- path: path to check
-
- Returns:
- (path, exists)
- """
-
- # Convert file urls to local paths
- path = path.replace("file://", "")
-
- # Check if this is a local file path or local file url
- exists = os.path.exists(path)
-
- # Safe open validation
- if not self.safecheck(path):
- 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 valid
- return (path if exists or urlparse(path).scheme in ("http", "https") else None, exists)
-
def download(self, url):
"""
Downloads content of url to a temporary file.
@@ -125,52 +91,6 @@ class Textractor(Segmentation):
path = output.name
# Retrieve and write data to temporary file
- output.write(self.retrieve(url))
+ output.write(self.safeopen.retrieve(url))
return path
-
- def retrieve(self, url):
- """
- Retrieves content from url.
-
- Args:
- url: input url
-
- Returns:
- data
- """
-
- # Local file
- if os.path.exists(url):
- with open(url, "rb") as f:
- return f.read()
-
- # Remote file
- return self.urlretrieve(url)
-
- def safecheck(self, url):
- """
- Safe open url validation. Validates a local path is within the safeopen directory and
- that URLs are a public HTTP(s) URLs.
-
- Args:
- url: input url
-
- Returns:
- True if url is valid, false otherwise
- """
-
- # Default to allow all urls when safe open is disabled
- valid = True
-
- if self.safeopen:
- if os.path.exists(url):
- # Validate local file is in safe path
- path = os.path.realpath(url)
- prefix = os.path.commonpath([self.safeopen, path])
- valid = prefix == self.safeopen
- else:
- # URL validation
- valid = url.lower().startswith("http") and not self.urlretrieve.isprivateurl(url)
-
- return valid
diff --git a/src/python/txtai/workflow/task/retrieve.py b/src/python/txtai/workflow/task/retrieve.py
index d68fd98b..c5fa2340 100644
--- a/src/python/txtai/workflow/task/retrieve.py
+++ b/src/python/txtai/workflow/task/retrieve.py
@@ -5,24 +5,26 @@ RetrieveTask module
import os
import tempfile
-from urllib.request import urlretrieve
from urllib.parse import urlparse
-from .url import UrlTask
+from ...pipeline import SafeOpen
+from .base import Task
-class RetrieveTask(UrlTask):
+class RetrieveTask(Task):
"""
- Task that retrieves urls (local or remote) to a local directory.
+ Task that retrieves files and urls (local or remote) to a local directory.
"""
- def register(self, directory=None, flatten=True):
+ def register(self, directory=None, flatten=True, headers=None, safeopen=False):
"""
Adds retrieve parameters to task.
Args:
directory: local directory used to store retrieved files
flatten: flatten input directory structure, defaults to True
+ headers: http headers
+ safeopen: if safe validation checks should be enabled
"""
# pylint: disable=W0201
@@ -38,24 +40,32 @@ class RetrieveTask(UrlTask):
self.directory = directory
self.flatten = flatten
+ self.safeopen = SafeOpen(headers, safeopen)
def prepare(self, element):
# Extract file path from URL
path = urlparse(element).path
- if self.flatten:
- # Flatten directory structure (default)
- path = os.path.join(self.directory, os.path.basename(path))
- else:
- # Derive output path
- path = os.path.join(self.directory, os.path.normpath(path.lstrip("/")))
- directory = os.path.dirname(path)
+ # Validate input element
+ url, _ = self.safeopen.valid(element)
+ if url:
+ if self.flatten:
+ # Flatten directory structure (default)
+ path = os.path.join(self.directory, os.path.basename(path))
+ else:
+ # Derive output path
+ path = os.path.join(self.directory, os.path.normpath(path.lstrip("/")))
+ directory = os.path.dirname(path)
- # Create local directory, if necessary
- os.makedirs(directory, exist_ok=True)
+ # Create local directory, if necessary
+ os.makedirs(directory, exist_ok=True)
- # Retrieve URL
- urlretrieve(element, path)
+ # Retrieve data
+ data = self.safeopen.retrieve(url)
+
+ # Write to destination path
+ with open(path, "wb") as output:
+ output.write(data)
# Return new file path
return path
diff --git a/test/python/testapi/testapiworkflow.py b/test/python/testapi/testapiworkflow.py
index 0bcf528d..875e9883 100644
--- a/test/python/testapi/testapiworkflow.py
+++ b/test/python/testapi/testapiworkflow.py
@@ -50,6 +50,10 @@ workflow:
args:
- [[positive, negative], false, True]
- null
+ retrieve:
+ tasks:
+ - task: retrieve
+ safeopen: /tmp/txtai
schedule:
schedule:
cron: '* * * * * *'
@@ -62,6 +66,9 @@ workflow:
tasks:
- action: segmentation
- action: index
+ textract:
+ tasks:
+ - action: textractor
get:
tasks:
- task: service
@@ -236,6 +243,20 @@ class TestWorkflow(unittest.TestCase):
results = self.client.post("workflow", json={"name": "multiaction", "elements": [text]}).json()
self.assertEqual(results[0], "['positive']. This is the best")
+ def testWorkflowRetrieve(self):
+ """
+ Test workflow with retrieve via API
+ """
+
+ # Check valid URL
+ results = self.client.post("workflow", json={"name": "retrieve", "elements": ["https://github.com/neuml/txtai"]}).json()
+ self.assertTrue(results[0].endswith("txtai"))
+
+ # Check invalid URLs
+ for url in ["http://192.168.1.1/path", "http://127.0.0.1/path", "http://invalid", "/etc/config", "/tmp/txtai-1/test"]:
+ with self.assertRaises(IOError):
+ self.client.post("workflow", json={"name": "retrieve", "elements": [url]})
+
def testWorkflowSegment(self):
"""
Test workflow with segmentation via API
@@ -249,6 +270,20 @@ class TestWorkflow(unittest.TestCase):
results = self.client.post("workflow", json={"name": "segment", "elements": [[0, text]]}).json()
self.assertEqual(len(results), 2)
+ def testWorkflowTextract(self):
+ """
+ Test workflow with textractor via API
+ """
+
+ # Check valid URL
+ results = self.client.post("workflow", json={"name": "textract", "elements": ["https://github.com/neuml/txtai"]}).json()
+ self.assertTrue("txtai is an all-in-one AI framework" in results[0])
+
+ # Check invalid URLs
+ for url in ["http://192.168.1.1/path", "http://127.0.0.1/path", "http://invalid", "/etc/config"]:
+ with self.assertRaises(IOError):
+ self.client.post("workflow", json={"name": "textract", "elements": [url]})
+
class TestInitFinal:
"""
diff --git a/test/python/testworkflow.py b/test/python/testworkflow.py
index 5851d73f..403a7e1b 100644
--- a/test/python/testworkflow.py
+++ b/test/python/testworkflow.py
@@ -27,6 +27,7 @@ from txtai.workflow import (
RetrieveTask,
StorageTask,
TemplateTask,
+ UrlTask,
WorkflowTask,
)
@@ -519,6 +520,16 @@ class TestWorkflow(unittest.TestCase):
results = np.array([x.numpy() for x in workflow(torch.tensor([2, 4, 6]))])
self.assertTrue(np.array_equal(np.array(results), np.array([[4, 16, 36], [8, 64, 216]])))
+ def testUrlWorkflow(self):
+ """
+ Test a url task
+ """
+
+ # Test url task
+ workflow = Workflow([UrlTask()])
+ results = list(workflow(["file://" + Utils.PATH + "/books.jpg"]))
+ self.assertTrue(results[0].endswith("books.jpg"))
+
def testYamlFunctionWorkflow(self):
"""
Test YAML workflow with a function action