Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions notion_client/api_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,3 +325,41 @@ def list(self, **kwargs: Any) -> SyncAsync[Any]:
query=pick(kwargs, "block_id", "start_cursor", "page_size"),
auth=kwargs.get("auth"),
)


class OAuthEndpoint(Endpoint):
def token(self, **kwargs: Any) -> SyncAsync[Any]:
"""Creates an access token that a third-party service can use to authenticate with Notion.

*[🔗 Endpoint documentation](https://developers.notion.com/reference/create-a-token)*
""" # noqa: E501
return self.parent.request(
path="oauth/token",
method="POST",
body=pick(kwargs, "grant_type", "code", "redirect_uri"),
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR 595 on notion-sdk-js added more to it: makenotion/notion-sdk-js#595

auth=kwargs.get("auth"),
)

def introspect(self, **kwargs: Any) -> SyncAsync[Any]:
"""Get a token's active status, scope, and issued time.

*[🔗 Endpoint documentation](https://developers.notion.com/reference/introspect-token)*
""" # noqa: E501
return self.parent.request(
path="oauth/introspect",
method="POST",
body=pick(kwargs, "token"),
auth=kwargs.get("auth"),
)

def revoke(self, **kwargs: Any) -> SyncAsync[Any]:
"""Revoke an access token.

*[🔗 Endpoint documentation](https://developers.notion.com/reference/revoke-token)*
""" # noqa: E501
return self.parent.request(
path="oauth/revoke",
method="POST",
body=pick(kwargs, "token"),
auth=kwargs.get("auth"),
)
25 changes: 22 additions & 3 deletions notion_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,26 @@
import httpx
from httpx import Request, Response

import base64

from notion_client.api_endpoints import (
BlocksEndpoint,
CommentsEndpoint,
DatabasesEndpoint,
PagesEndpoint,
SearchEndpoint,
UsersEndpoint,
OAuthEndpoint,
)
from notion_client.errors import (
APIResponseError,
HTTPResponseError,
RequestTimeoutError,
is_api_error_code,
APIErrorCode,
)
from notion_client.logging import make_console_logger
from notion_client.typing import SyncAsync
from notion_client.typing import SyncAsync, OAuthHeader


@dataclass
Expand Down Expand Up @@ -77,6 +81,7 @@ def __init__(
self.pages = PagesEndpoint(self)
self.search = SearchEndpoint(self)
self.comments = CommentsEndpoint(self)
self.oauth = OAuthEndpoint(self)

@property
def client(self) -> Union[httpx.Client, httpx.AsyncClient]:
Expand All @@ -102,11 +107,20 @@ def _build_request(
path: str,
query: Optional[Dict[Any, Any]] = None,
body: Optional[Dict[Any, Any]] = None,
auth: Optional[str] = None,
auth: Optional[Union[str, OAuthHeader]] = None,
) -> Request:
headers = httpx.Headers()
if auth:
headers["Authorization"] = f"Bearer {auth}"
# At runtime the TypedDict is the same type as a regular Dict
if isinstance(auth, Dict):
client_id = auth["client_id"]
client_secret = auth["client_secret"]
auth_header = base64.b64encode(
f"{client_id}:{client_secret}".encode()
).decode("utf-8")
headers["Authorization"] = f'Basic "{auth_header}"'
else:
headers["Authorization"] = f"Bearer {auth}"
self.logger.info(f"{method} {self.client.base_url}{path}")
self.logger.debug(f"=> {query} -- {body}")
return self.client.build_request(
Expand All @@ -120,6 +134,11 @@ def _parse_response(self, response: Response) -> Any:
try:
body = error.response.json()
code = body.get("code")
# Any oauth errors throw this exact error syntax, so handle them as so
if "code" not in body and body.get("error") == "invalid_client":
raise APIResponseError(
response, body["error"], APIErrorCode("unauthorized")
)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is weird, how does the JS SDK handle this?

except json.JSONDecodeError:
code = None
if code and is_api_error_code(code):
Expand Down
7 changes: 6 additions & 1 deletion notion_client/typing.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
"""Custom type definitions for notion-sdk-py."""
from typing import Awaitable, TypeVar, Union
from typing import Awaitable, TypeVar, Union, TypedDict

T = TypeVar("T")
SyncAsync = Union[T, Awaitable[T]]


class OAuthHeader(TypedDict):
client_id: str
client_secret: str
77 changes: 77 additions & 0 deletions tests/cassettes/test_client_request_oauth.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
interactions:
- request:
body: ''
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- ntn_... OR base64_encoded(client_id:client_secret)
connection:
- keep-alive
content-length:
- '0'
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/introspect
response:
content: '{"error":"invalid_client","request_id":"055b49b7-5a59-4a50-a7aa-f7190a726275"}'
headers: {}
http_version: HTTP/1.1
status_code: 401
- request:
body: ''
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- ntn_... OR base64_encoded(client_id:client_secret)
connection:
- keep-alive
content-length:
- '0'
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/introspect
response:
content: '{"error":"invalid_client","request_id":"4da9d985-7a35-4b31-94a1-4539f9beb711"}'
headers: {}
http_version: HTTP/1.1
status_code: 401
- request:
body: '{"token": "ntn_..."}'
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- ntn_... OR base64_encoded(client_id:client_secret)
connection:
- keep-alive
content-length:
- '63'
content-type:
- application/json
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/introspect
response:
content: '{"active":true,"scope":"read_content insert_content update_content read_user_with_email
read_user_without_email","iat":1742248683519,"request_id":"b5a7fea8-1b92-44ad-ad99-243df7723d75"}'
headers: {}
http_version: HTTP/1.1
status_code: 200
version: 1
29 changes: 29 additions & 0 deletions tests/cassettes/test_introspect_token.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
interactions:
- request:
body: '{"token": "ntn_..."}'
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- ntn_... OR base64_encoded(client_id:client_secret)
connection:
- keep-alive
content-length:
- '63'
content-type:
- application/json
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/introspect
response:
content: '{"active":true,"scope":"read_content insert_content update_content read_user_with_email
read_user_without_email","iat":1742248683519,"request_id":"ddd8cc28-162c-46cb-9268-fb890d4bb044"}'
headers: {}
http_version: HTTP/1.1
status_code: 200
version: 1
28 changes: 28 additions & 0 deletions tests/cassettes/test_revoke_token.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
interactions:
- request:
body: '{"token": "ntn_..."}'
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- ntn_... OR base64_encoded(client_id:client_secret)
connection:
- keep-alive
content-length:
- '63'
content-type:
- application/json
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/revoke
response:
content: '{"request_id":"a1bffba5-3255-4cc7-9495-5676c9464105"}'
headers: {}
http_version: HTTP/1.1
status_code: 200
version: 1
28 changes: 28 additions & 0 deletions tests/cassettes/test_token.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
interactions:
- request:
body: '{"grant_type": "authorization_code", "code": "...", "redirect_uri": "http://..."}'
headers:
accept:
- '*/*'
accept-encoding:
- gzip, deflate
authorization:
- ntn_... OR base64_encoded(client_id:client_secret)
connection:
- keep-alive
content-length:
- '134'
content-type:
- application/json
host:
- api.notion.com
notion-version:
- '2022-06-28'
method: POST
uri: https://api.notion.com/v1/oauth/token
response:
content: '{"access_token":"...","token_type":"...","bot_id":"...","workspace_name":"...","workspace_icon":"...","workspace_id":"...","owner":"...","duplicated_template_id":"...","request_id":"..."}'
headers: {}
http_version: HTTP/1.1
status_code: 200
version: 1
67 changes: 65 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
import re
from datetime import datetime
from typing import Optional
import json

import pytest
from vcr.request import Request

from notion_client import AsyncClient, Client

Expand All @@ -14,13 +16,54 @@ def remove_headers(response: dict):
response["headers"] = {}
return response

def scrub_requests(request: dict):
if request.body:
try:
body_str = request.body.decode("utf-8")
body_json = json.loads(body_str)
if "token" in body_json:
body_json["token"] = "ntn_..."
if "code" in body_json:
body_json["code"] = "..."
if "redirect_uri" in body_json:
body_json["redirect_uri"] = "http://..."
request.body = json.dumps(body_json).encode("utf-8")

except (json.JSONDecodeError, AttributeError):
pass
return request

def scrub_response(response: dict):
if "content" in response:
try:
content_json = json.loads(response["content"])
if "access_token" in content_json:
response["content"] = json.dumps(
{key: "..." for key in content_json}, separators=(",", ":")
)

except json.JSONDecodeError:
pass

return response

# The VCR config requires the passing of the request parameter, despite the face that it is not used
# (https://vcrpy.readthedocs.io/en/latest/advanced.html#advanced-use-of-filter-headers-filter-query-parameters-and-filter-post-data-parameters)
def scrub_auth_header(key: str, value: str, request: Optional[Request]):
if key == "authorization":
if value.startswith("Bearer "):
return "ntn_..."
elif value.startswith("Basic "):
return "Basic Base64Encoded($client_id:$client_secret)"

return {
"filter_headers": [
("authorization", "ntn_..."),
("authorization", scrub_auth_header),
("user-agent", None),
("cookie", None),
],
"before_record_response": remove_headers,
"before_record_request": scrub_requests,
"before_record_response": (remove_headers, scrub_response),
"match_on": ["method", "remove_page_id_for_matches"],
}

Expand All @@ -40,6 +83,26 @@ def token() -> str:
return os.environ.get("NOTION_TOKEN")


@pytest.fixture(scope="session")
def code() -> str:
return os.environ.get("NOTION_CODE")


@pytest.fixture(scope="session")
def redirect_uri() -> str:
return os.environ.get("NOTION_REDIRECT_URI")


@pytest.fixture(scope="session")
def client_id() -> str:
return os.environ.get("NOTION_CLIENT_ID")


@pytest.fixture(scope="session")
def client_secret() -> str:
return os.environ.get("NOTION_CLIENT_SECRET")


@pytest.fixture(scope="module", autouse=True)
def parent_page_id(vcr) -> str:
"""this is the ID of the Notion page where the tests will be executed
Expand Down
Loading
Loading