1515# Add the local otdf_python source directory to sys.path
1616# sys.path.insert(0, str(Path(__file__).parent / "src"))
1717
18- from otdf_python .config import TDFConfig
1918from otdf_python .kas_info import KASInfo
2019from otdf_python .sdk_builder import SDKBuilder
2120from otdf_python .sdk import SDK
2423from tests .config_pydantic import CONFIG_TDF
2524
2625
27- def get_fallback_kas_public_key () -> str :
28- """
29- Get the KAS public key from environment variables or use a fallback.
30-
31- Returns:
32- str: The KAS public key
33- """
34- # Try to get from environment
35- kas_public_key = os .environ .get ("OPENTDF_KAS_PUBLIC_KEY" )
36- if kas_public_key :
37- return kas_public_key
38-
39- # Fallback to default test key
40- return """-----BEGIN PUBLIC KEY-----
41- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvxW+N0O+ZdYG9JDAXhCP
42- 0bc9OHCIa9IHrP0O6I1a1/gYnZXUVkL/5VX1HCTwg8lYYGjFpDXCYl7kzr42RW9K
43- nzpgmH3A7erLp0X87Jzi7CgANu38/drJ5EnjWYQ7jkGY9vF/lJFG13RlM3HjhzGV
44- eIocJaQM3U4r1WMzUwYUoZ9/QfGUdwxbGKxkaY/Z2KjaS6A35RCiQyy2K8unmY9T
45- HPQHcm0OCZZkp4mXTWF8VoGIpPACCtSBR1t6tt3nZGH+pmIYYnV+gulYbJEvcaj/
46- n1UDtivFEh1ZSWKdVLzvwBGS6+pVaXLQH+tPRUSQ7/oBL5GQEMxYnTsQcmGPJxrL
47- pQIDAQAB
48- -----END PUBLIC KEY-----"""
49-
50-
51- def _get_configuration () -> SDK :
26+ def _get_sdk () -> SDK :
5227 return (
5328 SDKBuilder ()
5429 .set_platform_endpoint (
@@ -69,92 +44,37 @@ def _get_configuration() -> SDK:
6944 )
7045
7146
72- # Helper to build TDFConfig safely, using environment variables for defaults
73- def build_tdf_config () -> TDFConfig :
74- config = {}
75-
76- # Helper to build a KASInfo from dict or env
77- def build_kasinfo_from_env_or_dict (kas ):
78- if isinstance (kas , KASInfo ):
79- return kas
80- if isinstance (kas , dict ):
81- return KASInfo (** kas )
82- # Use environment variables for defaults
83- return KASInfo (
84- url = os .environ .get ("OPENTDF_KAS_URL" , "https://default.kas.example.com" ),
85- public_key = get_fallback_kas_public_key (),
86- kid = os .environ .get ("OPENTDF_KAS_KID" , None ),
87- default = None ,
88- algorithm = None ,
89- )
90-
91- kas_info = config .get ("kas_info" )
92- if not kas_info :
93- kas_info = build_kasinfo_from_env_or_dict (None )
94- elif isinstance (kas_info , list ):
95- kas_info = [build_kasinfo_from_env_or_dict (k ) for k in kas_info ]
96- else :
97- kas_info = build_kasinfo_from_env_or_dict (kas_info )
98-
99- # Only pass valid fields for TDFConfig
100- valid_keys = {
101- "kas_info" ,
102- "kas_private_key" ,
103- "policy_object" ,
104- "attributes" ,
105- "segment_size" ,
106- }
107- filtered = {k : v for k , v in config .items () if k in valid_keys }
108- filtered ["kas_info" ] = kas_info
109-
110- # Optionally, set kas_private_key from env if not provided
111- if "kas_private_key" not in filtered or not filtered ["kas_private_key" ]:
112- filtered ["kas_private_key" ] = os .environ .get ("OPENTDF_KAS_PRIVATE_KEY" , None )
47+ def _get_sdk_and_tdf_config () -> tuple :
48+ sdk = _get_sdk ()
11349
114- # Use the new builder pattern if available
50+ # Create KASInfo without public key - let the SDK fetch it
51+ kas_info = KASInfo (
52+ url = CONFIG_TDF .OPENTDF_PLATFORM_URL ,
53+ default = True ,
54+ )
11555
116- sdk = _get_configuration ()
117- return sdk .new_tdf_config (** filtered )
56+ tdf_config = sdk .new_tdf_config (
57+ attributes = ["attr1" , "attr2" ],
58+ kas_info_list = [kas_info ], # KAS info without explicit public key
59+ )
60+ return sdk , tdf_config
11861
11962
120- def encrypt_file (input_path : Path , sdk = None ) -> Path :
63+ def encrypt_file (input_path : Path ) -> Path :
12164 """Encrypt a file and return the path to the encrypted file."""
122- if sdk is None :
123- kas_url = os .environ .get ("OPENTDF_KAS_URL" , "https://default.kas.example.com" )
12465
125- # Build the SDK
126- sdk = _get_configuration ()
127-
128- # Create KASInfo without public key - let the SDK fetch it
129- kas_info = KASInfo (url = kas_url )
130-
131- # Create config with the KASInfo
132- config = sdk .new_tdf_config (
133- attributes = ["attr1" , "attr2" ], kas_info_list = [kas_info ]
134- )
135- else :
136- # If SDK is provided, we need to create a config with attributes and KASInfo
137- # Get the platform URL from the SDK
138- kas_url = sdk .get_platform_url () or "https://default.kas.example.com"
139-
140- # Create KASInfo without public key - let the SDK fetch it
141- kas_info = KASInfo (url = kas_url )
142-
143- # Create config with attributes and KASInfo
144- config = sdk .new_tdf_config (
145- attributes = ["attr1" , "attr2" ], kas_info_list = [kas_info ]
146- )
66+ # Build the SDK
67+ sdk , tdf_config = _get_sdk_and_tdf_config ()
14768
14869 output_path = input_path .with_suffix (input_path .suffix + ".tdf" )
14970 with open (input_path , "rb" ) as infile , open (output_path , "wb" ) as outfile :
150- sdk .create_tdf (infile .read (), config , output_stream = outfile )
71+ sdk .create_tdf (infile .read (), tdf_config , output_stream = outfile )
15172 return output_path
15273
15374
154- def decrypt_file (encrypted_path : Path , sdk = None ) -> Path :
75+ def decrypt_file (encrypted_path : Path ) -> Path :
15576 """Decrypt a file and return the path to the decrypted file."""
156- if sdk is None :
157- sdk = _get_configuration ()
77+ sdk = _get_sdk ()
15878
15979 output_path = encrypted_path .with_suffix (".decrypted" )
16080 with open (encrypted_path , "rb" ) as infile , open (output_path , "wb" ) as outfile :
@@ -179,7 +99,7 @@ def decrypt_file(encrypted_path: Path, sdk=None) -> Path:
17999def verify_encrypt_str () -> None :
180100 print ("Validating string encryption (local TDF)" )
181101 try :
182- sdk = _get_configuration ()
102+ sdk = _get_sdk ()
183103
184104 payload = b"Hello from Python"
185105
@@ -189,7 +109,7 @@ def verify_encrypt_str() -> None:
189109 default = True ,
190110 )
191111
192- config = sdk .new_tdf_config (
112+ tdf_config = sdk .new_tdf_config (
193113 attributes = ["attr1" , "attr2" ],
194114 kas_info_list = [kas_info ], # KAS info without explicit public key
195115 )
@@ -198,7 +118,7 @@ def verify_encrypt_str() -> None:
198118 from io import BytesIO
199119
200120 output = BytesIO ()
201- sdk .create_tdf (payload , config , output_stream = output )
121+ sdk .create_tdf (payload , tdf_config , output_stream = output )
202122 manifest_bytes = output .getvalue ()
203123 print (f"Manifest returned: { manifest_bytes [:60 ]} ... (truncated)" )
204124 assert manifest_bytes and len (manifest_bytes ) > 0
@@ -233,6 +153,11 @@ def verify_encrypt_file() -> None:
233153 ) from e
234154
235155
156+ def test_verify_encrypt_file ():
157+ """Run the file encryption verification test."""
158+ verify_encrypt_file ()
159+
160+
236161def verify_encrypt_decrypt_file () -> None :
237162 print ("Validating encrypt/decrypt roundtrip (local TDF)" )
238163 try :
@@ -241,17 +166,12 @@ def verify_encrypt_decrypt_file() -> None:
241166 input_file = tmpDir / "plain.txt"
242167 input_file .write_text ("Secret message" )
243168
244- # Build the SDK
245- sdk = _get_configuration ()
246-
247- # Get public key from KAS
248169 try :
249- # Use the encrypt_file function which now gets the public key from KAS
250- encrypted_path = encrypt_file (input_file , sdk )
170+ encrypted_path = encrypt_file (input_file )
251171 print (f"Encrypted file at: { encrypted_path } " )
252172
253173 # Decrypt the file using the same SDK
254- decrypted_path = decrypt_file (encrypted_path , sdk )
174+ decrypted_path = decrypt_file (encrypted_path )
255175 print (f"Decrypted file at: { decrypted_path } " )
256176
257177 # Verify the result
0 commit comments