Skip to content

PyJWKSet exposes an iterator but you cannot iterate it. #1024

Open
@Kyle-sandeman-mrdfood

Description

@Kyle-sandeman-mrdfood

Hi, in #724 __getitem__ was introduced which allows jwkset['my key id'] which is great!
However one cannot do e.g. keys_using_hmac = [k for k in jwkset if ...] or any other form of iteration.
I believe __iter__ needs to be implemented as python will treat any class with __getitem__ as iterable.

Expected Result

Example use-case: this should print all the kids

for key in jwkset:
  print(key.key_id)

Actual Result

KeyError: keyset has no key for kid: 0

Reproduction Steps

  1. create a PyJWKSet instance
  2. try iterate the instance

System Information

Can provide if required, I don't think anything more than pyjwt 2.10.0 is relevant as the code in the aforementioned issue is agnostic to the rest.

Proposed resolution

I'm no python expert, but from the docs and the below example, I believe implementing __iter__ is all that is required.

>>> class Test:
...   def __getitem__(self, k):
...     print(type(k), k)
...     raise KeyError('not implemented')
... 
>>> t = Test()
>>> for item in t:
...   print('got an item:', item)
... 
<class 'int'> 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __getitem__
KeyError: 'not implemented'

I have confirmed this code resolves the error

def __getitem__(...
   # original PyJWKSet impl.

def __iter__(self):
  return iter(self.keys)

I could make a PR later today but I am sure an existing collaborator would be able to get it into a release sooner.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions