Skip to content

[bug]: generate_secured_api_key fails on Python versions > 3.12, dict and None objects do not have the encode method #576

@bsmith8457

Description

@bsmith8457

Description

This code:

apiKey = str(current_app.config['ALGOLIA_API_KEY'])
restrictions = dict({
    'userToken': str(userId)
})
key = SearchClientSync.generate_secured_api_key(apiKey,restrictions)

Fails with the error Error Message: 'dict' object has no attribute 'encode'

Which, when looking in your code I notice:

secured_key = hmac.new(
    parent_api_key.encode(encoding="utf-8"),
    query_parameters.encode(encoding="utf-8"),
    hashlib.sha256,
).hexdigest()

Where it's expecting a dict object to have the encode method, which it does not.

This is your API documentation:

public_key = SearchClient.generate_secured_api_key(
    'YourSearchOnlyApiKey',
    {'userToken': 'user_42'}
)

Note that when I switch this argument to a string, it works, supposedly:

apiKey = str(current_app.config['ALGOLIA_API_KEY'])
restrictions = str({
    'userToken': str(userId)
})
key = SearchClientSync.generate_secured_api_key(apiKey,restrictions)

The documentation is pretty misleading or out of date.

Client

Search

Version

4.11.2

Relevant log output

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions