1# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2# SPDX-License-Identifier: Apache-2.0
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16from collections.abc import Callable
17from typing import Any
18
19# Import botocore patch to handle AIStore redirects.
20# See https://github.com/NVIDIA/aistore/tree/main/python/aistore/botocore_patch
21from aistore.botocore_patch import botocore # noqa: F401
22
23from ..telemetry import Telemetry
24from ..types import (
25 AWARE_DATETIME_MIN,
26 CredentialsProvider,
27 ObjectMetadata,
28 RetryableError,
29 StreamingObjectWriter,
30 StreamingWriterOptions,
31)
32from .s3 import S3StorageProvider, StaticS3CredentialsProvider
33
34PROVIDER = "ais_s3"
35
36# Default dummy credentials for AIStore S3 when auth is disabled
37DEFAULT_ACCESS_KEY = "FAKEKEY"
38DEFAULT_SECRET_KEY = "FAKESECRET"
39
40
[docs]
41class AIStoreS3StorageProvider(S3StorageProvider):
42 """
43 A concrete implementation of the :py:class:`multistorageclient.types.StorageProvider` for interacting with
44 AIStore via its S3-compatible interface.
45 """
46
47 def __init__(
48 self,
49 region_name: str = "",
50 endpoint_url: str = "",
51 base_path: str = "",
52 credentials_provider: CredentialsProvider | None = None,
53 config_dict: dict[str, Any] | None = None,
54 telemetry_provider: Callable[[], Telemetry] | None = None,
55 verify: bool | str | None = None,
56 **kwargs: Any,
57 ) -> None:
58 """
59 Initializes the :py:class:`AIStoreS3StorageProvider` with AIStore S3 endpoint and optional JWT authentication.
60
61 :param region_name: The AWS region (can be any valid region, AIStore ignores this).
62 :param endpoint_url: The AIStore S3 endpoint (e.g., ``http://localhost:8080/s3`` or ``https://aistore.example.com/s3``).
63 :param base_path: The root prefix path within the bucket where all operations will be scoped.
64 :param credentials_provider: The provider to retrieve AIStore credentials (AISCredentials).
65 If not provided, uses dummy credentials for unauthenticated access.
66 :param config_dict: Resolved MSC config.
67 :param telemetry_provider: A function that provides a telemetry instance.
68 :param verify: Controls SSL certificate verification. Can be ``True`` (verify using system CA bundle, default),
69 ``False`` (skip verification for self-signed certificates), or a string path to a custom CA certificate bundle.
70 :param kwargs: Additional keyword arguments. See :py:class:`S3StorageProvider` for all available options.
71 """
72 self._ais_credentials_provider = credentials_provider
73
74 dummy_s3_credentials = StaticS3CredentialsProvider(access_key=DEFAULT_ACCESS_KEY, secret_key=DEFAULT_SECRET_KEY)
75
76 super().__init__(
77 region_name=region_name or "us-east-1",
78 endpoint_url=endpoint_url,
79 base_path=base_path,
80 credentials_provider=dummy_s3_credentials,
81 config_dict=config_dict,
82 telemetry_provider=telemetry_provider,
83 verify=verify,
84 **kwargs,
85 )
86
87 self._provider_name = PROVIDER
88
89 # Register event handler to inject JWT token if credentials are provided
90 # Use 'before-send' instead of 'before-sign' to inject the header AFTER boto3 signs the request
91 # This prevents boto3 from overwriting our Authorization header with AWS signatures
92 if self._ais_credentials_provider:
93 self._s3_client.meta.events.register("before-send.s3.*", self._inject_auth_header)
94
95 def _can_use_rust_metadata(self, bucket: str, key: str) -> bool:
96 # JWT authorization is injected only by the boto3 event hook.
97 return not self._ais_credentials_provider and super()._can_use_rust_metadata(bucket, key)
98
99 def _open_streaming_writer(
100 self, path: str, attributes: dict[str, str] | None, options: StreamingWriterOptions
101 ) -> StreamingObjectWriter:
102 # Streaming uses the Rust client, which cannot carry the JWT the boto3 hook injects.
103 if self._ais_credentials_provider:
104 raise NotImplementedError("Streaming writes are not supported for ais_s3 with JWT authentication.")
105 return super()._open_streaming_writer(path, attributes, options)
106
107 def _get_object_metadata(self, path: str, strict: bool = True) -> ObjectMetadata:
108 """
109 Override to handle AIStore S3 API quirk where HEAD requests on directory-like paths return 400.
110 """
111 try:
112 return super()._get_object_metadata(path, strict=strict)
113 except (RuntimeError, RetryableError) as error:
114 # AIStore returns 400 for invalid HEAD requests (e.g., directory-like paths)
115 # Treat this the same as FileNotFoundError and check if it's a directory
116 if strict and "status_code: 400" in str(error):
117 path = self._append_delimiter(path)
118 if self._is_dir(path):
119 return ObjectMetadata(
120 key=path,
121 type="directory",
122 content_length=0,
123 last_modified=AWARE_DATETIME_MIN,
124 )
125 raise
126
127 def _inject_auth_header(self, request, **kwargs):
128 """
129 Event handler that injects the JWT Bearer token into the Authorization header.
130
131 This is called after boto3 signs the request but before it's sent over the network.
132 It replaces the AWS signature with the AIStore JWT token.
133 More details: https://github.com/NVIDIA/aistore/tree/main/python/aistore/botocore_patch#boto3-with-aistore-authentication
134
135 :param request: The request object from botocore containing headers, URL, etc.
136 :param kwargs: Additional keyword arguments from the event system.
137 """
138 if self._ais_credentials_provider:
139 credentials = self._ais_credentials_provider.get_credentials()
140 if credentials.token:
141 # Replace the Authorization header with the JWT Bearer token
142 request.headers["Authorization"] = f"Bearer {credentials.token}"