chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,50 @@
from types import ModuleType
from flask import Blueprint
from flask_restx import Namespace
from libs.external_api import ExternalApi
bp = Blueprint("files", __name__, url_prefix="/files")
api = ExternalApi(
bp,
version="1.0",
title="Files API",
description="API for file operations including upload and preview",
)
files_ns = Namespace("files", description="File operations", path="/")
def _register_controllers() -> tuple[ModuleType, ...]:
"""Load route modules after their namespaces and schema models exist."""
from . import appdeploy_files, plugin_file_upload, tool_files, upload_file_delivery
return (
appdeploy_files,
plugin_file_upload,
tool_files,
upload_file_delivery,
)
(
appdeploy_files,
plugin_file_upload,
tool_files,
upload_file_delivery,
) = _register_controllers()
api.add_namespace(files_ns)
__all__ = [
"api",
"appdeploy_files",
"bp",
"files_ns",
"plugin_file_upload",
"tool_files",
"upload_file_delivery",
]
@@ -0,0 +1,401 @@
"""File endpoints reached with an AppDeploy file grant.
Upload, remote-upload, produce, and resolve authenticate with a Bearer grant;
content authenticates with a per-file token in the query string, because an
``<img src>`` cannot carry a header.
They stay on the public ``files`` blueprint rather than moving under
``inner_api``, whose contract is a fully trusted caller holding the master key.
None of the five meets it: ``content`` is a browser-facing surface, ``upload``
carries an end user's payload, and ``produced`` and ``resolve`` are called by
workers executing third-party plugin code. The one genuinely server-to-server
step, minting the grant, already lives in ``inner_api``.
"""
from __future__ import annotations
from typing import IO
from urllib.parse import quote
from uuid import UUID
from flask import Response, request
from flask_restx import Resource
from pydantic import BaseModel, Field, HttpUrl, ValidationError
from werkzeug.datastructures import FileStorage
import services
from controllers.common.errors import (
BlockedFileExtensionError,
FilenameNotExistsError,
FileTooLargeError,
NoFileUploadedError,
RemoteFileUploadError,
TooManyFilesError,
UnsupportedFileTypeError,
)
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.files import files_ns
from controllers.files.wraps import FileGrantInvalidError, GrantedFileNotFoundError, file_grant_required
from extensions.ext_application_services import application_services
from fields.base import ResponseModel
from fields.file_fields import FileResponse
from fields.file_grant_fields import ResolvedFileResponse
from libs.exception import BaseHTTPException
from libs.helper import dump_response
from services.entities.file_grant_entities import (
FileContent,
FileGrantClaims,
FileGrantContext,
FileGrantScope,
FileKind,
FileRef,
StoredUpload,
)
from services.errors.file_grant import (
EndUserNotFoundError,
InvalidFileGrantError,
RemoteFileUnavailableError,
TooManyFileRefsError,
)
from services.file_grant_service import MAX_FILE_GRANT_REFS
# Everything outside this whitelist is served as an attachment. Produced files
# carry a plugin-declared MIME type, so SVG and the rest of the XML family must
# never render in the viewer's origin.
INLINE_MIME_TYPES = frozenset({"image/png", "image/jpeg", "image/gif", "image/webp"})
class InvalidFileRequestError(BaseHTTPException):
error_code = "invalid_request"
description = "The file request is malformed."
code = 400
class FileRefPayload(BaseModel):
id: str
kind: FileKind
class RemoteFileUploadPayload(BaseModel):
url: HttpUrl = Field(description="Remote file URL to fetch and store")
class FileResolvePayload(BaseModel):
files: list[FileRefPayload] = Field(default_factory=list, max_length=MAX_FILE_GRANT_REFS)
class FileContentQuery(BaseModel):
token: str = Field(description="Signed content token scoped to this file")
class RemoteFileUploadResponse(FileResponse):
"""Dify's upload shape plus the ``url`` key its remote-upload clients read.
Dify has no service-api remote upload for this endpoint to stand in for, and
the web and console one it does have answers under ``url``. Carrying both
names lets a client of either move over untouched; they hold one URL.
"""
url: str
class ProducedFileResponse(ResponseModel):
id: str
name: str
size: int
mime_type: str | None = None
url: str
internal_url: str
class FileResolveResponse(ResponseModel):
files: list[ResolvedFileResponse]
register_schema_models(files_ns, RemoteFileUploadPayload, FileResolvePayload)
register_response_schema_models(
files_ns, FileResponse, RemoteFileUploadResponse, ProducedFileResponse, FileResolveResponse
)
@files_ns.route("/appdeploy/upload")
class GrantedFileUploadApi(Resource):
"""Store one uploaded file against the grant's end user."""
@file_grant_required(FileGrantScope.UPLOAD)
@files_ns.doc("grant_upload_file")
@files_ns.doc(
responses={
201: "File uploaded",
400: "No file uploaded, the file has no name, or its extension is blocked",
401: "Invalid grant",
403: "Grant lacks the upload scope",
413: "File too large",
415: "Unsupported file type",
}
)
@files_ns.response(201, "File uploaded", files_ns.models[FileResponse.__name__])
def post(self, grant: FileGrantClaims):
upload = _single_upload()
upload_file = _store_upload(
grant,
filename=upload.filename or "",
stream=upload.stream,
mimetype=upload.mimetype,
)
return _granted_file_response(upload_file), 201
@files_ns.route("/appdeploy/remote-upload")
class GrantedRemoteFileUploadApi(Resource):
"""Fetch a remote URL through the SSRF-safe fetcher and store it."""
@file_grant_required(FileGrantScope.UPLOAD)
@files_ns.doc("grant_upload_remote_file")
@files_ns.expect(files_ns.models[RemoteFileUploadPayload.__name__])
@files_ns.doc(
responses={
201: "Remote file uploaded",
400: "Invalid URL, unfetchable remote file, or a blocked extension",
401: "Invalid grant",
403: "Grant lacks the upload scope",
413: "File too large",
415: "Unsupported file type",
}
)
@files_ns.response(201, "Remote file uploaded", files_ns.models[RemoteFileUploadResponse.__name__])
def post(self, grant: FileGrantClaims):
try:
payload = RemoteFileUploadPayload.model_validate(files_ns.payload or {})
except ValidationError as exc:
raise InvalidFileRequestError(str(exc)) from exc
try:
upload_file = application_services().file_grants.store_remote_upload(
context=_grant_context(grant),
url=str(payload.url),
)
except RemoteFileUnavailableError as exc:
raise RemoteFileUploadError(f"Failed to fetch file from {payload.url}") from exc
except EndUserNotFoundError as exc:
raise GrantedFileNotFoundError() from exc
except services.errors.file.FileTooLargeError as exc:
raise FileTooLargeError(exc.description) from exc
except services.errors.file.BlockedFileExtensionError as exc:
raise BlockedFileExtensionError(exc.description) from exc
except services.errors.file.UnsupportedFileTypeError as caught_error:
raise UnsupportedFileTypeError() from caught_error
return _remote_granted_file_response(upload_file), 201
@files_ns.route("/appdeploy/produced")
class ProducedFileApi(Resource):
"""Store one file produced by a running workflow node."""
@file_grant_required(FileGrantScope.PRODUCE)
@files_ns.doc("grant_upload_produced_file")
@files_ns.doc(
responses={
201: "Produced file stored",
400: "No file uploaded",
401: "Invalid grant",
403: "Grant lacks the produce scope",
413: "File too large",
}
)
@files_ns.response(201, "Produced file stored", files_ns.models[ProducedFileResponse.__name__])
def post(self, grant: FileGrantClaims):
upload = _single_upload()
try:
tool_file, access = application_services().file_grants.store_produced(
context=_grant_context(grant),
filename=upload.filename,
stream=upload.stream,
mimetype=upload.mimetype,
)
except services.errors.file.FileTooLargeError as exc:
raise FileTooLargeError(exc.description) from exc
except EndUserNotFoundError as exc:
raise GrantedFileNotFoundError() from exc
return ProducedFileResponse(
id=tool_file.id,
name=tool_file.name,
size=tool_file.size,
mime_type=tool_file.mime_type,
url=access.external_url,
internal_url=access.internal_url,
).model_dump(mode="json"), 201
@files_ns.route("/appdeploy/resolve")
class GrantedFileResolveApi(Resource):
"""Re-check ownership and sign fresh URLs at the moment of use."""
@file_grant_required(FileGrantScope.RESOLVE)
@files_ns.doc("grant_resolve_files")
@files_ns.expect(files_ns.models[FileResolvePayload.__name__])
@files_ns.doc(
responses={
200: "Files resolved",
400: "Malformed request",
401: "Invalid grant",
403: "Grant lacks the resolve scope",
}
)
@files_ns.response(200, "Files resolved", files_ns.models[FileResolveResponse.__name__])
def post(self, grant: FileGrantClaims):
try:
payload = FileResolvePayload.model_validate(files_ns.payload or {})
except ValidationError as exc:
raise InvalidFileRequestError(str(exc)) from exc
refs = [FileRef(id=ref.id, kind=ref.kind) for ref in payload.files]
try:
resolved = application_services().file_grants.resolve_file_access(
context=_grant_context(grant),
refs=refs,
)
except EndUserNotFoundError as exc:
raise GrantedFileNotFoundError() from exc
except TooManyFileRefsError as exc:
raise InvalidFileRequestError(str(exc)) from exc
return FileResolveResponse(
files=[ResolvedFileResponse.from_resolved(ref.id, file) for ref, file in zip(refs, resolved, strict=True)]
).model_dump(mode="json")
@files_ns.route("/appdeploy/<uuid:file_id>/content")
class GrantedFileContentApi(Resource):
"""Stream one file's bytes to a holder of its content token."""
@files_ns.doc("grant_file_content")
@files_ns.doc(params=query_params_from_model(FileContentQuery))
@files_ns.doc(
responses={
200: "File stream returned",
401: "Invalid or expired content token",
404: "File not found",
}
)
def get(self, file_id: UUID):
try:
query = FileContentQuery.model_validate(request.args.to_dict(flat=True))
except ValidationError as exc:
raise FileGrantInvalidError() from exc
try:
content = application_services().file_grants.load_content(
token=query.token,
requested_file_id=str(file_id),
)
except InvalidFileGrantError as exc:
raise FileGrantInvalidError() from exc
if content is None:
raise GrantedFileNotFoundError()
return _content_response(content)
def _content_response(content: FileContent) -> Response:
mime_type = _normalized_mime_type(content.mime_type)
inline = mime_type in INLINE_MIME_TYPES
response = Response(
content.stream,
mimetype=mime_type if inline else "application/octet-stream",
direct_passthrough=True,
headers={},
)
response.headers["X-Content-Type-Options"] = "nosniff"
if not inline:
encoded_filename = quote(content.name or "")
response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}"
response.headers["Content-Type"] = "application/octet-stream"
# The sibling preview endpoints advertise `Accept-Ranges` for audio and video.
# Every such type downloads here, so the hint could only ever ride on a
# response no player will seek.
if content.size > 0:
response.headers["Content-Length"] = str(content.size)
return response
def _normalized_mime_type(mime_type: str | None) -> str:
return mime_type.split(";", 1)[0].strip().lower() if mime_type else ""
def _single_upload() -> FileStorage:
if "file" not in request.files:
raise NoFileUploadedError()
if len(request.files) > 1:
raise TooManyFilesError()
upload = request.files["file"]
if not upload.filename:
raise FilenameNotExistsError()
return upload
def _store_upload(
grant: FileGrantClaims,
*,
filename: str,
stream: IO[bytes],
mimetype: str,
) -> StoredUpload:
try:
return application_services().file_grants.store_upload(
context=_grant_context(grant),
filename=filename,
stream=stream,
mimetype=mimetype,
)
except EndUserNotFoundError as exc:
raise GrantedFileNotFoundError() from exc
except services.errors.file.FileTooLargeError as exc:
raise FileTooLargeError(exc.description) from exc
except services.errors.file.BlockedFileExtensionError as exc:
raise BlockedFileExtensionError(exc.description) from exc
except services.errors.file.UnsupportedFileTypeError as caught_error:
raise UnsupportedFileTypeError() from caught_error
def _grant_context(grant: FileGrantClaims) -> FileGrantContext:
return FileGrantContext(tenant_id=grant.tenant_id, app_id=grant.app_id, end_user_id=grant.sub)
def _granted_file_response(upload_file: StoredUpload) -> dict[str, object]:
"""Answer an upload exactly as dify's own upload endpoints answer it.
A client moving off ``POST /v1/files/upload`` must not have to read a second
shape, so the same model reads the same ``upload_files`` row: every key dify
leaves null for such a row is null here too. Only the value of ``source_url``
is ours. Dify signs a ``file-preview`` URL there and this channel signs a
content-token URL, which keeps that key's promise of a signed URL that
retrieves the file while keeping the grant its only way in.
"""
signed_url, _ = application_services().file_grants.content_urls(file_id=upload_file.id, kind=FileKind.UPLOAD)
return dump_response(FileResponse, upload_file) | {"source_url": signed_url}
def _remote_granted_file_response(upload_file: StoredUpload) -> dict[str, object]:
"""Answer a remote upload with the upload shape plus dify's ``url`` key.
Reuses the URL already signed for ``source_url`` rather than signing a
second one, so the two keys are one value under the two names dify's two
kinds of client look for.
"""
response = _granted_file_response(upload_file)
return response | {"url": response["source_url"]}
__all__ = [
"GrantedFileContentApi",
"GrantedFileResolveApi",
"GrantedFileUploadApi",
"GrantedRemoteFileUploadApi",
"ProducedFileApi",
]
@@ -0,0 +1,113 @@
"""Signed plugin file upload endpoint."""
from typing import Literal
from flask import request
from flask_restx import Resource
from flask_restx.api import HTTPStatus
from pydantic import BaseModel, Field
from controllers.common.errors import (
FilenameNotExistsError,
FileTooLargeError,
NoFileUploadedError,
UnsupportedFileTypeError,
)
from controllers.common.schema import (
JsonResponseWithStatus,
query_params_from_model,
register_response_schema_models,
register_schema_models,
)
from controllers.console.wraps import setup_required
from controllers.files import files_ns
from extensions.ext_application_services import application_services
from fields.file_fields import FileResponse
from libs.exception import BaseHTTPException
from libs.helper import dump_response
from services.errors.file import FileTooLargeError as ServiceFileTooLargeError
from services.errors.file import UnsupportedFileTypeError as ServiceUnsupportedFileTypeError
from services.plugin_file_upload_service import PluginFileUploadAccessDeniedError
class PluginUploadQuery(BaseModel):
timestamp: str = Field(..., description="Unix timestamp for signature verification")
nonce: str = Field(..., description="Random nonce for signature verification")
sign: str = Field(..., description="HMAC signature")
tenant_id: str = Field(..., description="Tenant identifier")
user_id: str = Field(..., description="User identifier")
user_from: Literal["account", "end-user"] | None = Field(default=None, description="User identity type")
conversation_id: str | None = Field(default=None, description="Conversation identifier")
max_size: int | None = Field(default=None, ge=0, description="Signed maximum file size in bytes")
class InvalidPluginFileUploadError(BaseHTTPException):
error_code = "invalid_plugin_file_upload"
description = "The plugin file upload request is invalid or expired."
code = HTTPStatus.FORBIDDEN
_PLUGIN_UPLOAD_PARAMS = {
**query_params_from_model(PluginUploadQuery),
"file": {
"description": "File to upload for plugin usage.",
"in": "formData",
"type": "file",
"required": True,
},
}
register_schema_models(files_ns, PluginUploadQuery)
register_response_schema_models(files_ns, FileResponse)
@files_ns.route("/upload/for-plugin")
class PluginUploadFileApi(Resource):
@setup_required
@files_ns.doc("upload_plugin_file")
@files_ns.doc(
description="Upload a file for plugin usage with signature verification",
consumes=["multipart/form-data"],
params=_PLUGIN_UPLOAD_PARAMS,
responses={
201: "File uploaded successfully",
400: "Invalid query parameters, no file was uploaded, or the file has no name",
403: "The signed upload request is invalid or expired",
413: "File too large",
415: "Unsupported file type",
},
)
@files_ns.response(HTTPStatus.CREATED, "File uploaded", files_ns.models[FileResponse.__name__])
def post(self) -> JsonResponseWithStatus:
args = PluginUploadQuery.model_validate(request.args.to_dict(flat=True))
file = request.files.get("file")
if file is None:
raise NoFileUploadedError()
if not file.filename:
raise FilenameNotExistsError()
if not file.mimetype:
raise UnsupportedFileTypeError()
try:
result = application_services().plugin_file_uploads.upload(
stream=file.stream,
filename=file.filename,
mimetype=file.mimetype,
tenant_id=args.tenant_id,
user_id=args.user_id,
user_from=args.user_from,
conversation_id=args.conversation_id,
timestamp=args.timestamp,
nonce=args.nonce,
sign=args.sign,
max_size=args.max_size,
)
except PluginFileUploadAccessDeniedError as error:
raise InvalidPluginFileUploadError() from error
except ServiceFileTooLargeError as error:
raise FileTooLargeError(error.description) from error
except ServiceUnsupportedFileTypeError as error:
raise UnsupportedFileTypeError() from error
return dump_response(FileResponse, result), HTTPStatus.CREATED
@@ -0,0 +1,81 @@
from urllib.parse import quote
from uuid import UUID
from flask import Response
from flask_restx import Resource
from pydantic import BaseModel, Field
from werkzeug.exceptions import Forbidden, NotFound
from controllers.common.file_response import enforce_download_for_html
from controllers.common.schema import query_params_from_model, register_schema_models
from controllers.console.wraps import model_validate
from controllers.files import files_ns
from extensions.ext_application_services import application_services
from services.tool_file_download_service import (
ToolFileDownloadAccessDeniedError,
ToolFileDownloadNotFoundError,
)
class ToolFileQuery(BaseModel):
timestamp: str = Field(..., description="Unix timestamp")
nonce: str = Field(..., description="Random nonce")
sign: str = Field(..., description="HMAC signature")
as_attachment: bool = Field(default=False, description="Download as attachment")
register_schema_models(files_ns, ToolFileQuery)
@files_ns.route("/tools/<uuid:file_id>.<string:extension>")
class ToolFileApi(Resource):
@files_ns.doc("get_tool_file")
@files_ns.doc(description="Download a tool file by ID using signed parameters")
@files_ns.doc(
params={
"file_id": "Tool file identifier",
"extension": "Expected file extension",
**query_params_from_model(ToolFileQuery),
}
)
@files_ns.doc(
responses={
200: "Tool file stream returned successfully",
403: "Forbidden - invalid signature",
404: "File not found",
}
)
@model_validate(ToolFileQuery)
def get(self, args: ToolFileQuery, file_id: UUID, extension: str) -> Response:
try:
download = application_services().tool_file_downloads.get_signed_file(
file_id=str(file_id),
timestamp=args.timestamp,
nonce=args.nonce,
sign=args.sign,
)
except ToolFileDownloadAccessDeniedError as error:
raise Forbidden("Invalid request.") from error
except ToolFileDownloadNotFoundError as error:
raise NotFound("file is not found") from error
response = Response(
download.content,
mimetype=download.mime_type,
direct_passthrough=True,
headers={},
)
if download.size > 0:
response.headers["Content-Length"] = str(download.size)
if args.as_attachment and download.filename:
encoded_filename = quote(download.filename)
response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}"
enforce_download_for_html(
response,
mime_type=download.mime_type,
filename=download.filename,
extension=extension,
)
return response
@@ -0,0 +1,183 @@
import os
from urllib.parse import quote
from uuid import UUID
from flask import Response
from flask_restx import Resource
from pydantic import BaseModel, Field
from werkzeug.exceptions import NotFound
from controllers.common.errors import UnsupportedFileTypeError
from controllers.common.file_response import enforce_download_for_html
from controllers.common.schema import query_params_from_model, register_schema_models
from controllers.console.wraps import model_validate
from controllers.files import files_ns
from extensions.ext_application_services import application_services
from services.errors.file import UnsupportedFileTypeError as UnsupportedFileTypeServiceError
from services.upload_file_delivery_service import (
UploadFileDelivery,
UploadFileDeliveryNotFoundError,
)
class FileSignatureQuery(BaseModel):
timestamp: str = Field(..., description="Unix timestamp used in the signature")
nonce: str = Field(..., description="Random string for signature")
sign: str = Field(..., description="HMAC signature")
class FilePreviewQuery(FileSignatureQuery):
as_attachment: bool = Field(default=False, description="Whether to download as attachment")
register_schema_models(files_ns, FileSignatureQuery, FilePreviewQuery)
_RANGE_MEDIA_TYPES = frozenset(
{
"audio/aac",
"audio/flac",
"audio/mp4",
"audio/mpeg",
"audio/ogg",
"audio/wav",
"audio/x-m4a",
"video/mp4",
"video/quicktime",
"video/webm",
}
)
def _is_svg_content(mime_type: str | None, filename: str | None, extension: str | None) -> bool:
normalized_mime_type = mime_type.split(";", 1)[0].strip().lower() if mime_type else ""
if normalized_mime_type == "image/svg+xml":
return True
normalized_extension = extension.lstrip(".").lower() if extension else ""
if normalized_extension == "svg":
return True
return bool(filename and os.path.splitext(filename)[1].lstrip(".").lower() == "svg")
@files_ns.route("/<uuid:file_id>/image-preview")
class ImagePreviewApi(Resource):
"""Deprecated endpoint for retrieving image previews."""
@files_ns.doc("get_image_preview")
@files_ns.doc(description="Retrieve a signed image preview for a file")
@files_ns.doc(
params={
"file_id": "ID of the file to preview",
**query_params_from_model(FileSignatureQuery),
}
)
@files_ns.doc(
responses={
200: "Image preview returned successfully",
404: "File not found or signature is invalid",
415: "Unsupported file type",
422: "Missing or invalid query parameters",
}
)
@model_validate(FileSignatureQuery)
def get(self, args: FileSignatureQuery, file_id: UUID) -> Response:
try:
delivery = application_services().upload_file_delivery.get_signed_image_preview(
file_id=str(file_id),
timestamp=args.timestamp,
nonce=args.nonce,
sign=args.sign,
)
except UploadFileDeliveryNotFoundError as error:
raise NotFound(str(error) or None) from error
except UnsupportedFileTypeServiceError as error:
raise UnsupportedFileTypeError() from error
return Response(delivery.content, mimetype=delivery.file.mime_type)
@files_ns.route("/<uuid:file_id>/file-preview")
class FilePreviewApi(Resource):
@files_ns.doc("get_file_preview")
@files_ns.doc(description="Download a file preview or attachment using signed parameters")
@files_ns.doc(
params={
"file_id": "ID of the file to preview",
**query_params_from_model(FilePreviewQuery),
}
)
@files_ns.doc(
responses={
200: "File stream returned successfully",
404: "File not found or signature is invalid",
422: "Missing or invalid query parameters",
}
)
@model_validate(FilePreviewQuery)
def get(self, args: FilePreviewQuery, file_id: UUID) -> Response:
try:
delivery = application_services().upload_file_delivery.get_signed_file_preview(
file_id=str(file_id),
timestamp=args.timestamp,
nonce=args.nonce,
sign=args.sign,
)
except UploadFileDeliveryNotFoundError as error:
raise NotFound(str(error) or None) from error
return self._build_response(delivery=delivery, as_attachment=args.as_attachment)
@staticmethod
def _build_response(*, delivery: UploadFileDelivery, as_attachment: bool) -> Response:
file = delivery.file
response = Response(delivery.content, mimetype=file.mime_type, direct_passthrough=True, headers={})
if file.mime_type in _RANGE_MEDIA_TYPES:
response.headers["Accept-Ranges"] = "bytes"
if file.size > 0:
response.headers["Content-Length"] = str(file.size)
is_svg = _is_svg_content(file.mime_type, file.name, file.extension)
if as_attachment or is_svg:
encoded_filename = quote(file.name)
response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}"
response.headers["Content-Type"] = "application/octet-stream"
if is_svg:
response.headers["X-Content-Type-Options"] = "nosniff"
enforce_download_for_html(
response,
mime_type=file.mime_type,
filename=file.name,
extension=file.extension,
)
return response
@files_ns.route("/workspaces/<uuid:workspace_id>/webapp-logo")
class WorkspaceWebappLogoApi(Resource):
@files_ns.doc("get_workspace_webapp_logo")
@files_ns.doc(description="Fetch the custom webapp logo for a workspace")
@files_ns.doc(
params={
"workspace_id": "Workspace identifier",
}
)
@files_ns.doc(
responses={
200: "Logo returned successfully",
404: "Webapp logo not configured",
415: "Unsupported file type",
}
)
def get(self, workspace_id: UUID) -> Response:
try:
delivery = application_services().upload_file_delivery.get_workspace_webapp_logo(
workspace_id=str(workspace_id),
)
except UploadFileDeliveryNotFoundError as error:
raise NotFound(str(error) or None) from error
except UnsupportedFileTypeServiceError as error:
raise UnsupportedFileTypeError() from error
return Response(delivery.content, mimetype=delivery.file.mime_type)
@@ -0,0 +1,57 @@
"""Bearer authentication for the AppDeploy file grant endpoints."""
from collections.abc import Callable
from functools import wraps
from flask import request
from extensions.ext_application_services import application_services
from libs.exception import BaseHTTPException
from services.entities.file_grant_entities import FileGrantClaims, FileGrantScope
class FileGrantInvalidError(BaseHTTPException):
error_code = "grant_invalid"
description = "The file grant is missing, malformed, or expired."
code = 401
class FileGrantScopeDeniedError(BaseHTTPException):
error_code = "grant_scope_denied"
description = "The file grant does not carry the required scope."
code = 403
class GrantedFileNotFoundError(BaseHTTPException):
error_code = "file_not_found"
description = "File not found."
code = 404
def file_grant_required[**P, R](scope: FileGrantScope) -> Callable[[Callable[P, R]], Callable[P, R]]:
"""Require a valid file grant carrying ``scope`` and inject its claims."""
def decorator(view: Callable[P, R]) -> Callable[P, R]:
@wraps(view)
def decorated(*args: P.args, **kwargs: P.kwargs) -> R:
kwargs["grant"] = _authenticated_claims(scope)
return view(*args, **kwargs)
return decorated
return decorator
def _authenticated_claims(scope: FileGrantScope) -> FileGrantClaims:
scheme, _, token = request.headers.get("Authorization", "").partition(" ")
if scheme.lower() != "bearer" or not token:
raise FileGrantInvalidError()
claims = application_services().file_grants.decode_grant(token)
if claims is None:
raise FileGrantInvalidError()
if scope not in claims.scopes:
raise FileGrantScopeDeniedError()
return claims