Skip to content

Commit 8b356c5

Browse files
author
Mohamed Zeidan
committed
fix: apply output KMS key to ModelTrainer source-code S3 uploads (#5956)
V2 Estimator encrypted staged user code in S3 with output_kms_key; v3 ModelTrainer uploaded source code and driver files to S3 with no KMS encryption, so it could not be used in environments whose S3 policies enforce SSE-KMS. create_input_data_channel now passes S3 ExtraArgs (ServerSideEncryption=aws:kms, SSEKMSKeyId=...) on local uploads, using an explicit new kms_key argument when given and otherwise falling back to output_data_config.kms_key_id (mirroring V2, where the output KMS key also encrypted staged code). Behavior is unchanged when no KMS key is configured (extra_args stays None).
1 parent 7ac2708 commit 8b356c5

2 files changed

Lines changed: 83 additions & 5 deletions

File tree

‎sagemaker-train/src/sagemaker/train/model_trainer.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1034,6 +1034,7 @@ def create_input_data_channel(
10341034
key_prefix: Optional[str] = None,
10351035
ignore_patterns: Optional[List[str]] = None,
10361036
instance_group_names: Optional[List[str]] = None,
1037+
kms_key: Optional[str] = None,
10371038
) -> Channel:
10381039
"""Create an input data channel for the training job.
10391040
@@ -1058,9 +1059,16 @@ def create_input_data_channel(
10581059
channel's data should be assigned to. Only applied when the channel is
10591060
built from a URI/local-path data source (not a caller-supplied
10601061
``S3DataSource``/``FileSystemDataSource``, which the caller controls).
1062+
kms_key (Optional[str]): The Amazon Web Services KMS key id (or ARN/alias) to use for
1063+
server-side encryption when uploading local data to S3. If not specified, the
1064+
``kms_key_id`` of this trainer's ``output_data_config`` is used (mirroring the V2
1065+
``Estimator`` behavior of encrypting staged user code with the output KMS key).
1066+
Only applied when ``data_source`` is a local file path.
10611067
"""
10621068
from sagemaker.core.helper.pipeline_variable import PipelineVariable
10631069

1070+
upload_extra_args = self._resolve_upload_extra_args(kms_key)
1071+
10641072
# Pass the field only when provided, so it stays unset (Unassigned) by default.
10651073
instance_group_kwargs = (
10661074
{"instance_group_names": instance_group_names}
@@ -1136,12 +1144,14 @@ def create_input_data_channel(
11361144
path=copied_path,
11371145
bucket=staging_bucket,
11381146
key_prefix=effective_prefix,
1147+
extra_args=upload_extra_args,
11391148
)
11401149
else:
11411150
s3_uri = self.sagemaker_session.upload_data(
11421151
path=data_source,
11431152
bucket=staging_bucket,
11441153
key_prefix=effective_prefix,
1154+
extra_args=upload_extra_args,
11451155
)
11461156
channel = Channel(
11471157
channel_name=channel_name,
@@ -1170,6 +1180,22 @@ def create_input_data_channel(
11701180
raise ValueError(f"Unsupported data_source type: {type(data_source)}")
11711181
return channel
11721182

1183+
def _resolve_upload_extra_args(self, kms_key: Optional[str] = None) -> Optional[dict]:
1184+
"""Build S3 ``ExtraArgs`` for encrypting local source/data uploads with KMS.
1185+
1186+
Uses the explicit ``kms_key`` if given, otherwise falls back to the
1187+
``kms_key_id`` on this trainer's ``output_data_config`` (V2 ``Estimator`` parity:
1188+
staged user code is encrypted with the output KMS key). Returns ``None`` when no
1189+
usable string key is configured, so behavior is unchanged by default (GH #5956).
1190+
A pipeline-variable key is ignored here because uploads happen at SDK compile time.
1191+
"""
1192+
resolved_key = kms_key
1193+
if resolved_key is None and self.output_data_config is not None:
1194+
resolved_key = getattr(self.output_data_config, "kms_key_id", None)
1195+
if isinstance(resolved_key, str) and resolved_key:
1196+
return {"ServerSideEncryption": "aws:kms", "SSEKMSKeyId": resolved_key}
1197+
return None
1198+
11731199
def _get_input_data_config(
11741200
self,
11751201
input_data_channels: Optional[List[Union[Channel, InputData]]],

‎sagemaker-train/tests/unit/train/test_model_trainer.py‎

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,58 @@ def test_create_input_data_channel(mock_default_bucket, mock_upload_data, model_
474474
assert channel.data_source.s3_data_source.s3_uri == expected_s3_uri
475475

476476

477+
@patch("sagemaker.train.model_trainer.Session.upload_data")
478+
@patch("sagemaker.train.model_trainer.Session.default_bucket")
479+
def test_create_input_data_channel_encrypts_uploads_with_output_kms_key(
480+
mock_default_bucket, mock_upload_data
481+
):
482+
"""GH #5956: local source uploads are encrypted with output_data_config.kms_key_id."""
483+
mock_default_bucket.return_value = DEFAULT_BUCKET
484+
mock_upload_data.return_value = f"s3://{DEFAULT_BUCKET}/code"
485+
trainer = ModelTrainer(
486+
training_image=DEFAULT_IMAGE,
487+
role=DEFAULT_ROLE,
488+
compute=DEFAULT_COMPUTE_CONFIG,
489+
stopping_condition=DEFAULT_STOPPING_CONDITION,
490+
output_data_config=OutputDataConfig(
491+
s3_output_path=f"s3://{DEFAULT_BUCKET}/out",
492+
kms_key_id="my-kms-key",
493+
),
494+
)
495+
trainer.create_input_data_channel("code", DEFAULT_SOURCE_DIR)
496+
assert mock_upload_data.call_args.kwargs["extra_args"] == {
497+
"ServerSideEncryption": "aws:kms",
498+
"SSEKMSKeyId": "my-kms-key",
499+
}
500+
501+
502+
@patch("sagemaker.train.model_trainer.Session.upload_data")
503+
@patch("sagemaker.train.model_trainer.Session.default_bucket")
504+
def test_create_input_data_channel_explicit_kms_key_overrides(
505+
mock_default_bucket, mock_upload_data, model_trainer
506+
):
507+
"""An explicit kms_key argument takes precedence over output_data_config."""
508+
mock_default_bucket.return_value = DEFAULT_BUCKET
509+
mock_upload_data.return_value = f"s3://{DEFAULT_BUCKET}/code"
510+
model_trainer.create_input_data_channel("code", DEFAULT_SOURCE_DIR, kms_key="explicit-key")
511+
assert mock_upload_data.call_args.kwargs["extra_args"] == {
512+
"ServerSideEncryption": "aws:kms",
513+
"SSEKMSKeyId": "explicit-key",
514+
}
515+
516+
517+
@patch("sagemaker.train.model_trainer.Session.upload_data")
518+
@patch("sagemaker.train.model_trainer.Session.default_bucket")
519+
def test_create_input_data_channel_no_kms_by_default(
520+
mock_default_bucket, mock_upload_data, model_trainer
521+
):
522+
"""Default (no kms_key_id) leaves uploads unencrypted -> extra_args None (unchanged)."""
523+
mock_default_bucket.return_value = DEFAULT_BUCKET
524+
mock_upload_data.return_value = f"s3://{DEFAULT_BUCKET}/code"
525+
model_trainer.create_input_data_channel("code", DEFAULT_SOURCE_DIR)
526+
assert mock_upload_data.call_args.kwargs["extra_args"] is None
527+
528+
477529
def test_create_input_data_channel_with_instance_group_names(model_trainer):
478530
"""instance_group_names is propagated onto the channel's S3DataSource."""
479531
channel = model_trainer.create_input_data_channel(
@@ -874,7 +926,7 @@ def test_remote_debug_config(mock_training_job, modules_session):
874926
@patch("sagemaker.train.model_trainer._get_unique_name")
875927
@patch("sagemaker.train.model_trainer.TrainingJob")
876928
def test_model_trainer_full_init(mock_training_job, mock_unique_name, modules_session):
877-
def mock_upload_data(path, bucket, key_prefix):
929+
def mock_upload_data(path, bucket, key_prefix, extra_args=None):
878930
return f"s3://{bucket}/{key_prefix}"
879931

880932
modules_session.upload_data.side_effect = mock_upload_data
@@ -1152,7 +1204,7 @@ def mock_upload_data(path, bucket, key_prefix):
11521204
# def test_model_trainer_local_full_init(
11531205
# mock_download_folder, mock_unique_name, mock_local_container, modules_session
11541206
# ):
1155-
# def mock_upload_data(path, bucket, key_prefix):
1207+
# def mock_upload_data(path, bucket, key_prefix, extra_args=None):
11561208
# return f"s3://{bucket}/{key_prefix}"
11571209

11581210
# modules_session.upload_data.side_effect = mock_upload_data
@@ -1406,7 +1458,7 @@ def test_hyperparameters_invalid(mock_exists, modules_session):
14061458
@patch("sagemaker.train.model_trainer._get_unique_name")
14071459
@patch("sagemaker.train.model_trainer.TrainingJob")
14081460
def test_model_trainer_default_paths(mock_training_job, mock_unique_name, modules_session):
1409-
def mock_upload_data(path, bucket, key_prefix):
1461+
def mock_upload_data(path, bucket, key_prefix, extra_args=None):
14101462
return f"s3://{bucket}/{key_prefix}"
14111463

14121464
unique_name = "base-job-0123456789"
@@ -1510,7 +1562,7 @@ def test_metric_definitions(mock_training_job, modules_session):
15101562
@patch("sagemaker.train.model_trainer._get_unique_name")
15111563
@patch("sagemaker.core.resources.TrainingJob")
15121564
def test_nova_recipe(mock_training_job, mock_unique_name, modules_session):
1513-
def mock_upload_data(path, bucket, key_prefix):
1565+
def mock_upload_data(path, bucket, key_prefix, extra_args=None):
15141566
if os.path.isfile(path):
15151567
file_name = os.path.basename(path)
15161568
return f"s3://{bucket}/{key_prefix}/{file_name}"
@@ -1782,7 +1834,7 @@ def test_nova_recipe_model_package_config_only_mpg_from_recipe(modules_session):
17821834
@patch("sagemaker.train.model_trainer._get_unique_name")
17831835
@patch("sagemaker.train.model_trainer.TrainingJob")
17841836
def test_llmft_recipe(mock_training_job, mock_unique_name, modules_session):
1785-
def mock_upload_data(path, bucket, key_prefix):
1837+
def mock_upload_data(path, bucket, key_prefix, extra_args=None):
17861838
if os.path.isfile(path):
17871839
file_name = os.path.basename(path)
17881840
return f"s3://{bucket}/{key_prefix}/{file_name}"

0 commit comments

Comments
 (0)