Skip to content

Adding OAuth revoke and introspect endpoints #261

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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"),
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"),
)
36 changes: 31 additions & 5 deletions notion_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,23 @@
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
Expand All @@ -32,7 +36,7 @@ class ClientOptions:
"""Options to configure the client.

Attributes:
auth: Bearer token for authentication. If left undefined, the `auth` parameter
auth: Bearer token for authentication, or Base 64 encoded client ID and secret. If left undefined, the `auth` parameter
should be set on each request.
timeout_ms: Number of milliseconds to wait before emitting a
`RequestTimeoutError`.
Expand All @@ -44,7 +48,7 @@ class ClientOptions:
notion_version: Notion version to use.
"""

auth: Optional[str] = None
auth: Optional[Union[str, tuple[str, str]]] = None
timeout_ms: int = 60_000
base_url: str = "https://api.notion.com"
log_level: int = logging.WARNING
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 @@ -93,7 +98,15 @@ def client(self, client: Union[httpx.Client, httpx.AsyncClient]) -> None:
}
)
if self.options.auth:
client.headers["Authorization"] = f"Bearer {self.options.auth}"
if isinstance(self.options.auth, tuple):
client_id = self.options.auth[0]
client_secret = self.options.auth[1]
auth_header = base64.b64encode(
f"{client_id}:{client_secret}".encode()
).decode("utf-8")
client.headers["Authorization"] = f'Basic "{auth_header}"'
else:
client.headers["Authorization"] = f"Bearer {self.options.auth}"
self._clients.append(client)

def _build_request(
Expand All @@ -102,11 +115,19 @@ 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, tuple[str, str]]] = None,
) -> Request:
headers = httpx.Headers()
if auth:
headers["Authorization"] = f"Bearer {auth}"
if isinstance(auth, tuple):
client_id = auth[0]
client_secret = auth[1]
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 +141,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
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
57 changes: 55 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re
from datetime import datetime
from typing import Optional
import json

import pytest

Expand All @@ -14,13 +15,45 @@ 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

return {
"filter_headers": [
("authorization", "ntn_..."),
("authorization", "ntn_... OR base64_encoded(client_id:client_secret)"),
("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 +73,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