Skip to content

Commit 0c7fd06

Browse files
Wauplinclaudehanouticelina
authored
[HfApi] Support gated repos hiding requester username/email (#5047)
* [HfApi] Support gated repos hiding requester username/email Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * [HfApi] Split user/user_id validation into two explicit checks Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix access requests for repos hiding usernames --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]> Co-authored-by: Celina Hanouti <[email protected]>
1 parent c629fa3 commit 0c7fd06

2 files changed

Lines changed: 101 additions & 37 deletions

File tree

‎src/huggingface_hub/hf_api.py‎

Lines changed: 76 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -446,13 +446,17 @@ class AccessRequest:
446446
"""Data structure containing information about a user access request.
447447

448448
Attributes:
449-
username (`str`):
450-
Username of the user who requested access.
451-
fullname (`str`):
452-
Fullname of the user who requested access.
453-
email (`Optional[str]`):
454-
Email of the user who requested access.
455-
Can only be `None` in the /accepted list if the user was granted access manually.
449+
username (`str`, *optional*):
450+
Username of the user who requested access. `None` if the repo is configured to not share usernames of
451+
requesters. In that case, use `request_id` to accept, reject or cancel the request.
452+
request_id (`str`):
453+
Id of the access request. Always set, even if the username is not shared.
454+
fullname (`str`, *optional*):
455+
Fullname of the user who requested access. `None` if the repo is configured to not share usernames of
456+
requesters.
457+
email (`str`, *optional*):
458+
Email of the user who requested access. `None` if the user was granted access manually or if the repo is
459+
configured to not share emails of requesters.
456460
timestamp (`datetime`):
457461
Timestamp of the request.
458462
status (`Literal["pending", "accepted", "rejected"]`):
@@ -461,8 +465,9 @@ class AccessRequest:
461465
Additional fields filled by the user in the gate form.
462466
"""
463467

464-
username: str
465-
fullname: str
468+
username: str | None
469+
request_id: str
470+
fullname: str | None
466471
email: str | None
467472
timestamp: datetime
468473
status: Literal["pending", "accepted", "rejected"]
@@ -10623,9 +10628,9 @@ def list_pending_access_requests(
1062310628
To disable authentication, pass `False`.
1062410629

1062510630
Returns:
10626-
`Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
10627-
`status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
10628-
be populated with user's answers.
10631+
`Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each item contains a `username`,
10632+
`request_id`, `email`, `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields`
10633+
attribute will be populated with user's answers.
1062910634

1063010635
Raises:
1063110636
[`HfHubHTTPError`]:
@@ -10646,6 +10651,7 @@ def list_pending_access_requests(
1064610651
[
1064710652
AccessRequest(
1064810653
username='clem',
10654+
request_id='655f3a1c9e6b2d4f8a7c1e05',
1064910655
fullname='Clem 🤗',
1065010656
email='***',
1065110657
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
@@ -10689,9 +10695,9 @@ def list_accepted_access_requests(
1068910695
To disable authentication, pass `False`.
1069010696

1069110697
Returns:
10692-
`Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
10693-
`status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
10694-
be populated with user's answers.
10698+
`Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each item contains a `username`,
10699+
`request_id`, `email`, `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields`
10700+
attribute will be populated with user's answers.
1069510701

1069610702
Raises:
1069710703
[`HfHubHTTPError`]:
@@ -10711,6 +10717,7 @@ def list_accepted_access_requests(
1071110717
[
1071210718
AccessRequest(
1071310719
username='clem',
10720+
request_id='655f3a1c9e6b2d4f8a7c1e05',
1071410721
fullname='Clem 🤗',
1071510722
email='***',
1071610723
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
@@ -10751,9 +10758,9 @@ def list_rejected_access_requests(
1075110758
To disable authentication, pass `False`.
1075210759

1075310760
Returns:
10754-
`Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`,
10755-
`status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
10756-
be populated with user's answers.
10761+
`Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each item contains a `username`,
10762+
`request_id`, `email`, `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields`
10763+
attribute will be populated with user's answers.
1075710764

1075810765
Raises:
1075910766
[`HfHubHTTPError`]:
@@ -10773,6 +10780,7 @@ def list_rejected_access_requests(
1077310780
[
1077410781
AccessRequest(
1077510782
username='clem',
10783+
request_id='655f3a1c9e6b2d4f8a7c1e05',
1077610784
fullname='Clem 🤗',
1077710785
email='***',
1077810786
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
@@ -10802,18 +10810,26 @@ def _list_access_requests(
1080210810
params={},
1080310811
headers=self._build_hf_headers(token=token),
1080410812
):
10813+
user = request.get("user", {}) # not shared if repo is configured to hide usernames
1080510814
yield AccessRequest(
10806-
username=request["user"]["user"],
10807-
fullname=request["user"]["fullname"],
10808-
email=request["user"].get("email"),
10815+
username=user.get("user"),
10816+
request_id=request["requestId"],
10817+
fullname=user.get("fullname"),
10818+
email=user.get("email"),
1080910819
status=request["status"],
1081010820
timestamp=parse_datetime(request["timestamp"]),
1081110821
fields=request.get("fields"), # only if custom fields in form
1081210822
)
1081310823

1081410824
@validate_hf_hub_args
1081510825
def cancel_access_request(
10816-
self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None
10826+
self,
10827+
repo_id: str,
10828+
user: str | None = None,
10829+
*,
10830+
request_id: str | None = None,
10831+
repo_type: str | None = None,
10832+
token: bool | str | None = None,
1081710833
) -> None:
1081810834
"""
1081910835
Cancel an access request from a user for a given gated repo.
@@ -10825,8 +10841,12 @@ def cancel_access_request(
1082510841
Args:
1082610842
repo_id (`str`):
1082710843
The id of the repo to cancel access request for.
10828-
user (`str`):
10829-
The username of the user which access request should be cancelled.
10844+
user (`str`, *optional*):
10845+
The username of the user which access request should be cancelled. Exactly one of `user` or
10846+
`request_id` must be provided.
10847+
request_id (`str`, *optional*):
10848+
The id of the access request to cancel (see [`AccessRequest`]). Required when the repo is configured
10849+
to not share usernames of requesters. Exactly one of `user` or `request_id` must be provided.
1083010850
repo_type (`str`, *optional*):
1083110851
The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`.
1083210852
Defaults to `model`.
@@ -10849,11 +10869,17 @@ def cancel_access_request(
1084910869
[`HfHubHTTPError`]:
1085010870
HTTP 404 if the user access request is already in the pending list.
1085110871
"""
10852-
self._handle_access_request(repo_id, user, "pending", repo_type=repo_type, token=token)
10872+
self._handle_access_request(repo_id, user, request_id, "pending", repo_type=repo_type, token=token)
1085310873

1085410874
@validate_hf_hub_args
1085510875
def accept_access_request(
10856-
self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None
10876+
self,
10877+
repo_id: str,
10878+
user: str | None = None,
10879+
*,
10880+
request_id: str | None = None,
10881+
repo_type: str | None = None,
10882+
token: bool | str | None = None,
1085710883
) -> None:
1085810884
"""
1085910885
Accept an access request from a user for a given gated repo.
@@ -10867,8 +10893,12 @@ def accept_access_request(
1086710893
Args:
1086810894
repo_id (`str`):
1086910895
The id of the repo to accept access request for.
10870-
user (`str`):
10871-
The username of the user which access request should be accepted.
10896+
user (`str`, *optional*):
10897+
The username of the user which access request should be accepted. Exactly one of `user` or
10898+
`request_id` must be provided.
10899+
request_id (`str`, *optional*):
10900+
The id of the access request to accept (see [`AccessRequest`]). Required when the repo is configured
10901+
to not share usernames of requesters. Exactly one of `user` or `request_id` must be provided.
1087210902
repo_type (`str`, *optional*):
1087310903
The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`.
1087410904
Defaults to `model`.
@@ -10891,14 +10921,15 @@ def accept_access_request(
1089110921
[`HfHubHTTPError`]:
1089210922
HTTP 404 if the user access request is already in the accepted list.
1089310923
"""
10894-
self._handle_access_request(repo_id, user, "accepted", repo_type=repo_type, token=token)
10924+
self._handle_access_request(repo_id, user, request_id, "accepted", repo_type=repo_type, token=token)
1089510925

1089610926
@validate_hf_hub_args
1089710927
def reject_access_request(
1089810928
self,
1089910929
repo_id: str,
10900-
user: str,
10930+
user: str | None = None,
1090110931
*,
10932+
request_id: str | None = None,
1090210933
repo_type: str | None = None,
1090310934
rejection_reason: str | None,
1090410935
token: bool | str | None = None,
@@ -10915,8 +10946,12 @@ def reject_access_request(
1091510946
Args:
1091610947
repo_id (`str`):
1091710948
The id of the repo to reject access request for.
10918-
user (`str`):
10919-
The username of the user which access request should be rejected.
10949+
user (`str`, *optional*):
10950+
The username of the user which access request should be rejected. Exactly one of `user` or
10951+
`request_id` must be provided.
10952+
request_id (`str`, *optional*):
10953+
The id of the access request to reject (see [`AccessRequest`]). Required when the repo is configured
10954+
to not share usernames of requesters. Exactly one of `user` or `request_id` must be provided.
1092010955
repo_type (`str`, *optional*):
1092110956
The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`.
1092210957
Defaults to `model`.
@@ -10942,14 +10977,15 @@ def reject_access_request(
1094210977
HTTP 404 if the user access request is already in the rejected list.
1094310978
"""
1094410979
self._handle_access_request(
10945-
repo_id, user, "rejected", repo_type=repo_type, rejection_reason=rejection_reason, token=token
10980+
repo_id, user, request_id, "rejected", repo_type=repo_type, rejection_reason=rejection_reason, token=token
1094610981
)
1094710982

1094810983
@validate_hf_hub_args
1094910984
def _handle_access_request(
1095010985
self,
1095110986
repo_id: str,
10952-
user: str,
10987+
user: str | None,
10988+
request_id: str | None,
1095310989
status: Literal["accepted", "rejected", "pending"],
1095410990
repo_type: str | None = None,
1095510991
rejection_reason: str | None = None,
@@ -10960,7 +10996,12 @@ def _handle_access_request(
1096010996
if repo_type is None:
1096110997
repo_type = constants.REPO_TYPE_MODEL
1096210998

10963-
payload = {"user": user, "status": status}
10999+
if user is None and request_id is None:
11000+
raise ValueError("One of `user` or `request_id` must be provided.")
11001+
if user is not None and request_id is not None:
11002+
raise ValueError("Cannot provide both `user` and `request_id`.")
11003+
payload: dict[str, str | None] = {"user": user} if user is not None else {"requestId": request_id}
11004+
payload["status"] = status
1096411005

1096511006
if rejection_reason is not None:
1096611007
if status != "rejected":

‎tests/test_hf_api.py‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4071,6 +4071,7 @@ def test_access_requests_normal_usage(self, api: HfApi) -> None:
40714071
request = requests[0]
40724072
assert isinstance(request, AccessRequest)
40734073
assert request.username == OTHER_USER
4074+
assert isinstance(request.request_id, str)
40744075
assert request.email is None # email not shared when granted access manually
40754076
assert request.status == "accepted"
40764077
assert isinstance(request.timestamp, datetime.datetime)
@@ -4093,8 +4094,8 @@ def test_access_requests_normal_usage(self, api: HfApi) -> None:
40934094
assert len(requests) == 1
40944095
assert requests[0].username == OTHER_USER
40954096

4096-
# Accept again
4097-
api.accept_access_request(self.repo_id, OTHER_USER)
4097+
# Accept again (using request id instead of username)
4098+
api.accept_access_request(self.repo_id, request_id=requests[0].request_id)
40984099
time.sleep(1) # hub-ci: give the server time to propagate the write before reading it back
40994100
requests = list(api.list_accepted_access_requests(self.repo_id))
41004101
assert len(requests) == 1
@@ -4123,6 +4124,28 @@ def test_access_request_error(self, api: HfApi):
41234124
api.cancel_access_request(self.repo_id, OTHER_USER)
41244125

41254126

4127+
class TestAccessRequestHiddenPII:
4128+
def test_list_access_requests_without_username_and_email(self):
4129+
# Repos can be configured to not share username/email of requesters
4130+
request = {
4131+
"requestId": "655f3a1c9e6b2d4f8a7c1e05",
4132+
"status": "pending",
4133+
"timestamp": "2023-11-23T18:04:53.828Z",
4134+
}
4135+
with patch("huggingface_hub.hf_api.paginate", return_value=[request]):
4136+
requests = list(HfApi().list_pending_access_requests("user/repo"))
4137+
assert requests[0].username is None
4138+
assert requests[0].fullname is None
4139+
assert requests[0].email is None
4140+
assert requests[0].request_id == "655f3a1c9e6b2d4f8a7c1e05"
4141+
4142+
def test_handle_access_request_requires_exactly_one_of_user_or_request_id(self):
4143+
with pytest.raises(ValueError, match="One of `user` or `request_id` must be provided"):
4144+
HfApi().accept_access_request("user/repo")
4145+
with pytest.raises(ValueError, match="Cannot provide both `user` and `request_id`"):
4146+
HfApi().accept_access_request("user/repo", "clem", request_id="655f3a1c9e6b2d4f8a7c1e05")
4147+
4148+
41264149
@pytest.mark.production
41274150
class TestUserApi:
41284151
@pytest.fixture(autouse=True)

0 commit comments

Comments
 (0)