tracebit-python 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tracebit/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
tracebit/api.py ADDED
@@ -0,0 +1,65 @@
1
+ import requests
2
+
3
+ from .config import get_base_url
4
+
5
+
6
+ class TracebitError(Exception):
7
+ pass
8
+
9
+
10
+ class TracebitClient:
11
+ def __init__(self, token, base_url=None):
12
+ self.base_url = (base_url or get_base_url()).rstrip("/")
13
+ self.session = requests.Session()
14
+ self.session.headers["Authorization"] = f"Bearer {token}"
15
+ self.session.headers["Content-Type"] = "application/json"
16
+
17
+ def _url(self, path):
18
+ return f"{self.base_url}/api/v1/credentials/{path}"
19
+
20
+ def _check(self, resp, context="API request"):
21
+ if resp.status_code == 401:
22
+ raise TracebitError(
23
+ "Authentication failed (401). Check your API token."
24
+ )
25
+ if resp.status_code == 400:
26
+ raise TracebitError(f"{context} failed: {resp.text}")
27
+ resp.raise_for_status()
28
+
29
+ def generate_metadata(self):
30
+ resp = self.session.get(self._url("generate-metadata"))
31
+ self._check(resp, "Generate metadata")
32
+ return resp.json()
33
+
34
+ def issue_credentials(self, name, types, source="tracebit-python",
35
+ source_type="endpoint", labels=None):
36
+ body = {
37
+ "name": name,
38
+ "types": types,
39
+ "source": source,
40
+ "sourceType": source_type,
41
+ }
42
+ if labels:
43
+ body["labels"] = [{"name": k, "value": v} for k, v in labels.items()]
44
+ resp = self.session.post(self._url("issue-credentials"), json=body)
45
+ self._check(resp, "Issue credentials")
46
+ return resp.json()
47
+
48
+ def confirm_credentials(self, confirmation_id):
49
+ resp = self.session.post(
50
+ self._url("confirm-credentials"),
51
+ json={"id": confirmation_id},
52
+ )
53
+ if resp.status_code == 404:
54
+ raise TracebitError(
55
+ f"Confirmation ID {confirmation_id} not found."
56
+ )
57
+ self._check(resp, "Confirm credentials")
58
+
59
+ def remove_credentials(self, name, cred_type="aws"):
60
+ """Notify Tracebit to expire credentials server-side."""
61
+ resp = self.session.post(
62
+ f"{self.base_url}/api/_internal/v1/cli/remove",
63
+ json={"name": name, "type": cred_type},
64
+ )
65
+ self._check(resp, "Remove credentials")
tracebit/aws.py ADDED
@@ -0,0 +1,80 @@
1
+ import configparser
2
+ import os
3
+ from pathlib import Path
4
+
5
+
6
+ AWS_DIR = Path.home() / ".aws"
7
+ CREDENTIALS_FILE = AWS_DIR / "credentials"
8
+ CONFIG_FILE = AWS_DIR / "config"
9
+
10
+
11
+ def _ensure_aws_dir():
12
+ AWS_DIR.mkdir(mode=0o700, exist_ok=True)
13
+
14
+
15
+ def _read_ini(path):
16
+ parser = configparser.ConfigParser()
17
+ if path.exists():
18
+ parser.read(str(path))
19
+ return parser
20
+
21
+
22
+ def _write_ini(parser, path):
23
+ with open(path, "w") as f:
24
+ parser.write(f)
25
+ os.chmod(path, 0o600)
26
+
27
+
28
+ def deploy_aws_credentials(profile, region, access_key_id, secret_access_key,
29
+ session_token):
30
+ """Write canary AWS credentials to ~/.aws/credentials and ~/.aws/config."""
31
+ _ensure_aws_dir()
32
+
33
+ # credentials file
34
+ creds = _read_ini(CREDENTIALS_FILE)
35
+ if not creds.has_section(profile):
36
+ creds.add_section(profile)
37
+ creds.set(profile, "aws_access_key_id", access_key_id)
38
+ creds.set(profile, "aws_secret_access_key", secret_access_key)
39
+ creds.set(profile, "aws_session_token", session_token)
40
+ _write_ini(creds, CREDENTIALS_FILE)
41
+
42
+ # config file
43
+ config = _read_ini(CONFIG_FILE)
44
+ config_section = f"profile {profile}" if profile != "default" else "default"
45
+ if not config.has_section(config_section):
46
+ config.add_section(config_section)
47
+ config.set(config_section, "region", region)
48
+ _write_ini(config, CONFIG_FILE)
49
+
50
+
51
+ def remove_aws_credentials(profile):
52
+ """Remove a profile from both AWS credential files."""
53
+ for path, section in [
54
+ (CREDENTIALS_FILE, profile),
55
+ (CONFIG_FILE, f"profile {profile}" if profile != "default" else "default"),
56
+ ]:
57
+ if not path.exists():
58
+ continue
59
+ parser = _read_ini(path)
60
+ if parser.has_section(section):
61
+ parser.remove_section(section)
62
+ _write_ini(parser, path)
63
+
64
+
65
+ def get_aws_credentials(profile):
66
+ """Read back credentials for a profile, or None if not found."""
67
+ creds = _read_ini(CREDENTIALS_FILE)
68
+ if not creds.has_section(profile):
69
+ return None
70
+ return {
71
+ "aws_access_key_id": creds.get(profile, "aws_access_key_id", fallback=None),
72
+ "aws_secret_access_key": creds.get(profile, "aws_secret_access_key", fallback=None),
73
+ "aws_session_token": creds.get(profile, "aws_session_token", fallback=None),
74
+ }
75
+
76
+
77
+ def profile_exists(profile):
78
+ """Check if a profile already exists in the credentials file."""
79
+ creds = _read_ini(CREDENTIALS_FILE)
80
+ return creds.has_section(profile)
tracebit/cli.py ADDED
@@ -0,0 +1,435 @@
1
+ import argparse
2
+ import json
3
+ import socket
4
+ import subprocess
5
+ import sys
6
+ from datetime import datetime, timezone
7
+
8
+ import requests
9
+
10
+ from .api import TracebitClient, TracebitError
11
+ from .aws import deploy_aws_credentials, remove_aws_credentials, profile_exists
12
+ from .config import load_token, save_token
13
+ from .state import (
14
+ save_credential,
15
+ load_credentials,
16
+ remove_credential,
17
+ get_expiring_credentials,
18
+ )
19
+
20
+
21
+ def _get_client(args):
22
+ token = getattr(args, "token", None) or load_token()
23
+ if not token:
24
+ print(
25
+ "Error: No API token found. Set TRACEBIT_API_TOKEN, "
26
+ "run 'tracebit configure', or pass --token.",
27
+ file=sys.stderr,
28
+ )
29
+ sys.exit(1)
30
+ base_url = getattr(args, "base_url", None)
31
+ return TracebitClient(token, base_url=base_url)
32
+
33
+
34
+ def _parse_labels(label_args):
35
+ if not label_args:
36
+ return {}
37
+ labels = {}
38
+ for item in label_args:
39
+ if "=" not in item:
40
+ print(f"Error: Invalid label format '{item}', expected key=value",
41
+ file=sys.stderr)
42
+ sys.exit(1)
43
+ k, v = item.split("=", 1)
44
+ labels[k] = v
45
+ return labels
46
+
47
+
48
+ def cmd_configure(args):
49
+ """Save API token to config file."""
50
+ if args.token_value:
51
+ token = args.token_value
52
+ elif not sys.stdin.isatty():
53
+ token = sys.stdin.read().strip()
54
+ else:
55
+ import getpass
56
+ token = getpass.getpass("API token: ")
57
+
58
+ if not token:
59
+ print("Error: No token provided.", file=sys.stderr)
60
+ sys.exit(1)
61
+
62
+ save_token(token)
63
+ print("Token saved to ~/.config/tracebit/token")
64
+
65
+
66
+ def cmd_deploy_aws(args):
67
+ """Issue, deploy, and confirm AWS canary credentials."""
68
+ client = _get_client(args)
69
+ name = args.name or socket.gethostname()
70
+ labels = _parse_labels(args.labels)
71
+
72
+ # get defaults from API if profile/region not specified
73
+ profile = args.profile
74
+ region = args.region
75
+ if not region:
76
+ try:
77
+ meta = client.generate_metadata()
78
+ region = meta.get("awsRegion") or "us-east-1"
79
+ except Exception:
80
+ region = "us-east-1"
81
+ if not profile:
82
+ profile = "staging"
83
+
84
+ # check for existing profile (don't clobber real credentials)
85
+ if profile_exists(profile) and not args.force:
86
+ # check if it's one of ours (from state) — suggest --force
87
+ # if it's unknown, warn more strongly
88
+ ours = any(
89
+ c.get("profile") == profile
90
+ for c in load_credentials()
91
+ if c["type"] == "aws"
92
+ )
93
+ if ours:
94
+ print(
95
+ f"Error: AWS profile '{profile}' already has a canary deployed. "
96
+ f"Use --force to replace it, or 'tracebit refresh' to renew.",
97
+ file=sys.stderr,
98
+ )
99
+ else:
100
+ print(
101
+ f"Error: AWS profile '{profile}' already exists and is NOT a "
102
+ f"known canary — refusing to overwrite. Use --profile to choose "
103
+ f"a different name, or --force if you're sure.",
104
+ file=sys.stderr,
105
+ )
106
+ sys.exit(1)
107
+
108
+ # if --force and there's an existing canary for this profile, expire it first
109
+ if args.force:
110
+ existing = [
111
+ c for c in load_credentials()
112
+ if c["type"] == "aws" and c.get("profile") == profile
113
+ ]
114
+ for old in existing:
115
+ try:
116
+ client.remove_credentials(old["name"], "aws")
117
+ print(f"Expired previous canary '{old['name']}' on Tracebit.")
118
+ except TracebitError:
119
+ pass
120
+ remove_credential(old["name"], "aws")
121
+
122
+ # issue credentials
123
+ print(f"Issuing AWS canary credentials (name={name}, profile={profile})...")
124
+ try:
125
+ result = client.issue_credentials(
126
+ name=name, types=["aws"], source="tracebit-python",
127
+ source_type="endpoint", labels=labels,
128
+ )
129
+ except TracebitError as e:
130
+ print(f"Error: {e}", file=sys.stderr)
131
+ sys.exit(1)
132
+
133
+ aws = result.get("aws")
134
+ if not aws:
135
+ print("Error: No AWS credentials in response.", file=sys.stderr)
136
+ sys.exit(1)
137
+
138
+ # deploy locally
139
+ deploy_aws_credentials(
140
+ profile=profile,
141
+ region=region,
142
+ access_key_id=aws["awsAccessKeyId"],
143
+ secret_access_key=aws["awsSecretAccessKey"],
144
+ session_token=aws["awsSessionToken"],
145
+ )
146
+ print(f"Credentials written to ~/.aws/credentials [{profile}]")
147
+
148
+ # confirm deployment
149
+ try:
150
+ client.confirm_credentials(aws["awsConfirmationId"])
151
+ print("Deployment confirmed with Tracebit.")
152
+ except TracebitError as e:
153
+ print(f"Warning: Could not confirm deployment: {e}", file=sys.stderr)
154
+
155
+ # save state
156
+ save_credential({
157
+ "name": name,
158
+ "type": "aws",
159
+ "profile": profile,
160
+ "region": region,
161
+ "expiration": aws["awsExpiration"],
162
+ "confirmation_id": aws["awsConfirmationId"],
163
+ "labels": labels,
164
+ })
165
+
166
+ if args.json_output:
167
+ print(json.dumps({
168
+ "profile": profile,
169
+ "region": region,
170
+ "access_key_id": aws["awsAccessKeyId"],
171
+ "expiration": aws["awsExpiration"],
172
+ }, indent=2))
173
+ else:
174
+ print(f"\nCanary deployed successfully!")
175
+ print(f" Profile: {profile}")
176
+ print(f" Region: {region}")
177
+ print(f" Access Key: {aws['awsAccessKeyId']}")
178
+ print(f" Expires: {aws['awsExpiration']}")
179
+
180
+
181
+ def cmd_refresh(args):
182
+ """Refresh credentials expiring within the given threshold."""
183
+ client = _get_client(args)
184
+ hours = args.hours
185
+ expiring = get_expiring_credentials(hours=hours)
186
+
187
+ if not expiring:
188
+ print("No credentials need refreshing.")
189
+ return
190
+
191
+ failures = 0
192
+ for cred in expiring:
193
+ if cred["type"] != "aws":
194
+ print(f"Skipping non-AWS credential: {cred['name']}")
195
+ continue
196
+
197
+ print(f"Refreshing AWS credential '{cred['name']}'...")
198
+ try:
199
+ result = client.issue_credentials(
200
+ name=cred["name"], types=["aws"], source="tracebit-python",
201
+ source_type="endpoint", labels=cred.get("labels", {}),
202
+ )
203
+ except (TracebitError, requests.RequestException) as e:
204
+ print(f"Error refreshing {cred['name']}: {e}", file=sys.stderr)
205
+ failures += 1
206
+ continue
207
+
208
+ aws = result.get("aws")
209
+ if not aws:
210
+ print(f"Error: No AWS credentials in refresh response for {cred['name']}.",
211
+ file=sys.stderr)
212
+ failures += 1
213
+ continue
214
+
215
+ deploy_aws_credentials(
216
+ profile=cred["profile"],
217
+ region=cred["region"],
218
+ access_key_id=aws["awsAccessKeyId"],
219
+ secret_access_key=aws["awsSecretAccessKey"],
220
+ session_token=aws["awsSessionToken"],
221
+ )
222
+
223
+ try:
224
+ client.confirm_credentials(aws["awsConfirmationId"])
225
+ except (TracebitError, requests.RequestException) as e:
226
+ print(f"Warning: Could not confirm refresh for {cred['name']}: {e}",
227
+ file=sys.stderr)
228
+
229
+ save_credential({
230
+ "name": cred["name"],
231
+ "type": "aws",
232
+ "profile": cred["profile"],
233
+ "region": cred["region"],
234
+ "expiration": aws["awsExpiration"],
235
+ "confirmation_id": aws["awsConfirmationId"],
236
+ "labels": cred.get("labels", {}),
237
+ })
238
+ print(f" Refreshed. New expiration: {aws['awsExpiration']}")
239
+
240
+ if failures:
241
+ print(f"\n{failures} credential(s) failed to refresh.", file=sys.stderr)
242
+ sys.exit(1)
243
+
244
+
245
+ def cmd_trigger_aws(args):
246
+ """Test-fire an AWS canary credential."""
247
+ creds = load_credentials()
248
+ aws_creds = [c for c in creds if c["type"] == "aws"]
249
+
250
+ if not aws_creds:
251
+ print("No AWS canary credentials deployed.", file=sys.stderr)
252
+ sys.exit(1)
253
+
254
+ if args.name:
255
+ match = [c for c in aws_creds if c["name"] == args.name]
256
+ if not match:
257
+ print(f"No AWS credential found with name '{args.name}'.",
258
+ file=sys.stderr)
259
+ sys.exit(1)
260
+ cred = match[0]
261
+ else:
262
+ cred = aws_creds[0]
263
+
264
+ profile = cred["profile"]
265
+ print(f"Triggering canary credential (profile={profile})...")
266
+
267
+ try:
268
+ result = subprocess.run(
269
+ ["aws", "sts", "get-caller-identity", "--profile", profile],
270
+ capture_output=True, text=True, timeout=10,
271
+ )
272
+ if result.returncode == 0 and "arn:aws:sts::" in result.stdout:
273
+ print("Canary triggered successfully!")
274
+ print(result.stdout.strip())
275
+ else:
276
+ print("Trigger command ran but output was unexpected:")
277
+ if result.stdout:
278
+ print(result.stdout.strip())
279
+ if result.stderr:
280
+ print(result.stderr.strip(), file=sys.stderr)
281
+ except FileNotFoundError:
282
+ print(
283
+ "Error: 'aws' CLI not found. Install it to use the trigger command.",
284
+ file=sys.stderr,
285
+ )
286
+ sys.exit(1)
287
+ except subprocess.TimeoutExpired:
288
+ print("Error: Trigger command timed out.", file=sys.stderr)
289
+ sys.exit(1)
290
+
291
+
292
+ def cmd_show(args):
293
+ """Display deployed canary credentials."""
294
+ creds = load_credentials()
295
+ if not creds:
296
+ print("No canary credentials deployed.")
297
+ return
298
+
299
+ if args.json_output:
300
+ print(json.dumps(creds, indent=2))
301
+ return
302
+
303
+ now = datetime.now(timezone.utc)
304
+ for c in creds:
305
+ exp_str = c.get("expiration", "unknown")
306
+ status = ""
307
+ if exp_str and exp_str != "unknown":
308
+ try:
309
+ exp_dt = datetime.fromisoformat(exp_str.replace("Z", "+00:00"))
310
+ if exp_dt < now:
311
+ status = " [EXPIRED]"
312
+ elif (exp_dt - now).total_seconds() < 7200:
313
+ status = " [EXPIRING SOON]"
314
+ except ValueError:
315
+ pass
316
+
317
+ print(f" Name: {c['name']}")
318
+ print(f" Type: {c['type']}")
319
+ if c["type"] == "aws":
320
+ print(f" Profile: {c.get('profile', 'n/a')}")
321
+ print(f" Region: {c.get('region', 'n/a')}")
322
+ print(f" Expires: {exp_str}{status}")
323
+ if c.get("labels"):
324
+ print(f" Labels: {c['labels']}")
325
+ print()
326
+
327
+
328
+ def cmd_remove(args):
329
+ """Remove deployed canary credentials."""
330
+ client = _get_client(args)
331
+ creds = load_credentials()
332
+
333
+ if args.name:
334
+ matches = [c for c in creds if c["name"] == args.name]
335
+ else:
336
+ matches = creds
337
+
338
+ if not matches:
339
+ print("No matching credentials found.")
340
+ return
341
+
342
+ for c in matches:
343
+ # expire server-side
344
+ try:
345
+ client.remove_credentials(c["name"], c["type"])
346
+ print(f"Expired '{c['name']}' ({c['type']}) on Tracebit.")
347
+ except TracebitError as e:
348
+ print(f"Warning: Could not expire server-side: {e}", file=sys.stderr)
349
+
350
+ if c["type"] == "aws":
351
+ remove_aws_credentials(c.get("profile", ""))
352
+ print(f"Removed AWS profile '{c.get('profile')}' from ~/.aws/")
353
+ remove_credential(c["name"], c["type"])
354
+ print(f"Removed credential '{c['name']}' ({c['type']}) from state.")
355
+
356
+
357
+ def main():
358
+ parser = argparse.ArgumentParser(
359
+ prog="tracebit",
360
+ description="Manage Tracebit canary credentials",
361
+ )
362
+ parser.add_argument("--token", help="API token (overrides env/config)")
363
+ parser.add_argument("--base-url", help="Override Tracebit API base URL")
364
+ parser.add_argument("--json", dest="json_output", action="store_true",
365
+ help="Output in JSON format where supported")
366
+
367
+ sub = parser.add_subparsers(dest="command")
368
+
369
+ # configure
370
+ p_conf = sub.add_parser("configure", help="Save API token")
371
+ p_conf.add_argument("token_value", nargs="?", help="Token to save")
372
+
373
+ # deploy
374
+ p_deploy = sub.add_parser("deploy", help="Deploy canary credentials")
375
+ deploy_sub = p_deploy.add_subparsers(dest="deploy_type")
376
+
377
+ p_aws = deploy_sub.add_parser("aws", help="Deploy AWS canary credentials")
378
+ p_aws.add_argument("--name", help="Credential name for Tracebit dashboard (default: hostname)")
379
+ p_aws.add_argument("--profile",
380
+ help="AWS profile name — pick something realistic "
381
+ "e.g. 'staging', 'backup', 'legacy-admin' (default: from API)")
382
+ p_aws.add_argument("--region", help="AWS region (default: from API)")
383
+ p_aws.add_argument("--labels", nargs="*", metavar="KEY=VALUE",
384
+ help="Labels as key=value pairs")
385
+ p_aws.add_argument("--force", action="store_true",
386
+ help="Overwrite existing profile")
387
+
388
+ # refresh
389
+ p_refresh = sub.add_parser("refresh", help="Refresh expiring credentials")
390
+ p_refresh.add_argument("--hours", type=float, default=13,
391
+ help="Refresh credentials expiring within this many hours (default: 13)")
392
+
393
+ # trigger
394
+ p_trigger = sub.add_parser("trigger", help="Test-fire a canary credential")
395
+ trigger_sub = p_trigger.add_subparsers(dest="trigger_type")
396
+ p_trig_aws = trigger_sub.add_parser("aws", help="Trigger AWS canary")
397
+ p_trig_aws.add_argument("--name", help="Credential name to trigger")
398
+
399
+ # show
400
+ sub.add_parser("show", help="Show deployed credentials")
401
+
402
+ # remove
403
+ p_remove = sub.add_parser("remove", help="Remove deployed credentials")
404
+ p_remove.add_argument("--name", help="Name of credential to remove (all if omitted)")
405
+
406
+ args = parser.parse_args()
407
+
408
+ if not args.command:
409
+ parser.print_help()
410
+ sys.exit(1)
411
+
412
+ if args.command == "configure":
413
+ cmd_configure(args)
414
+ elif args.command == "deploy":
415
+ if not getattr(args, "deploy_type", None):
416
+ p_deploy.print_help()
417
+ sys.exit(1)
418
+ if args.deploy_type == "aws":
419
+ cmd_deploy_aws(args)
420
+ elif args.command == "refresh":
421
+ cmd_refresh(args)
422
+ elif args.command == "trigger":
423
+ if not getattr(args, "trigger_type", None):
424
+ p_trigger.print_help()
425
+ sys.exit(1)
426
+ if args.trigger_type == "aws":
427
+ cmd_trigger_aws(args)
428
+ elif args.command == "show":
429
+ cmd_show(args)
430
+ elif args.command == "remove":
431
+ cmd_remove(args)
432
+
433
+
434
+ if __name__ == "__main__":
435
+ main()
tracebit/config.py ADDED
@@ -0,0 +1,28 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+
5
+ DEFAULT_BASE_URL = "https://community.tracebit.com"
6
+ CONFIG_DIR = Path.home() / ".config" / "tracebit"
7
+ TOKEN_FILE = CONFIG_DIR / "token"
8
+
9
+
10
+ def get_base_url():
11
+ return os.environ.get("TRACEBIT_URL", DEFAULT_BASE_URL).rstrip("/")
12
+
13
+
14
+ def load_token():
15
+ """Load API token from env var or config file."""
16
+ token = os.environ.get("TRACEBIT_API_TOKEN")
17
+ if token:
18
+ return token.strip()
19
+ if TOKEN_FILE.exists():
20
+ return TOKEN_FILE.read_text().strip()
21
+ return None
22
+
23
+
24
+ def save_token(token):
25
+ """Save API token to config file with restricted permissions."""
26
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
27
+ TOKEN_FILE.write_text(token.strip() + "\n")
28
+ TOKEN_FILE.chmod(0o600)
tracebit/state.py ADDED
@@ -0,0 +1,81 @@
1
+ import json
2
+ import os
3
+ from datetime import datetime, timezone
4
+ from pathlib import Path
5
+
6
+
7
+ STATE_DIR = Path.home() / ".config" / "tracebit"
8
+ STATE_FILE = STATE_DIR / "state.json"
9
+
10
+
11
+ def _load_state():
12
+ if not STATE_FILE.exists():
13
+ return {"credentials": []}
14
+ with open(STATE_FILE) as f:
15
+ return json.load(f)
16
+
17
+
18
+ def _save_state(state):
19
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
20
+ with open(STATE_FILE, "w") as f:
21
+ json.dump(state, f, indent=2)
22
+ os.chmod(STATE_FILE, 0o600)
23
+
24
+
25
+ def save_credential(data):
26
+ """Save or update a deployed credential entry.
27
+
28
+ data should contain: name, type, profile, region, expiration,
29
+ confirmation_id, labels (dict).
30
+ """
31
+ state = _load_state()
32
+ # replace existing entry with same name+type
33
+ state["credentials"] = [
34
+ c for c in state["credentials"]
35
+ if not (c["name"] == data["name"] and c["type"] == data["type"])
36
+ ]
37
+ state["credentials"].append(data)
38
+ _save_state(state)
39
+
40
+
41
+ def load_credentials():
42
+ """Return list of all deployed credentials."""
43
+ return _load_state().get("credentials", [])
44
+
45
+
46
+ def remove_credential(name, cred_type=None):
47
+ """Remove a credential by name (and optionally type)."""
48
+ state = _load_state()
49
+ if cred_type:
50
+ state["credentials"] = [
51
+ c for c in state["credentials"]
52
+ if not (c["name"] == name and c["type"] == cred_type)
53
+ ]
54
+ else:
55
+ state["credentials"] = [
56
+ c for c in state["credentials"] if c["name"] != name
57
+ ]
58
+ _save_state(state)
59
+
60
+
61
+ def get_credential(name, cred_type="aws"):
62
+ """Get a specific credential by name and type."""
63
+ for c in load_credentials():
64
+ if c["name"] == name and c["type"] == cred_type:
65
+ return c
66
+ return None
67
+
68
+
69
+ def get_expiring_credentials(hours=2):
70
+ """Return credentials expiring within the given number of hours."""
71
+ now = datetime.now(timezone.utc)
72
+ expiring = []
73
+ for c in load_credentials():
74
+ exp = c.get("expiration")
75
+ if not exp:
76
+ continue
77
+ exp_dt = datetime.fromisoformat(exp.replace("Z", "+00:00"))
78
+ diff = (exp_dt - now).total_seconds() / 3600
79
+ if diff < hours:
80
+ expiring.append(c)
81
+ return expiring
@@ -0,0 +1,200 @@
1
+ Metadata-Version: 2.4
2
+ Name: tracebit-python
3
+ Version: 0.1.0
4
+ Summary: CLI for managing Tracebit canary credentials on headless servers
5
+ License: Apache-2.0
6
+ Project-URL: Repository, https://github.com/SiteRelEnby/tracebit-python
7
+ Project-URL: Issues, https://github.com/SiteRelEnby/tracebit-python/issues
8
+ Keywords: tracebit,canary,honeypot,aws,credentials,security,detection,deception
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: System Administrators
12
+ Classifier: Operating System :: POSIX
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Security
20
+ Requires-Python: >=3.8
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: requests>=2.20
24
+ Dynamic: license-file
25
+
26
+ # tracebit-python
27
+
28
+ [![PyPI](https://img.shields.io/pypi/v/tracebit-python)](https://pypi.org/project/tracebit-python/)
29
+ [![Python](https://img.shields.io/pypi/pyversions/tracebit-python)](https://pypi.org/project/tracebit-python/)
30
+ [![License](https://img.shields.io/pypi/l/tracebit-python)](LICENSE)
31
+ ![transrights](https://pride-badges.pony.workers.dev/static/v1?label=trans%20rights&stripeWidth=6&stripeColors=5BCEFA,F5A9B8,FFFFFF,F5A9B8,5BCEFA)
32
+ ![enbyware](https://pride-badges.pony.workers.dev/static/v1?label=enbyware&labelColor=%23555&stripeWidth=8&stripeColors=FCF434%2CFFFFFF%2C9C59D1%2C2C2C2C)
33
+ ![pluralmade](https://pride-badges.pony.workers.dev/static/v1?label=plural+made&labelColor=%23555&stripeWidth=8&stripeColors=2e0525%2C553578%2C7675c3%2C89c7b0%2Cf4ecbd)
34
+
35
+ Python CLI for deploying [Tracebit](https://community.tracebit.com/) canary
36
+ credentials on headless servers.
37
+
38
+ Tracebit provides canary tokens — fake credentials that trigger alerts when
39
+ used by an attacker. Their official CLI requires browser-based OAuth, which
40
+ doesn't work on headless servers. This tool uses the Tracebit API directly
41
+ with pre-generated API tokens.
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ pip install tracebit-python
47
+ ```
48
+
49
+ Or from source:
50
+
51
+ ```bash
52
+ git clone https://github.com/SiteRelEnby/tracebit-python
53
+ cd tracebit-python
54
+ pip install -e .
55
+ ```
56
+
57
+ ## Quick Start
58
+
59
+ ### 1. Get an API token
60
+
61
+ Log in to [community.tracebit.com](https://community.tracebit.com/) and
62
+ create an API token from the web UI.
63
+
64
+ ### 2. Configure
65
+
66
+ ```bash
67
+ tracebit configure
68
+ # paste your API token when prompted
69
+ ```
70
+
71
+ Or use an environment variable:
72
+
73
+ ```bash
74
+ export TRACEBIT_API_TOKEN=your-token-here
75
+ ```
76
+
77
+ ### 3. Deploy a canary
78
+
79
+ ```bash
80
+ tracebit deploy aws --profile staging
81
+ ```
82
+
83
+ This issues canary AWS credentials from Tracebit, writes them to
84
+ `~/.aws/credentials` under the specified profile, and confirms the
85
+ deployment. If anyone (or anything) uses these credentials, Tracebit
86
+ fires an alert.
87
+
88
+ ### 4. Test it
89
+
90
+ ```bash
91
+ tracebit trigger aws
92
+ ```
93
+
94
+ Runs `aws sts get-caller-identity` against the canary profile. You should
95
+ see an alert on the Tracebit dashboard within a few minutes.
96
+
97
+ ### 5. Keep credentials fresh
98
+
99
+ Canary credentials expire after ~24 hours. Set up a cron job to refresh them:
100
+
101
+ ```bash
102
+ # crontab -e
103
+ 0 */12 * * * /path/to/tracebit refresh
104
+ ```
105
+
106
+ ## Commands
107
+
108
+ ### `tracebit configure [TOKEN]`
109
+
110
+ Save an API token to `~/.config/tracebit/token`. Reads from argument, stdin,
111
+ or interactive prompt.
112
+
113
+ ### `tracebit deploy aws`
114
+
115
+ Issue and deploy canary AWS credentials.
116
+
117
+ | Option | Default | Description |
118
+ |--------|---------|-------------|
119
+ | `--name` | hostname | Credential name (shown on Tracebit dashboard) |
120
+ | `--profile` | `staging` | AWS profile name in `~/.aws/credentials` |
121
+ | `--region` | from API | AWS region |
122
+ | `--labels` | | Metadata as `key=value` pairs |
123
+ | `--force` | | Replace existing profile (expires old canary first) |
124
+
125
+ Choose a realistic profile name — `staging`, `backup`, `legacy-admin`, etc.
126
+ The whole point is for these to look like real credentials to an attacker.
127
+
128
+ ### `tracebit refresh`
129
+
130
+ Re-issue any credentials expiring within the given threshold. Designed to run
131
+ from cron.
132
+
133
+ | Option | Default | Description |
134
+ |--------|---------|-------------|
135
+ | `--hours` | `13` | Refresh credentials expiring within this many hours |
136
+
137
+ With 24h credentials and a 12h cron, the default of 13 hours ensures every
138
+ cron run refreshes credentials.
139
+
140
+ ### `tracebit trigger aws`
141
+
142
+ Test-fire a canary by calling `aws sts get-caller-identity` with the canary
143
+ profile. Requires the AWS CLI to be installed.
144
+
145
+ | Option | Default | Description |
146
+ |--------|---------|-------------|
147
+ | `--name` | first found | Credential name to trigger |
148
+
149
+ ### `tracebit show`
150
+
151
+ Display deployed canary credentials, their profiles, and expiration status.
152
+
153
+ ### `tracebit remove`
154
+
155
+ Remove canary credentials locally and expire them on Tracebit's server.
156
+
157
+ | Option | Default | Description |
158
+ |--------|---------|-------------|
159
+ | `--name` | all | Name of credential to remove |
160
+
161
+ ## Global Options
162
+
163
+ | Option | Description |
164
+ |--------|-------------|
165
+ | `--token TOKEN` | API token (overrides env var and config file) |
166
+ | `--base-url URL` | Override Tracebit API URL |
167
+ | `--json` | JSON output (where supported) |
168
+
169
+ ## Token Resolution
170
+
171
+ The API token is resolved in this order:
172
+
173
+ 1. `--token` command-line flag
174
+ 2. `TRACEBIT_API_TOKEN` environment variable
175
+ 3. `~/.config/tracebit/token` file
176
+
177
+ ## How It Works
178
+
179
+ 1. **Issue** — requests canary AWS credentials from the Tracebit API
180
+ 2. **Deploy** — writes them to `~/.aws/credentials` and `~/.aws/config`
181
+ under the chosen profile name
182
+ 3. **Confirm** — tells Tracebit the credentials were deployed, so it starts
183
+ monitoring for usage
184
+ 4. **Alert** — any AWS API call using these credentials triggers a detection
185
+ on the Tracebit dashboard
186
+
187
+ The credentials have an explicit deny policy — they can't actually do anything
188
+ in AWS. But any attempt to use them (by an attacker who found them on disk,
189
+ in a config file, etc.) is logged and alerted on.
190
+
191
+ ## File Permissions
192
+
193
+ - `~/.aws/` directory: `0700`
194
+ - `~/.aws/credentials`, `~/.aws/config`: `0600`
195
+ - `~/.config/tracebit/token`: `0600`
196
+ - `~/.config/tracebit/state.json`: `0600`
197
+
198
+ ## License
199
+
200
+ [Apache License 2.0](LICENSE)
@@ -0,0 +1,12 @@
1
+ tracebit/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ tracebit/api.py,sha256=c4JeIqio63BCJYgpMJ4UbrPH3QLk9ntvxRr_kQxKYio,2244
3
+ tracebit/aws.py,sha256=e1v3cFRjCa5dnmC3o9Z4fLTo8snoBxcnXtTfk1KqNXE,2503
4
+ tracebit/cli.py,sha256=-opbLUpX0HsBvZfBWVLBNm7a0SuFZmX8uC8RHDHk-oM,14517
5
+ tracebit/config.py,sha256=4Ij0n9r7vnjBOXtr5ocb67cqh3_XplETEe94TPC3D7w,743
6
+ tracebit/state.py,sha256=8LI8VBOKcoFrOXmWnxuWMldyYy6avOSXzFglnZclxls,2251
7
+ tracebit_python-0.1.0.dist-info/licenses/LICENSE,sha256=v3xdaciFoLUqc5hVeC4fmMEJChMUxbCW6D-bJIPgbW4,10773
8
+ tracebit_python-0.1.0.dist-info/METADATA,sha256=ZCZph8PPtJWqdBCRBw9d6W-YVNXhk0AJkvZzEPYBFHU,6271
9
+ tracebit_python-0.1.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
10
+ tracebit_python-0.1.0.dist-info/entry_points.txt,sha256=mssiXqZ3necMdOeKdjEG2vQvp4u1hlsmuBnhqsl-UyY,47
11
+ tracebit_python-0.1.0.dist-info/top_level.txt,sha256=vxCf1kl0TOzPUugMSloikJ23W9aqNVhyE8dm7T0nQVs,9
12
+ tracebit_python-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tracebit = tracebit.cli:main
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 keyquorum contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1 @@
1
+ tracebit