Store and retrieve API keys from encrypted files, env, 1Password, or a keychain.
Examples:
>>> from pathlib import Path
>>> from ures.secrets import SecureKeyManager, StorageMethod
>>> manager = SecureKeyManager(app_name="docs-demo", config_dir=Path("/tmp/ures-keys"))
>>> manager.store_key("ieee", "secret-token", method=StorageMethod.ENCRYPTED)
True
>>> manager.get_key("ieee")
'secret-token'
Initialize the SecureKeyManager.
Parameters:
-
app_name
(str, default:
'default'
)
–
Application name for namespacing keys
-
config_dir
(Optional[Union[str, Path]], default:
None
)
–
Custom directory for storing encrypted keys
Source code in ures/secrets.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80 | def __init__(
self, app_name: str = "default", config_dir: Optional[Union[str, Path]] = None
):
"""
Initialize the SecureKeyManager.
Args:
app_name: Application name for namespacing keys
config_dir: Custom directory for storing encrypted keys
"""
self.app_name = app_name
if config_dir:
self.config_dir = Path(config_dir)
else:
# Use platform-appropriate config directory
if os.name == "nt": # Windows
self.config_dir = (
Path.home() / "AppData" / "Local" / f"SecureKeys-{app_name}"
)
else: # Unix-like
self.config_dir = Path.home() / f".ures-secure-keys-{app_name}"
self.config_dir.mkdir(parents=True, exist_ok=True)
self.key_file = self.config_dir / "encrypted_keys.json"
self.logger = logging.getLogger(__name__)
# Generate or load encryption key
self.encryption_key = self._get_or_create_encryption_key()
# 1Password client cache
self._onepassword_client = None
|
store_key
store_key(service: str, api_key: str, method: StorageMethod = StorageMethod.ENCRYPTED) -> bool
Store API key using specified method.
Parameters:
-
service
(str)
–
Service name (e.g., 'ieee', 'springer')
-
api_key
(str)
–
The API key to store or reference
-
method
(StorageMethod, default:
ENCRYPTED
)
–
Storage method ('encrypted', 'env', '1password', 'keychain')
Returns:
-
bool ( bool
) –
True when the key was stored.
Examples:
>>> from pathlib import Path
>>> manager = SecureKeyManager(app_name="docs-demo", config_dir=Path("/tmp/ures-keys"))
>>> manager.store_key("ieee", "secret-token")
True
Source code in ures/secrets.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214 | def store_key(
self,
service: str,
api_key: str,
method: StorageMethod = StorageMethod.ENCRYPTED,
) -> bool:
"""
Store API key using specified method.
Args:
service: Service name (e.g., 'ieee', 'springer')
api_key: The API key to store or reference
method: Storage method ('encrypted', 'env', '1password', 'keychain')
Returns:
bool: True when the key was stored.
Examples:
>>> from pathlib import Path
>>> manager = SecureKeyManager(app_name="docs-demo", config_dir=Path("/tmp/ures-keys"))
>>> manager.store_key("ieee", "secret-token")
True
"""
try:
if method == StorageMethod.ENCRYPTED:
return self._store_encrypted_key(service, api_key)
elif method == StorageMethod.ENV:
return self._store_env_reference(service, api_key)
elif method == StorageMethod.ONEPASSWORD:
return self._store_1password_reference(service, api_key)
elif method == StorageMethod.KEYCHAIN:
return self._store_keychain_reference(service, api_key)
else:
raise ValueError(f"Unsupported storage method: {method}")
except Exception as e:
self.logger.error(f"Failed to store key for {service}: {e}")
return False
|
get_key
get_key(service: str) -> Optional[str]
Retrieve API key using stored method (synchronous wrapper).
Parameters:
Returns:
-
Optional[str]
–
str | None: The API key if found and accessible.
Examples:
>>> manager = SecureKeyManager(app_name="docs-demo")
>>> manager.get_key("missing-service") is None
True
Source code in ures/secrets.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319 | def get_key(self, service: str) -> Optional[str]:
"""
Retrieve API key using stored method (synchronous wrapper).
Args:
service: Service name
Returns:
str | None: The API key if found and accessible.
Examples:
>>> manager = SecureKeyManager(app_name="docs-demo")
>>> manager.get_key("missing-service") is None
True
"""
# For 1Password, we need to handle async
encrypted_keys = self._load_encrypted_keys()
if service not in encrypted_keys:
return None
key_info = encrypted_keys[service]
method = key_info.get("method", StorageMethod.ENCRYPTED.value)
if method == StorageMethod.ONEPASSWORD.value:
# Run async method in event loop
try:
return asyncio.run(
self._get_1password_key_async(key_info.get("op_reference", ""))
)
except Exception as e:
self.logger.error(f"Failed to get 1Password key synchronously: {e}")
return None
else:
# Handle other methods synchronously
return self._get_key_sync(service)
|
get_key_async
async
get_key_async(service: str) -> Optional[str]
Retrieve API key using stored method (async version).
Parameters:
Returns:
-
Optional[str]
–
str | None: The API key if found and accessible.
Source code in ures/secrets.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379 | async def get_key_async(self, service: str) -> Optional[str]:
"""
Retrieve API key using stored method (async version).
Args:
service: Service name
Returns:
str | None: The API key if found and accessible.
"""
try:
encrypted_keys = self._load_encrypted_keys()
if service not in encrypted_keys:
return None
key_info = encrypted_keys[service]
method = key_info.get("method", StorageMethod.ENCRYPTED.value)
if method == StorageMethod.ENCRYPTED.value:
return self._decrypt_value(key_info.get("value", ""))
elif method == StorageMethod.ENV.value:
env_var = key_info.get("env_var", "")
return os.getenv(env_var)
elif method == StorageMethod.ONEPASSWORD.value:
return await self._get_1password_key_async(
key_info.get("op_reference", "")
)
elif method == StorageMethod.KEYCHAIN.value:
return self._get_keychain_key(key_info.get("keychain_service", ""))
except Exception as e:
self.logger.error(f"Failed to retrieve key for {service}: {e}")
return None
|
list_keys
list_keys() -> Dict[str, Dict]
List all stored API key references without revealing actual keys.
Returns:
-
dict ( Dict[str, Dict]
) –
Service information including method and accessibility
Source code in ures/secrets.py
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495 | def list_keys(self) -> Dict[str, Dict]:
"""
List all stored API key references without revealing actual keys.
Returns:
dict: Service information including method and accessibility
"""
try:
encrypted_keys = self._load_encrypted_keys()
display_keys = {}
for service, info in encrypted_keys.items():
# Only show keys for this app
if info.get("app_name") != self.app_name:
continue
display_info = {
"method": info.get("method", StorageMethod.ENCRYPTED.value),
"created_at": info.get("created_at", ""),
"has_key": bool(self.get_key(service)),
}
method = info.get("method", StorageMethod.ENCRYPTED.value)
if method == StorageMethod.ENV.value:
display_info["env_var"] = info.get("env_var", "")
elif method == StorageMethod.ONEPASSWORD.value:
display_info["op_reference"] = info.get("op_reference", "")
elif method == StorageMethod.KEYCHAIN.value:
display_info["keychain_service"] = info.get("keychain_service", "")
display_keys[service] = display_info
return display_keys
except Exception as e:
self.logger.error(f"Failed to list keys: {e}")
return {}
|
delete_key
delete_key(service: str) -> bool
Delete stored API key reference.
Parameters:
Returns:
Source code in ures/secrets.py
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521 | def delete_key(self, service: str) -> bool:
"""
Delete stored API key reference.
Args:
service: Service name
Returns:
bool: Success status
"""
try:
encrypted_keys = self._load_encrypted_keys()
if service in encrypted_keys:
del encrypted_keys[service]
success = self._save_encrypted_keys(encrypted_keys)
if success:
self.logger.info(f"Deleted key for {service}")
return success
return True # Already deleted
except Exception as e:
self.logger.error(f"Failed to delete key for {service}: {e}")
return False
|
test_key_access
test_key_access(service: str) -> Dict[str, any]
Test if a key is accessible and return status info.
Parameters:
Returns:
Source code in ures/secrets.py
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563 | def test_key_access(self, service: str) -> Dict[str, any]:
"""
Test if a key is accessible and return status info.
Args:
service: Service name
Returns:
dict: Status information
"""
result = {
"service": service,
"exists": False,
"accessible": False,
"method": None,
"error": None,
}
try:
encrypted_keys = self._load_encrypted_keys()
if service not in encrypted_keys:
result["error"] = "Key not configured"
return result
result["exists"] = True
result["method"] = encrypted_keys[service].get(
"method", StorageMethod.ENCRYPTED.value
)
key = self.get_key(service)
if key:
result["accessible"] = True
result["key_length"] = len(key)
else:
result["error"] = "Key exists but not accessible"
except Exception as e:
result["error"] = str(e)
return result
|
export_config
export_config(include_encrypted: bool = False) -> Dict
Export configuration for backup or migration.
Parameters:
-
include_encrypted
(bool, default:
False
)
–
Whether to include encrypted values (use with caution)
Returns:
Source code in ures/secrets.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622 | def export_config(self, include_encrypted: bool = False) -> Dict:
"""
Export configuration for backup or migration.
Args:
include_encrypted: Whether to include encrypted values (use with caution)
Returns:
dict: Configuration data
"""
try:
encrypted_keys = self._load_encrypted_keys()
if not include_encrypted:
# Remove encrypted values for safety
safe_keys = {}
for service, info in encrypted_keys.items():
if info.get("app_name") == self.app_name:
safe_info = {k: v for k, v in info.items() if k != "value"}
safe_keys[service] = safe_info
return safe_keys
return {
k: v
for k, v in encrypted_keys.items()
if v.get("app_name") == self.app_name
}
except Exception as e:
self.logger.error(f"Failed to export config: {e}")
return {}
|
import_config
import_config(config_data: Dict, overwrite: bool = False) -> bool
Import configuration from backup.
Parameters:
-
config_data
(Dict)
–
-
overwrite
(bool, default:
False
)
–
Whether to overwrite existing keys
Returns:
Source code in ures/secrets.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650 | def import_config(self, config_data: Dict, overwrite: bool = False) -> bool:
"""
Import configuration from backup.
Args:
config_data: Configuration data
overwrite: Whether to overwrite existing keys
Returns:
bool: Success status
"""
try:
encrypted_keys = self._load_encrypted_keys()
for service, info in config_data.items():
if not overwrite and service in encrypted_keys:
continue
# Ensure app_name is set
info["app_name"] = self.app_name
encrypted_keys[service] = info
return self._save_encrypted_keys(encrypted_keys)
except Exception as e:
self.logger.error(f"Failed to import config: {e}")
return False
|
is_onepassword_available
staticmethod
is_onepassword_available() -> bool
Check if 1Password SDK is available.
Source code in ures/secrets.py
| @staticmethod
def is_onepassword_available() -> bool:
"""Check if 1Password SDK is available."""
return ONEPASSWORD_SDK_AVAILABLE
|
get_onepassword_setup_instructions
staticmethod
get_onepassword_setup_instructions() -> str
Get setup instructions for 1Password integration.
Source code in ures/secrets.py
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680 | @staticmethod
def get_onepassword_setup_instructions() -> str:
"""Get setup instructions for 1Password integration."""
return """
1Password Setup Instructions:
1. Install the 1Password SDK:
pip install onepassword
2. Create a Service Account:
- Go to your 1Password account settings
- Create a new Service Account
- Note the token (starts with 'ops_')
3. Set Environment Variable:
export OP_SERVICE_ACCOUNT_TOKEN="ops_your_token_here"
4. Store your API keys in 1Password:
- Create items for each API key
- Note the secret references (e.g., "op://vault/item/field")
5. Configure the key manager:
manager.store_key('ieee', 'op://Private/IEEE-API/credential', '1password')
"""
|