File size: 8,222 Bytes
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
"""Utilities for the PLUG challenge Space.

Username and link checking, ported from the OpenADMET blind-challenge template
(including its SSRF guard on user-supplied URLs) with the S3 layer removed —
storage lives in ``plug_challenge.store``.
"""

import ipaddress
import re
import socket
import time
from urllib.parse import urljoin, urlparse

import requests
from loguru import logger

_MAX_REDIRECTS = 5

BANNED_USERNAMES: dict[str, str] = {  # normalised (lowercase) username: reason
    # Add entries here to block submissions from a Hugging Face account, e.g.:
    # "some-username": "Suspected of using multiple HF accounts",
}


def safeify_username(username: str) -> str:
    """Sanitise a Hugging Face username for use in repo paths.

    Organisation usernames use the form ``org/user``, which would create
    unintended path nesting. Lowercased so that casing variants — which all
    resolve to the same account — map to the same prefix; otherwise the
    submission cooldown could be bypassed by alternating case.

    Parameters
    ----------
    username : str
        The raw username as typed.

    Returns
    -------
    str
        Lowercased, with ``/`` and spaces replaced by underscores.

    """
    return str(username).strip().lower().replace("/", "_").replace(" ", "_")


def _is_safe_public_url(url: str) -> bool:
    """Reject URLs whose host resolves to a private/loopback/link-local address.

    Guards ``check_page_exists`` against SSRF: without this, a user-supplied URL
    (the "Method Report Link" field) could point the server at internal
    infrastructure and have it report reachability back.

    Parameters
    ----------
    url : str
        The URL to check.

    Returns
    -------
    bool
        True if every address the host resolves to is public.

    """
    hostname = urlparse(url).hostname
    if not hostname:
        return False
    try:
        infos = socket.getaddrinfo(hostname, None)
    except socket.gaierror:
        return False
    for info in infos:
        ip = ipaddress.ip_address(info[4][0])
        if (
            ip.is_private
            or ip.is_loopback
            or ip.is_link_local
            or ip.is_reserved
            or ip.is_multicast
            or ip.is_unspecified
        ):
            return False
    return True


def check_page_exists(
    url: str,
    delay: float = 0.2,
    max_retries: int = 3,
    current_retries: int = 0,
    restrict_to_public: bool = True,
) -> bool:
    """Check whether a page exists, retrying on rate limits.

    Redirects are followed manually rather than via ``requests``' built-in
    ``allow_redirects`` so each hop is checked against ``_is_safe_public_url``
    before it is requested, closing off SSRF via a redirect to an internal
    address.

    Parameters
    ----------
    url : str
        The URL to check.
    delay : float
        Seconds to sleep after every request.
    max_retries : int
        Maximum retries on HTTP 429.
    current_retries : int
        Internal retry counter.
    restrict_to_public : bool
        Reject hosts resolving to private addresses. Only meaningful when the
        host is user-controlled; disable for a hardcoded trusted domain, since
        some platforms resolve their own domain internally (split-horizon DNS)
        and this check would then reject it.

    Returns
    -------
    bool
        True when the URL returns HTTP 200.

    """
    safe_url = str(url).strip()
    if not safe_url.startswith(("http://", "https://")):
        safe_url = f"https://{safe_url}"

    try:
        response = None
        for _ in range(_MAX_REDIRECTS + 1):
            if restrict_to_public and not _is_safe_public_url(safe_url):
                logger.warning("Refusing to fetch non-public URL: {}", safe_url)
                return False
            response = requests.get(safe_url, timeout=5, allow_redirects=False)
            if (
                response.status_code in (301, 302, 303, 307, 308)
                and "Location" in response.headers
            ):
                safe_url = urljoin(safe_url, response.headers["Location"])
                continue
            break
        else:
            logger.warning("Too many redirects for {}", url)
            return False

        if response.status_code == 429:
            if current_retries < max_retries:
                wait = 5 * (2**current_retries)
                logger.warning(
                    "Rate limited on {} (attempt {}/{}), waiting {}s.",
                    safe_url,
                    current_retries + 1,
                    max_retries,
                    wait,
                )
                time.sleep(wait)
                return check_page_exists(
                    safe_url,
                    delay=delay,
                    max_retries=max_retries,
                    current_retries=current_retries + 1,
                    restrict_to_public=restrict_to_public,
                )
            logger.error("Max retries reached for rate limit on {}.", safe_url)
            return False

        return response.status_code == 200

    except requests.exceptions.RequestException as exc:
        logger.error("Error checking URL {}: {}", safe_url, exc)
        return False

    finally:
        time.sleep(delay)


def validate_hf_username(username: str) -> bool:
    """Confirm a Hugging Face account exists by fetching its profile page.

    This is a typo check, not an identity proof — nothing here verifies that the
    submitter owns the account.

    Parameters
    ----------
    username : str
        A username, or a full ``https://huggingface.co/<user>`` URL.

    Returns
    -------
    bool
        True when the profile page loads.

    """
    # restrict_to_public=False: the target is always the literal huggingface.co
    # domain, never an attacker-supplied host, and HF can resolve its own domain
    # to an internal address from inside its infrastructure.
    candidate = str(username).strip()
    if re.match(r"^https?://huggingface\.co/([^/]+)/?$", candidate):
        return check_page_exists(
            candidate, delay=1, max_retries=10, restrict_to_public=False
        )
    return check_page_exists(
        f"https://huggingface.co/{candidate}",
        delay=1,
        max_retries=10,
        restrict_to_public=False,
    )


def validate_model_details(tag: str | None) -> str:
    """Validate a method report link.

    Parameters
    ----------
    tag : str | None
        The URL as typed, or empty.

    Returns
    -------
    str
        The URL when it is a reachable ``https://`` page, ``"Not submitted"``
        when blank, or ``"Invalid link"`` otherwise.

    """
    if tag is None or str(tag).strip() == "":
        return "Not submitted"
    safe_tag = str(tag).strip()
    if not safe_tag.startswith("https://"):
        return "Invalid link"
    return safe_tag if check_page_exists(safe_tag, delay=2) else "Invalid link"


def make_user_clickable(name: str) -> str:
    """Link a leaderboard username to its Hugging Face profile.

    Parameters
    ----------
    name : str
        Username or alias as displayed.

    Returns
    -------
    str
        An HTML anchor.

    """
    link = f"https://huggingface.co/{name}" if not str(name).startswith("https://") else str(name)
    return (
        f'<a target="_blank" href="{link}" style="color: var(--link-text-color); '
        f'text-decoration: underline; text-decoration-style: dotted;">{name}</a>'
    )


def make_tag_clickable(tag: str) -> str:
    """Render a method report link as a leaderboard cell.

    Parameters
    ----------
    tag : str
        The stored link, possibly empty or a placeholder.

    Returns
    -------
    str
        An HTML anchor, or a plain placeholder string.

    """
    text = "" if tag is None else str(tag).strip()
    if text in ("", "nan", "Not submitted"):
        return "Not submitted"
    if not text.startswith(("http://", "https://")):
        return "Invalid link"
    return (
        f'<a target="_blank" href="{text}" style="color: var(--link-text-color); '
        f'text-decoration: underline; text-decoration-style: dotted;">link</a>'
    )