From c161c5210d1165998687b73935f9432da681ee21 Mon Sep 17 00:00:00 2001 From: box-sdk-build Date: Mon, 16 Nov 2026 09:43:51 -0800 Subject: [PATCH 1/2] fix(SDK-6627): Avoid duplicate `jti` errors by signing a new JWT assertion on token request retries (box/box-codegen#1001) --- .codegen.json | 2 +- box_sdk_gen/box/jwt_auth.py | 113 +++++++--- box_sdk_gen/networking/box_network_client.py | 15 ++ box_sdk_gen/networking/fetch_options.py | 18 ++ docs/box_sdk_gen/client.md | 2 + test/box_sdk_gen/test/box_network_client.py | 214 +++++++++++++++++++ 6 files changed, 334 insertions(+), 30 deletions(-) diff --git a/.codegen.json b/.codegen.json index 0b4a46f55..9239eade7 100644 --- a/.codegen.json +++ b/.codegen.json @@ -1 +1 @@ -{ "engineHash": "0eab570", "specHash": "7f8494a", "version": "4.20.0" } +{ "engineHash": "6772894", "specHash": "7f8494a", "version": "4.20.0" } diff --git a/box_sdk_gen/box/jwt_auth.py b/box_sdk_gen/box/jwt_auth.py index 7f268b282..9c385a57b 100644 --- a/box_sdk_gen/box/jwt_auth.py +++ b/box_sdk_gen/box/jwt_auth.py @@ -6,6 +6,8 @@ from box_sdk_gen.serialization.json import deserialize +from box_sdk_gen.serialization.json import serialize + from typing import List from box_sdk_gen.schemas.post_o_auth_2_token import PostOAuth2TokenGrantTypeField @@ -30,6 +32,14 @@ from box_sdk_gen.serialization.json import SerializedData +from box_sdk_gen.networking.fetch_options import FetchOptions + +from box_sdk_gen.networking.fetch_options import RequestDataFactory + +from box_sdk_gen.networking.fetch_options import ResponseFormat + +from box_sdk_gen.networking.fetch_response import FetchResponse + from box_sdk_gen.internal.utils import get_uuid from box_sdk_gen.internal.utils import read_text_from_file @@ -269,36 +279,32 @@ def from_config_file( ) -class BoxJWTAuth(Authentication): - def __init__(self, config: JWTConfig, **kwargs): +class JwtAccessTokenDataFactory(RequestDataFactory): + def __init__( + self, + config: JWTConfig, + *, + subject_id: Optional[str] = None, + subject_type: Optional[str] = None, + **kwargs + ): """ - :param config: An object containing all JWT configuration to use for authentication + :param config: JWT configuration used to sign the assertion :type config: JWTConfig + :param subject_id: The ID of the user or enterprise to authenticate as, defaults to None + :type subject_id: Optional[str], optional + :param subject_type: The type of the subject ID, either 'user' or 'enterprise', defaults to None + :type subject_type: Optional[str], optional """ super().__init__(**kwargs) self.config = config - self.token_storage = self.config.token_storage - self.subject_id = ( - self.config.enterprise_id - if not self.config.enterprise_id == None - else self.config.user_id - ) - self.subject_type = ( - 'enterprise' if not self.config.enterprise_id == None else 'user' - ) + self.subject_id = subject_id + self.subject_type = subject_type - def refresh_token( - self, *, network_session: Optional[NetworkSession] = None - ) -> AccessToken: + def create(self) -> SerializedData: """ - Get new access token using JWT auth. - :param network_session: An object to keep network session state, defaults to None - :type network_session: Optional[NetworkSession], optional + Creates the access token request body with a newly signed JWT assertion. """ - if is_browser(): - raise BoxSDKError( - message='JWT auth is not supported in browser environment.' - ) alg: JwtAlgorithm = ( self.config.algorithm if not self.config.algorithm == None @@ -321,17 +327,66 @@ def refresh_token( key=self.config.private_key, passphrase=self.config.private_key_passphrase ) assertion: str = create_jwt_assertion(claims, jwt_key, jwt_options) - auth_manager: AuthorizationManager = AuthorizationManager( - network_session=( - network_session if not network_session == None else NetworkSession() - ) - ) - token: AccessToken = auth_manager.request_access_token( - PostOAuth2TokenGrantTypeField.URN_IETF_PARAMS_OAUTH_GRANT_TYPE_JWT_BEARER, + request_body: PostOAuth2Token = PostOAuth2Token( + grant_type=PostOAuth2TokenGrantTypeField.URN_IETF_PARAMS_OAUTH_GRANT_TYPE_JWT_BEARER, assertion=assertion, client_id=self.config.client_id, client_secret=self.config.client_secret, ) + return serialize(request_body) + + +class BoxJWTAuth(Authentication): + def __init__(self, config: JWTConfig, **kwargs): + """ + :param config: An object containing all JWT configuration to use for authentication + :type config: JWTConfig + """ + super().__init__(**kwargs) + self.config = config + self.token_storage = self.config.token_storage + self.subject_id = ( + self.config.enterprise_id + if not self.config.enterprise_id == None + else self.config.user_id + ) + self.subject_type = ( + 'enterprise' if not self.config.enterprise_id == None else 'user' + ) + + def refresh_token( + self, *, network_session: Optional[NetworkSession] = None + ) -> AccessToken: + """ + Get new access token using JWT auth. + :param network_session: An object to keep network session state, defaults to None + :type network_session: Optional[NetworkSession], optional + """ + if is_browser(): + raise BoxSDKError( + message='JWT auth is not supported in browser environment.' + ) + network_session_to_use: NetworkSession = ( + network_session if not network_session == None else NetworkSession() + ) + data_factory: JwtAccessTokenDataFactory = JwtAccessTokenDataFactory( + config=self.config, + subject_id=self.subject_id, + subject_type=self.subject_type, + ) + response: FetchResponse = network_session_to_use.network_client.fetch( + FetchOptions( + url=''.join( + [network_session_to_use.base_urls.base_url, '/oauth2/token'] + ), + method='POST', + data_factory=data_factory, + content_type='application/x-www-form-urlencoded', + response_format=ResponseFormat.JSON, + network_session=network_session_to_use, + ) + ) + token: AccessToken = deserialize(response.data, AccessToken) self.token_storage.store(token) return token diff --git a/box_sdk_gen/networking/box_network_client.py b/box_sdk_gen/networking/box_network_client.py index 417d7a18f..c025341ea 100644 --- a/box_sdk_gen/networking/box_network_client.py +++ b/box_sdk_gen/networking/box_network_client.py @@ -1,3 +1,4 @@ +import copy import io import time @@ -89,6 +90,7 @@ def fetch(self, options: 'FetchOptions') -> FetchResponse: multipart_streams_positions = self._get_multipart_stream_positions(options) while True: + options = self._prepare_options_for_attempt(options, attempt_nr) request: APIRequest = self._prepare_request( options=options, reauthenticate=response.reauthentication_needed ) @@ -150,6 +152,19 @@ def fetch(self, options: 'FetchOptions') -> FetchResponse: request=request, response=response, data_sanitizer=data_sanitizer ) + @staticmethod + def _prepare_options_for_attempt( + options: 'FetchOptions', attempt_number: int + ) -> 'FetchOptions': + if options.data_factory is None or ( + attempt_number == 1 and options.data is not None + ): + return options + + retry_options = copy.copy(options) + retry_options.data = options.data_factory.create() + return retry_options + def _prepare_request( self, options: 'FetchOptions', reauthenticate: bool = False ) -> APIRequest: diff --git a/box_sdk_gen/networking/fetch_options.py b/box_sdk_gen/networking/fetch_options.py index 84d85f215..32c8bb7ba 100644 --- a/box_sdk_gen/networking/fetch_options.py +++ b/box_sdk_gen/networking/fetch_options.py @@ -6,6 +6,8 @@ from typing import Optional +from abc import abstractmethod + from typing import Dict from typing import List @@ -56,6 +58,18 @@ def __init__( self.content_type = content_type +class RequestDataFactory: + def __init__(self): + pass + + @abstractmethod + def create(self) -> SerializedData: + """ + Creates a new request body + """ + pass + + class FetchOptions: def __init__( self, @@ -65,6 +79,7 @@ def __init__( params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, data: Optional[SerializedData] = None, + data_factory: Optional[RequestDataFactory] = None, file_stream: Optional[ByteStream] = None, multipart_data: Optional[List[MultipartItem]] = None, content_type: str = 'application/json', @@ -84,6 +99,8 @@ def __init__( :type headers: Optional[Dict[str, str]], optional :param data: Request body of the request, defaults to None :type data: Optional[SerializedData], optional + :param data_factory: Factory that builds a request body when `data` is not provided and rebuilds it for each retry., defaults to None + :type data_factory: Optional[RequestDataFactory], optional :param file_stream: Stream data of the request, defaults to None :type file_stream: Optional[ByteStream], optional :param multipart_data: Multipart data of the request, defaults to None @@ -104,6 +121,7 @@ def __init__( self.params = params self.headers = headers self.data = data + self.data_factory = data_factory self.file_stream = file_stream self.multipart_data = multipart_data self.content_type = content_type diff --git a/docs/box_sdk_gen/client.md b/docs/box_sdk_gen/client.md index 052d17e3c..a91d1fb76 100644 --- a/docs/box_sdk_gen/client.md +++ b/docs/box_sdk_gen/client.md @@ -27,6 +27,8 @@ This method allows you to make any HTTP request to the Box API. It will automati network configuration settings from the client. The method accepts a `FetchOptions` object as an argument and returns a `FetchResponse` object. +For request bodies that cannot be safely replayed, such as a JWT assertion with a one-time `jti`, `FetchOptions` also accepts `data_factory`. `data_factory.create()` is called on the first attempt when `data` is not set and on each retry so each retry can send a fresh body. + ## JSON request The following example demonstrates how to make a custom POST request to create a new folder in the root folder. diff --git a/test/box_sdk_gen/test/box_network_client.py b/test/box_sdk_gen/test/box_network_client.py index 21abdd5b6..82f7da5fa 100644 --- a/test/box_sdk_gen/test/box_network_client.py +++ b/test/box_sdk_gen/test/box_network_client.py @@ -1,4 +1,5 @@ import pytest +import base64 import json import threading from http.server import BaseHTTPRequestHandler, HTTPServer @@ -6,7 +7,10 @@ from unittest import mock from unittest.mock import Mock, patch from requests import Session, Response, RequestException +from urllib.parse import parse_qs from urllib3.filepost import encode_multipart_formdata +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa from box_sdk_gen import ( NetworkSession, @@ -17,6 +21,8 @@ ResponseFormat, DataSanitizer, ) +from box_sdk_gen.box.jwt_auth import BoxJWTAuth, JWTConfig +from box_sdk_gen.networking.base_urls import BaseUrls from box_sdk_gen.networking.box_network_client import ( BoxNetworkClient, USER_AGENT_HEADER, @@ -488,6 +494,37 @@ def test_fetch_successfully_retry_network_exception( assert response.status == 200 +def test_retry_network_exception_regenerates_request_data( + network_client, mock_requests_session, network_session_mock, response_200 +): + bodies = [] + data_factory = Mock() + data_factory.create.return_value = {"attempt": "D2"} + + def request_side_effect(**kwargs): + bodies.append(kwargs["data"]) + if len(bodies) == 1: + raise RequestException("Connection cancelled") + return response_200 + + mock_requests_session.request.side_effect = request_side_effect + + with patch("time.sleep"): + network_client.fetch( + FetchOptions( + method="POST", + url="https://example.com", + content_type="application/x-www-form-urlencoded", + data={"attempt": "D1"}, + data_factory=data_factory, + network_session=network_session_mock, + ) + ) + + assert bodies == ["attempt=D1", "attempt=D2"] + data_factory.create.assert_called_once_with() + + def test_fetch_retries_network_exception_max_attempts( network_client, mock_requests_session, network_session_mock ): @@ -613,6 +650,183 @@ def test_retryable_status_codes_with_invalid__response_body( assert mock_requests_session.request.call_count == 3 +def test_retry_500_regenerates_request_data( + network_client, + mock_requests_session, + network_session_mock, + response_500, + response_200, +): + data_factory = Mock() + data_factory.create.return_value = {"attempt": "D2"} + mock_requests_session.request.side_effect = [response_500, response_200] + + with patch("time.sleep"): + network_client.fetch( + FetchOptions( + method="POST", + url="https://example.com", + content_type="application/x-www-form-urlencoded", + data={"attempt": "D1"}, + data_factory=data_factory, + network_session=network_session_mock, + ) + ) + + bodies = [ + call.kwargs["data"] for call in mock_requests_session.request.call_args_list + ] + assert bodies == ["attempt=D1", "attempt=D2"] + data_factory.create.assert_called_once_with() + + +def test_retry_strategy_receives_regenerated_request_data( + network_client, mock_requests_session, response_500, response_200 +): + class RetryStrategySpy: + def __init__(self): + self.data = [] + + def should_retry(self, fetch_options, fetch_response, attempt_number): + self.data.append(fetch_options.data) + return fetch_response.status == 500 + + def retry_after(self, fetch_options, fetch_response, attempt_number): + return 0 + + retry_strategy = RetryStrategySpy() + data_factory = Mock() + data_factory.create.return_value = {"attempt": "D2"} + mock_requests_session.request.side_effect = [response_500, response_200] + + with patch("time.sleep"): + network_client.fetch( + FetchOptions( + method="POST", + url="https://example.com", + content_type="application/x-www-form-urlencoded", + data={"attempt": "D1"}, + data_factory=data_factory, + network_session=NetworkSession(retry_strategy=retry_strategy), + ) + ) + + assert retry_strategy.data == [{"attempt": "D1"}, {"attempt": "D2"}] + + +def test_retry_without_data_factory_reuses_request_data( + network_client, + mock_requests_session, + network_session_mock, + response_500, + response_200, +): + mock_requests_session.request.side_effect = [response_500, response_200] + + with patch("time.sleep"): + network_client.fetch( + FetchOptions( + method="POST", + url="https://example.com", + content_type="application/x-www-form-urlencoded", + data={"attempt": "D1"}, + network_session=network_session_mock, + ) + ) + + bodies = [ + call.kwargs["data"] for call in mock_requests_session.request.call_args_list + ] + assert bodies == ["attempt=D1", "attempt=D1"] + + +def _create_jwt_auth(): + passphrase = b"passphrase" + private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + private_key_pem = private_key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.BestAvailableEncryption(passphrase), + ).decode("ascii") + + return BoxJWTAuth( + config=JWTConfig( + client_id="client-id", + client_secret="client-secret", + enterprise_id="enterprise-id", + jwt_key_id="jwt-key-id", + private_key=private_key_pem, + private_key_passphrase=passphrase.decode("ascii"), + ) + ) + + +def _decode_jwt_payload(assertion): + payload = assertion.split(".")[1] + padded_payload = payload + "=" * (-len(payload) % 4) + return json.loads(base64.urlsafe_b64decode(padded_payload)) + + +@pytest.fixture +def jwt_token_server(): + bodies = [] + statuses = [500, 200] + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def do_POST(self): + body = _read_request_body(self) + bodies.append(body.decode("utf-8")) + status = statuses.pop(0) + response_body = ( + b'{"access_token":"token","expires_in":3600,"token_type":"bearer"}' + ) + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(response_body))) + self.end_headers() + self.wfile.write(response_body) + + def log_message(self, *args): + pass + + server = HTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + yield f"http://127.0.0.1:{server.server_port}", bodies + server.shutdown() + server.server_close() + + +class OneSecondRetryStrategy: + def should_retry(self, fetch_options, fetch_response, attempt_number): + return fetch_response.status == 500 + + def retry_after(self, fetch_options, fetch_response, attempt_number): + return 1 + + +def test_box_jwt_auth_regenerates_assertion_on_token_request_retry(jwt_token_server): + url, bodies = jwt_token_server + auth = _create_jwt_auth() + + auth.refresh_token( + network_session=NetworkSession( + base_urls=BaseUrls(base_url=url, upload_url=url, oauth_2_url=url), + retry_strategy=OneSecondRetryStrategy(), + ) + ) + + assert len(bodies) == 2 + first_assertion = parse_qs(bodies[0])["assertion"][0] + second_assertion = parse_qs(bodies[1])["assertion"][0] + first_payload = _decode_jwt_payload(first_assertion) + second_payload = _decode_jwt_payload(second_assertion) + + assert second_payload["jti"] != first_payload["jti"] + assert second_payload["exp"] > first_payload["exp"] + + def test_status_code_202_with_no_retry_after_header( network_client, mock_requests_session, network_session_mock, response_202 ): From a6f09d70b9a806171cb224234c1e290ecf6c1c59 Mon Sep 17 00:00:00 2001 From: box-sdk-build Date: Tue, 17 Nov 2026 11:44:48 -0800 Subject: [PATCH 2/2] docs: publish ai_session docs (AGNTPLAT-3186) (box/box-openapi#630) --- .codegen.json | 2 +- box_sdk_gen/client.py | 5 + box_sdk_gen/managers/__init__.py | 2 + box_sdk_gen/managers/ai_sessions.py | 222 ++++++++++++++++++ box_sdk_gen/managers/sign_requests.py | 2 +- box_sdk_gen/schemas/sign_request.py | 2 +- box_sdk_gen/schemas/sign_request_base.py | 2 +- .../schemas/sign_request_create_request.py | 2 +- box_sdk_gen/schemas/v2026_r0/__init__.py | 4 + .../schemas/v2026_r0/ai_session_v2026_r0.py | 72 ++++++ .../schemas/v2026_r0/ai_sessions_v2026_r0.py | 34 +++ docs/box_sdk_gen/README.md | 1 + docs/box_sdk_gen/ai_sessions.md | 82 +++++++ docs/box_sdk_gen/sign_requests.md | 2 +- 14 files changed, 428 insertions(+), 6 deletions(-) create mode 100644 box_sdk_gen/managers/ai_sessions.py create mode 100644 box_sdk_gen/schemas/v2026_r0/ai_session_v2026_r0.py create mode 100644 box_sdk_gen/schemas/v2026_r0/ai_sessions_v2026_r0.py create mode 100644 docs/box_sdk_gen/ai_sessions.md diff --git a/.codegen.json b/.codegen.json index 9239eade7..232b5e05d 100644 --- a/.codegen.json +++ b/.codegen.json @@ -1 +1 @@ -{ "engineHash": "6772894", "specHash": "7f8494a", "version": "4.20.0" } +{ "engineHash": "6772894", "specHash": "7cec401", "version": "4.20.0" } diff --git a/box_sdk_gen/client.py b/box_sdk_gen/client.py index 8bd2a0dc2..038a7cbbc 100644 --- a/box_sdk_gen/client.py +++ b/box_sdk_gen/client.py @@ -204,6 +204,8 @@ from box_sdk_gen.managers.shuttle import ShuttleManager +from box_sdk_gen.managers.ai_sessions import AiSessionsManager + from box_sdk_gen.networking.auth import Authentication from box_sdk_gen.networking.network import NetworkSession @@ -489,6 +491,9 @@ def __init__( self.shuttle = ShuttleManager( auth=self.auth, network_session=self.network_session ) + self.ai_sessions = AiSessionsManager( + auth=self.auth, network_session=self.network_session + ) def make_request(self, fetch_options: FetchOptions) -> FetchResponse: """ diff --git a/box_sdk_gen/managers/__init__.py b/box_sdk_gen/managers/__init__.py index ceffc2810..0e513db0e 100644 --- a/box_sdk_gen/managers/__init__.py +++ b/box_sdk_gen/managers/__init__.py @@ -173,3 +173,5 @@ from box_sdk_gen.managers.query import * from box_sdk_gen.managers.shuttle import * + +from box_sdk_gen.managers.ai_sessions import * diff --git a/box_sdk_gen/managers/ai_sessions.py b/box_sdk_gen/managers/ai_sessions.py new file mode 100644 index 000000000..4e16d7028 --- /dev/null +++ b/box_sdk_gen/managers/ai_sessions.py @@ -0,0 +1,222 @@ +from enum import Enum + +from typing import Optional + +from typing import List + +from typing import Dict + +from box_sdk_gen.internal.utils import to_string + +from box_sdk_gen.serialization.json import deserialize + +from box_sdk_gen.networking.fetch_options import ResponseFormat + +from box_sdk_gen.schemas.v2026_r0.ai_sessions_v2026_r0 import AiSessionsV2026R0 + +from box_sdk_gen.schemas.v2026_r0.client_error_v2026_r0 import ClientErrorV2026R0 + +from box_sdk_gen.parameters.v2026_r0.box_version_header_v2026_r0 import ( + BoxVersionHeaderV2026R0, +) + +from box_sdk_gen.box.errors import BoxSDKError + +from box_sdk_gen.networking.auth import Authentication + +from box_sdk_gen.networking.network import NetworkSession + +from box_sdk_gen.networking.fetch_options import FetchOptions + +from box_sdk_gen.networking.fetch_response import FetchResponse + +from box_sdk_gen.internal.utils import prepare_params + +from box_sdk_gen.internal.utils import to_string + +from box_sdk_gen.internal.utils import ByteStream + +from box_sdk_gen.serialization.json import sd_to_json + +from box_sdk_gen.serialization.json import SerializedData + + +class GetAiSessionsV2026R0Source(str, Enum): + API = 'api' + + +class GetAiSessionsV2026R0Sort(str, Enum): + CREATED_AT = 'created_at' + UPDATED_AT = 'updated_at' + NAME = 'name' + + +class GetAiSessionsV2026R0Direction(str, Enum): + ASC = 'asc' + DESC = 'desc' + + +class AiSessionsManager: + def __init__( + self, + *, + auth: Optional[Authentication] = None, + network_session: Optional[NetworkSession] = None + ): + if network_session is None: + network_session = NetworkSession() + self.auth = auth + self.network_session = network_session + + def get_ai_sessions_v2026_r0( + self, + source: GetAiSessionsV2026R0Source, + *, + marker: Optional[str] = None, + sort: Optional[GetAiSessionsV2026R0Sort] = None, + direction: Optional[GetAiSessionsV2026R0Direction] = None, + limit: Optional[int] = None, + client_ids: Optional[List[str]] = None, + box_version: BoxVersionHeaderV2026R0 = BoxVersionHeaderV2026R0._2026_0, + extra_headers: Optional[Dict[str, Optional[str]]] = None + ) -> AiSessionsV2026R0: + """ + Returns a marker-paginated list of the AI sessions that the authenticated + + user can read and that were created through the Box public API. Entries are + + + ordered by `sort` and `direction`, defaulting to `updated_at` descending so + + + the most recently active session appears first. + + + The access token must have both the `ai.readwrite` and `root_readwrite` + + + scopes. + + + A page may contain fewer than `limit` entries while further pages remain. + + + Treat a non-null `next_marker` as the only signal that more results exist. + + :param source: Restricts the list to AI sessions with this origin. The only supported + value is `api`. + :type source: GetAiSessionsV2026R0Source + :param marker: The position marker at which to begin returning results, as returned in + `next_marker` by the previous page. Omit it for the first page. All other + parameters must match the request that returned the marker., defaults to None + :type marker: Optional[str], optional + :param sort: The field to sort results by. Possible values are `created_at`, + `updated_at`, and `name`. Default is `updated_at`, which advances on each + turn of session activity., defaults to None + :type sort: Optional[GetAiSessionsV2026R0Sort], optional + :param direction: The direction to sort results in, either ascending (`asc`) or + descending (`desc`). Default is `desc`., defaults to None + :type direction: Optional[GetAiSessionsV2026R0Direction], optional + :param limit: The maximum number of AI sessions to return per page. The maximum is + `100`; larger values are treated as `100`. The server may return fewer + entries than requested., defaults to None + :type limit: Optional[int], optional + :param client_ids: A comma-separated list of OAuth client IDs. Restricts the list to AI + sessions created by any of these applications. Client IDs that match no + application are ignored, so the response is an empty list if none of them + match. Empty entries are ignored, and an empty value is treated as if the + parameter were not provided., defaults to None + :type client_ids: Optional[List[str]], optional + :param box_version: Version header., defaults to BoxVersionHeaderV2026R0._2026_0 + :type box_version: BoxVersionHeaderV2026R0, optional + :param extra_headers: Extra headers that will be included in the HTTP request., defaults to None + :type extra_headers: Optional[Dict[str, Optional[str]]], optional + """ + if extra_headers is None: + extra_headers = {} + query_params_map: Dict[str, str] = prepare_params( + { + 'source': to_string(source), + 'marker': to_string(marker), + 'sort': to_string(sort), + 'direction': to_string(direction), + 'limit': to_string(limit), + 'client_ids': to_string(client_ids), + } + ) + headers_map: Dict[str, str] = prepare_params( + {'box-version': to_string(box_version), **extra_headers} + ) + response: FetchResponse = self.network_session.network_client.fetch( + FetchOptions( + url=''.join( + [self.network_session.base_urls.base_url, '/2.0/ai_sessions'] + ), + method='GET', + params=query_params_map, + headers=headers_map, + response_format=ResponseFormat.JSON, + auth=self.auth, + network_session=self.network_session, + ) + ) + return deserialize(response.data, AiSessionsV2026R0) + + def delete_ai_session_by_id_v2026_r0( + self, + ai_session_id: str, + *, + box_version: BoxVersionHeaderV2026R0 = BoxVersionHeaderV2026R0._2026_0, + extra_headers: Optional[Dict[str, Optional[str]]] = None + ) -> None: + """ + Deletes an AI session created through the Box public API, together with its + + agent tasks. The session's agent-generated files and uploaded files are + + + moved to the trash. Files attached as sources from elsewhere in Box are not + + + affected. Deleting a session does not stop a running task or notify the + + + agent. + + + The access token must have both the `ai.readwrite` and `root_readwrite` + + + scopes. + + :param ai_session_id: The unique identifier of the AI session. This is the same value returned as + `id` by the list endpoint and used as the A2A `contextId`. + Example: "23489723" + :type ai_session_id: str + :param box_version: Version header., defaults to BoxVersionHeaderV2026R0._2026_0 + :type box_version: BoxVersionHeaderV2026R0, optional + :param extra_headers: Extra headers that will be included in the HTTP request., defaults to None + :type extra_headers: Optional[Dict[str, Optional[str]]], optional + """ + if extra_headers is None: + extra_headers = {} + headers_map: Dict[str, str] = prepare_params( + {'box-version': to_string(box_version), **extra_headers} + ) + response: FetchResponse = self.network_session.network_client.fetch( + FetchOptions( + url=''.join( + [ + self.network_session.base_urls.base_url, + '/2.0/ai_sessions/', + to_string(ai_session_id), + ] + ), + method='DELETE', + headers=headers_map, + response_format=ResponseFormat.NO_CONTENT, + auth=self.auth, + network_session=self.network_session, + ) + ) + return None diff --git a/box_sdk_gen/managers/sign_requests.py b/box_sdk_gen/managers/sign_requests.py index a9bd89755..2eee70c8a 100644 --- a/box_sdk_gen/managers/sign_requests.py +++ b/box_sdk_gen/managers/sign_requests.py @@ -299,7 +299,7 @@ def create_sign_request( :type are_text_signatures_enabled: Optional[bool], optional :param email_subject: Subject of sign request email. This is cleaned by sign request. If this field is not passed, a default subject will be used., defaults to None :type email_subject: Union[Optional[str], NullValue], optional - :param email_message: Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `acronym`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used., defaults to None + :param email_message: Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used., defaults to None :type email_message: Union[Optional[str], NullValue], optional :param are_reminders_enabled: Reminds signers to sign a document on day 3, 8, 13 and 18. Reminders are only sent to outstanding signers., defaults to None :type are_reminders_enabled: Optional[bool], optional diff --git a/box_sdk_gen/schemas/sign_request.py b/box_sdk_gen/schemas/sign_request.py index 1cdf35034..c9a725ce5 100644 --- a/box_sdk_gen/schemas/sign_request.py +++ b/box_sdk_gen/schemas/sign_request.py @@ -155,7 +155,7 @@ def __init__( :type are_text_signatures_enabled: Optional[bool], optional :param email_subject: Subject of sign request email. This is cleaned by sign request. If this field is not passed, a default subject will be used., defaults to None :type email_subject: Optional[str], optional - :param email_message: Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `acronym`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used., defaults to None + :param email_message: Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used., defaults to None :type email_message: Optional[str], optional :param are_reminders_enabled: Reminds signers to sign a document on day 3, 8, 13 and 18. Reminders are only sent to outstanding signers., defaults to None :type are_reminders_enabled: Optional[bool], optional diff --git a/box_sdk_gen/schemas/sign_request_base.py b/box_sdk_gen/schemas/sign_request_base.py index abad716d3..0c34d7e0e 100644 --- a/box_sdk_gen/schemas/sign_request_base.py +++ b/box_sdk_gen/schemas/sign_request_base.py @@ -40,7 +40,7 @@ def __init__( :type are_text_signatures_enabled: Optional[bool], optional :param email_subject: Subject of sign request email. This is cleaned by sign request. If this field is not passed, a default subject will be used., defaults to None :type email_subject: Optional[str], optional - :param email_message: Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `acronym`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used., defaults to None + :param email_message: Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used., defaults to None :type email_message: Optional[str], optional :param are_reminders_enabled: Reminds signers to sign a document on day 3, 8, 13 and 18. Reminders are only sent to outstanding signers., defaults to None :type are_reminders_enabled: Optional[bool], optional diff --git a/box_sdk_gen/schemas/sign_request_create_request.py b/box_sdk_gen/schemas/sign_request_create_request.py index a1d53a5c9..8836ef619 100644 --- a/box_sdk_gen/schemas/sign_request_create_request.py +++ b/box_sdk_gen/schemas/sign_request_create_request.py @@ -71,7 +71,7 @@ def __init__( :type are_text_signatures_enabled: Optional[bool], optional :param email_subject: Subject of sign request email. This is cleaned by sign request. If this field is not passed, a default subject will be used., defaults to None :type email_subject: Optional[str], optional - :param email_message: Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `acronym`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used., defaults to None + :param email_message: Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used., defaults to None :type email_message: Optional[str], optional :param are_reminders_enabled: Reminds signers to sign a document on day 3, 8, 13 and 18. Reminders are only sent to outstanding signers., defaults to None :type are_reminders_enabled: Optional[bool], optional diff --git a/box_sdk_gen/schemas/v2026_r0/__init__.py b/box_sdk_gen/schemas/v2026_r0/__init__.py index ae356c867..c5e3905ff 100644 --- a/box_sdk_gen/schemas/v2026_r0/__init__.py +++ b/box_sdk_gen/schemas/v2026_r0/__init__.py @@ -191,3 +191,7 @@ from box_sdk_gen.schemas.v2026_r0.shuttle_run_v2026_r0 import * from box_sdk_gen.schemas.v2026_r0.shuttle_runs_v2026_r0 import * + +from box_sdk_gen.schemas.v2026_r0.ai_session_v2026_r0 import * + +from box_sdk_gen.schemas.v2026_r0.ai_sessions_v2026_r0 import * diff --git a/box_sdk_gen/schemas/v2026_r0/ai_session_v2026_r0.py b/box_sdk_gen/schemas/v2026_r0/ai_session_v2026_r0.py new file mode 100644 index 000000000..846a1dc96 --- /dev/null +++ b/box_sdk_gen/schemas/v2026_r0/ai_session_v2026_r0.py @@ -0,0 +1,72 @@ +from enum import Enum + +from typing import Optional + +from box_sdk_gen.internal.base_object import BaseObject + +from box_sdk_gen.schemas.v2026_r0.user_base_v2026_r0 import UserBaseV2026R0 + +from box_sdk_gen.box.errors import BoxSDKError + +from box_sdk_gen.internal.utils import DateTime + + +class AiSessionV2026R0TypeField(str, Enum): + AI_SESSION = 'ai_session' + + +class AiSessionV2026R0SourceField(str, Enum): + API = 'api' + + +class AiSessionV2026R0(BaseObject): + _discriminator = 'type', {'ai_session'} + + def __init__( + self, + id: str, + created_by: UserBaseV2026R0, + updated_by: UserBaseV2026R0, + created_at: DateTime, + updated_at: DateTime, + *, + type: AiSessionV2026R0TypeField = AiSessionV2026R0TypeField.AI_SESSION, + name: Optional[str] = None, + source: AiSessionV2026R0SourceField = AiSessionV2026R0SourceField.API, + client_id: Optional[str] = None, + **kwargs + ): + """ + :param id: The unique identifier for the AI session. This is also the A2A + `contextId` for the conversation. Treat the value as opaque. + :type id: str + :param created_at: The date and time when the AI session was created. + :type created_at: DateTime + :param updated_at: The date and time when the AI session was last updated. It advances on + each turn of session activity, so it also serves as the most recently + used ordering. + :type updated_at: DateTime + :param type: The value is always `ai_session`., defaults to AiSessionV2026R0TypeField.AI_SESSION + :type type: AiSessionV2026R0TypeField, optional + :param name: The display name of the AI session. Sessions created through the A2A API + are named automatically. The value is `null` only when no name was + recorded., defaults to None + :type name: Optional[str], optional + :param source: The origin of the AI session. Currently always `api`. New values + may be added, so clients must tolerate values they do not recognize., defaults to AiSessionV2026R0SourceField.API + :type source: AiSessionV2026R0SourceField, optional + :param client_id: The OAuth client ID of the application that created the AI session, as + shown in the Developer Console. The value is `null` if the application is + not known., defaults to None + :type client_id: Optional[str], optional + """ + super().__init__(**kwargs) + self.id = id + self.created_by = created_by + self.updated_by = updated_by + self.created_at = created_at + self.updated_at = updated_at + self.type = type + self.name = name + self.source = source + self.client_id = client_id diff --git a/box_sdk_gen/schemas/v2026_r0/ai_sessions_v2026_r0.py b/box_sdk_gen/schemas/v2026_r0/ai_sessions_v2026_r0.py new file mode 100644 index 000000000..f72457da8 --- /dev/null +++ b/box_sdk_gen/schemas/v2026_r0/ai_sessions_v2026_r0.py @@ -0,0 +1,34 @@ +from typing import List + +from typing import Optional + +from box_sdk_gen.internal.base_object import BaseObject + +from box_sdk_gen.schemas.v2026_r0.ai_session_v2026_r0 import AiSessionV2026R0 + +from box_sdk_gen.box.errors import BoxSDKError + + +class AiSessionsV2026R0(BaseObject): + def __init__( + self, + entries: List[AiSessionV2026R0], + limit: int, + *, + next_marker: Optional[str] = None, + **kwargs + ): + """ + :param entries: A list of AI sessions. The list is empty when there are no results. + :type entries: List[AiSessionV2026R0] + :param limit: The limit that was used for these entries. This will be the same as the + `limit` query parameter unless that value exceeded the maximum value + allowed. The maximum value varies by API. + :type limit: int + :param next_marker: The marker for the start of the next page of results., defaults to None + :type next_marker: Optional[str], optional + """ + super().__init__(**kwargs) + self.entries = entries + self.limit = limit + self.next_marker = next_marker diff --git a/docs/box_sdk_gen/README.md b/docs/box_sdk_gen/README.md index 0a73477d5..d6f26d26d 100644 --- a/docs/box_sdk_gen/README.md +++ b/docs/box_sdk_gen/README.md @@ -14,6 +14,7 @@ General explanations of the available functionality and examples of how to use the SDK are available by topic: - [Ai](ai.md) +- [Ai sessions](ai_sessions.md) - [Ai studio](ai_studio.md) - [App item associations](app_item_associations.md) - [Archives](archives.md) diff --git a/docs/box_sdk_gen/ai_sessions.md b/docs/box_sdk_gen/ai_sessions.md new file mode 100644 index 000000000..41517d578 --- /dev/null +++ b/docs/box_sdk_gen/ai_sessions.md @@ -0,0 +1,82 @@ +# AiSessionsManager + +- [List AI sessions](#list-ai-sessions) +- [Delete AI session](#delete-ai-session) + +## List AI sessions + +Returns a marker-paginated list of the AI sessions that the authenticated +user can read and that were created through the Box public API. Entries are +ordered by `sort` and `direction`, defaulting to `updated_at` descending so +the most recently active session appears first. + +The access token must have both the `ai.readwrite` and `root_readwrite` +scopes. + +A page may contain fewer than `limit` entries while further pages remain. +Treat a non-null `next_marker` as the only signal that more results exist. + +This operation is performed by calling function `get_ai_sessions_v2026_r0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2026.0/get-ai-sessions/). + +_Currently we don't have an example for calling `get_ai_sessions_v2026_r0` in integration tests_ + +### Arguments + +- source `GetAiSessionsV2026R0Source` + - Restricts the list to AI sessions with this origin. The only supported value is `api`. +- marker `Optional[str]` + - The position marker at which to begin returning results, as returned in `next_marker` by the previous page. Omit it for the first page. All other parameters must match the request that returned the marker. +- sort `Optional[GetAiSessionsV2026R0Sort]` + - The field to sort results by. Possible values are `created_at`, `updated_at`, and `name`. Default is `updated_at`, which advances on each turn of session activity. +- direction `Optional[GetAiSessionsV2026R0Direction]` + - The direction to sort results in, either ascending (`asc`) or descending (`desc`). Default is `desc`. +- limit `Optional[int]` + - The maximum number of AI sessions to return per page. The maximum is `100`; larger values are treated as `100`. The server may return fewer entries than requested. +- client_ids `Optional[List[str]]` + - A comma-separated list of OAuth client IDs. Restricts the list to AI sessions created by any of these applications. Client IDs that match no application are ignored, so the response is an empty list if none of them match. Empty entries are ignored, and an empty value is treated as if the parameter were not provided. +- box_version `BoxVersionHeaderV2026R0` + - Version header. +- extra_headers `Optional[Dict[str, Optional[str]]]` + - Extra headers that will be included in the HTTP request. + +### Returns + +This function returns a value of type `AiSessionsV2026R0`. + +Returns a paginated list of AI sessions. + +## Delete AI session + +Deletes an AI session created through the Box public API, together with its +agent tasks. The session's agent-generated files and uploaded files are +moved to the trash. Files attached as sources from elsewhere in Box are not +affected. Deleting a session does not stop a running task or notify the +agent. + +The access token must have both the `ai.readwrite` and `root_readwrite` +scopes. + +This operation is performed by calling function `delete_ai_session_by_id_v2026_r0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2026.0/delete-ai-sessions-id/). + +_Currently we don't have an example for calling `delete_ai_session_by_id_v2026_r0` in integration tests_ + +### Arguments + +- ai_session_id `str` + - The unique identifier of the AI session. This is the same value returned as `id` by the list endpoint and used as the A2A `contextId`. Example: "23489723" +- box_version `BoxVersionHeaderV2026R0` + - Version header. +- extra_headers `Optional[Dict[str, Optional[str]]]` + - Extra headers that will be included in the HTTP request. + +### Returns + +This function returns a value of type `None`. + +Returns an empty response when the AI session was successfully deleted. diff --git a/docs/box_sdk_gen/sign_requests.md b/docs/box_sdk_gen/sign_requests.md index dd703c1a4..7d012080c 100644 --- a/docs/box_sdk_gen/sign_requests.md +++ b/docs/box_sdk_gen/sign_requests.md @@ -161,7 +161,7 @@ client.sign_requests.create_sign_request([SignRequestCreateSigner(email=signer_e - email_subject `Optional[str]` - Subject of sign request email. This is cleaned by sign request. If this field is not passed, a default subject will be used. - email_message `Optional[str]` - - Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `acronym`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used. + - Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used. - are_reminders_enabled `Optional[bool]` - Reminds signers to sign a document on day 3, 8, 13 and 18. Reminders are only sent to outstanding signers. - name `Optional[str]`