Coverage for open_webui/utils/validate.py: 49%

47 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 05:07 +0000

1"""Validation utilities for user-supplied input.""" 

2 

3import io 

4import re 

5from urllib.parse import urlparse 

6 

7from open_webui.env import ( 

8 PROFILE_IMAGE_ALLOWED_MIME_TYPES, 

9 PROFILE_IMAGE_MAX_DATA_URI_SIZE, 

10) 

11from PIL import Image 

12 

13_USER_PROFILE_IMAGE_RE = re.compile(r'^/api/v1/users/[^/?#]+/profile/image$') 

14 

15# Data-URI prefix validator derived from PROFILE_IMAGE_ALLOWED_MIME_TYPES. 

16_mime_suffixes = '|'.join(re.escape(t.split('/')[-1]) for t in sorted(PROFILE_IMAGE_ALLOWED_MIME_TYPES)) 

17_SAFE_DATA_URI_RE = re.compile(rf'^data:image/({_mime_suffixes});base64,', re.IGNORECASE) 

18 

19# Exact relative paths accepted as profile images. These are the only 

20# static-asset paths OWUI itself assigns; no prefix/wildcard matching is 

21# used so that arbitrary relative paths cannot trigger authenticated GETs 

22# against internal endpoints when rendered as ``<img>`` sources. 

23# LICENSE covers the Open WebUI favicon fallback paths below. Do not alter, 

24# remove, obscure, or replace them except as LICENSE permits: 

25# https://docs.openwebui.com/license. 

26_SAFE_STATIC_PATHS = frozenset( 

27 { 

28 '/user.png', 

29 '/favicon.png', 

30 '/static/favicon.png', 

31 } 

32) 

33 

34 

35def validate_image_url(url: str, *, file_only: bool = False) -> str: 

36 """ 

37 Validate profile image URLs or canonical file URLs for model backgrounds. 

38 

39 With file_only=True, only /api/v1/files/<uuid>/content is accepted. 

40 This checks the URL only; file access and image bytes are checked when saving. 

41 

42 Profile formats (the default): 

43 - Empty string (falls back to default avatar) 

44 - Known static-asset paths assigned by OWUI (exact match) 

45 - The OWUI profile-image API route ``/api/v1/users/{id}/profile/image`` 

46 - ``http://`` and ``https://`` URLs with a valid hostname 

47 - ``data:image/{png,jpeg,gif,webp};base64,...`` URIs 

48 

49 Everything else is rejected, including: 

50 - Dangerous schemes (javascript:, file:, ftp:, …) 

51 - SVG data URIs (can contain embedded scripts) 

52 - Arbitrary relative paths (prevents authenticated GET triggers) 

53 - Scheme-relative URLs (``//host/path``) 

54 - data URIs larger than PROFILE_IMAGE_MAX_DATA_URI_SIZE bytes 

55 """ 

56 if not isinstance(url, str): 

57 raise ValueError('Invalid image URL.') 

58 

59 if file_only: 

60 if re.fullmatch(r'/api/v1/files/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/content', url): 60 ↛ 61line 60 didn't jump to line 61 because the condition on line 60 was never true

61 return url 

62 raise ValueError('Invalid background image URL: must reference an internal file.') 

63 

64 # --- Relative paths (exact match + anchored regex only) ----------- 

65 

66 if not url or url in _SAFE_STATIC_PATHS or _USER_PROFILE_IMAGE_RE.match(url): 

67 return url 

68 

69 # --- Absolute URLs ------------------------------------------------- 

70 

71 # urlparse normalises the scheme to lowercase, giving us 

72 # case-insensitive scheme matching for free. 

73 parsed = urlparse(url) 

74 

75 # External images served over HTTP(S), e.g. OAuth provider avatars. 

76 # Require a non-empty hostname (not just netloc, which can be ":80" 

77 # for a URL like http://:80/path with no actual host). 

78 if parsed.scheme in ('http', 'https'): 78 ↛ 79line 78 didn't jump to line 79 because the condition on line 78 was never true

79 if not parsed.hostname: 

80 raise ValueError('Invalid profile image URL: HTTP(S) URLs must include a host.') 

81 return url 

82 

83 # Base64-encoded raster images uploaded via the frontend. 

84 # The regex enforces the ;base64, boundary and is case-insensitive 

85 # per the data-URI / MIME-type specs. 

86 if _SAFE_DATA_URI_RE.match(url): 86 ↛ 87line 86 didn't jump to line 87 because the condition on line 86 was never true

87 if PROFILE_IMAGE_MAX_DATA_URI_SIZE and len(url) > PROFILE_IMAGE_MAX_DATA_URI_SIZE: 

88 raise ValueError( 

89 f'Invalid profile image URL: data URI exceeds the {PROFILE_IMAGE_MAX_DATA_URI_SIZE}-byte limit.' 

90 ) 

91 return url 

92 

93 raise ValueError( 

94 'Invalid profile image URL: must be a known internal path, ' 

95 'an HTTP(S) URL with a host, or a data:image URI (png/jpeg/gif/webp).' 

96 ) 

97 

98 

99BACKGROUND_IMAGE_MAX_BYTES = 5 * 1024 * 1024 

100BACKGROUND_IMAGE_MAX_PIXELS = 25_000_000 

101BACKGROUND_IMAGE_MIME_TYPES = {'PNG': 'image/png', 'JPEG': 'image/jpeg', 'WEBP': 'image/webp', 'GIF': 'image/gif'} 

102 

103 

104def validate_background_image(data: bytes) -> str: 

105 if len(data) > BACKGROUND_IMAGE_MAX_BYTES: 

106 raise ValueError('Background image must be at most 5 MiB.') 

107 try: 

108 with Image.open(io.BytesIO(data)) as image: 

109 content_type = BACKGROUND_IMAGE_MIME_TYPES.get(image.format) 

110 if not content_type: 

111 raise ValueError('Background image must be PNG, JPEG, WebP, or GIF.') 

112 if image.width * image.height > BACKGROUND_IMAGE_MAX_PIXELS: 

113 raise ValueError('Background image must be at most 25 megapixels.') 

114 image.verify() 

115 # verify() does not decode pixels for every format. 

116 with Image.open(io.BytesIO(data)) as image: 

117 image.load() 

118 except (OSError, SyntaxError, Image.DecompressionBombError) as error: 

119 raise ValueError('Invalid background image.') from error 

120 return content_type