tailscalekit 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.
- tailscalekit/__init__.py +18 -0
- tailscalekit/__main__.py +3 -0
- tailscalekit/cli.py +240 -0
- tailscalekit/client.py +436 -0
- tailscalekit/lib/tailscale.sh +62 -0
- tailscalekit/pod/bootstrap.sh +75 -0
- tailscalekit-0.1.0.dist-info/METADATA +189 -0
- tailscalekit-0.1.0.dist-info/RECORD +12 -0
- tailscalekit-0.1.0.dist-info/WHEEL +5 -0
- tailscalekit-0.1.0.dist-info/entry_points.txt +2 -0
- tailscalekit-0.1.0.dist-info/licenses/LICENSE +21 -0
- tailscalekit-0.1.0.dist-info/top_level.txt +1 -0
tailscalekit/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""tailscalekit: dependency-free Tailscale API control for Python, Bash and the CLI."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .client import ( # noqa: E402
|
|
6
|
+
Tailscale,
|
|
7
|
+
TailscaleError,
|
|
8
|
+
TailscaleTimeoutError,
|
|
9
|
+
device_ip,
|
|
10
|
+
policy_allows_all,
|
|
11
|
+
public_device,
|
|
12
|
+
redact,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Tailscale", "TailscaleError", "TailscaleTimeoutError",
|
|
17
|
+
"device_ip", "policy_allows_all", "public_device", "redact", "__version__",
|
|
18
|
+
]
|
tailscalekit/__main__.py
ADDED
tailscalekit/cli.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
from . import Tailscale, TailscaleError, TailscaleTimeoutError, __version__, device_ip, public_device
|
|
11
|
+
from .client import policy_allows_all, redact
|
|
12
|
+
|
|
13
|
+
_LIB = Path(__file__).resolve().parent / "lib" / "tailscale.sh"
|
|
14
|
+
_POD = Path(__file__).resolve().parent / "pod" / "bootstrap.sh"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _secrets() -> tuple:
|
|
18
|
+
return (os.environ.get("TS_API_KEY"), os.environ.get("TS_OAUTH_CLIENT_SECRET"))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _error(message: object) -> None:
|
|
22
|
+
print("tailscalekit: " + " ".join(redact(str(message), *_secrets()).split()), file=sys.stderr)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _Parser(argparse.ArgumentParser):
|
|
26
|
+
def error(self, message: str) -> None:
|
|
27
|
+
_error(message)
|
|
28
|
+
raise SystemExit(2)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _emit(obj: object) -> None:
|
|
32
|
+
print(redact(json.dumps(obj, indent=2), *_secrets()))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _lookup(ts: Tailscale, target: str) -> Optional[dict]:
|
|
36
|
+
"""A device by hostname, falling back to a device/node ID."""
|
|
37
|
+
device = ts.find_device(target)
|
|
38
|
+
if device is None and target.replace("-", "").isalnum():
|
|
39
|
+
device = ts.get_device(target)
|
|
40
|
+
return device
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _cmd_devices(args: argparse.Namespace) -> int:
|
|
44
|
+
devices = Tailscale().list_devices()
|
|
45
|
+
_emit(devices if args.all_fields else [public_device(d) for d in devices])
|
|
46
|
+
return 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _cmd_device(args: argparse.Namespace) -> int:
|
|
50
|
+
device = _lookup(Tailscale(), args.target)
|
|
51
|
+
if device is None:
|
|
52
|
+
_emit({"detail": "device not found"})
|
|
53
|
+
return 3
|
|
54
|
+
_emit(device if args.all_fields else public_device(device))
|
|
55
|
+
return 0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _cmd_ip(args: argparse.Namespace) -> int:
|
|
59
|
+
device = _lookup(Tailscale(), args.target)
|
|
60
|
+
address = device_ip(device, 6 if args.ipv6 else 4) if device else None
|
|
61
|
+
if not address:
|
|
62
|
+
return 3
|
|
63
|
+
print(address)
|
|
64
|
+
return 0
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _cmd_authkey(args: argparse.Namespace) -> int:
|
|
68
|
+
key = Tailscale().create_auth_key(
|
|
69
|
+
reusable=args.reusable, ephemeral=args.ephemeral, preauthorized=not args.no_preauthorized,
|
|
70
|
+
tags=args.tag or None, expiry_seconds=args.expiry, description=args.description,
|
|
71
|
+
)
|
|
72
|
+
if args.json:
|
|
73
|
+
# Deliberately unredacted: handing the key to a machine is the point of this command.
|
|
74
|
+
print(json.dumps({"id": key["id"], "key": key["key"], "expires": key.get("expires")}, indent=2))
|
|
75
|
+
else:
|
|
76
|
+
print(key["key"])
|
|
77
|
+
return 0
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _cmd_keys(args: argparse.Namespace) -> int:
|
|
81
|
+
_emit(Tailscale().list_keys())
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _cmd_revoke(args: argparse.Namespace) -> int:
|
|
86
|
+
ts = Tailscale()
|
|
87
|
+
status = ts.revoke_key(args.key_id)
|
|
88
|
+
print(status)
|
|
89
|
+
if status != 404 and not ts.key_revoked(args.key_id):
|
|
90
|
+
_error(f"key {args.key_id} still valid after DELETE")
|
|
91
|
+
return 1
|
|
92
|
+
return 0
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _cmd_delete(args: argparse.Namespace) -> int:
|
|
96
|
+
ts = Tailscale()
|
|
97
|
+
device = _lookup(ts, args.target)
|
|
98
|
+
if device is None:
|
|
99
|
+
print(404)
|
|
100
|
+
return 3
|
|
101
|
+
print(ts.delete_device(str(device.get("id") or device.get("nodeId"))))
|
|
102
|
+
return 0
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _cmd_wait_online(args: argparse.Namespace) -> int:
|
|
106
|
+
try:
|
|
107
|
+
device = Tailscale().wait_online(args.hostname, timeout=args.timeout,
|
|
108
|
+
created_after=args.after, tag=args.tag)
|
|
109
|
+
except TailscaleTimeoutError as error:
|
|
110
|
+
_error(error)
|
|
111
|
+
return 3
|
|
112
|
+
if args.json:
|
|
113
|
+
_emit(public_device(device))
|
|
114
|
+
else:
|
|
115
|
+
print(device_ip(device))
|
|
116
|
+
return 0
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _cmd_policy_check(args: argparse.Namespace) -> int:
|
|
120
|
+
allows_all = policy_allows_all(Tailscale().get_policy())
|
|
121
|
+
print("default-allow" if allows_all else "restricted")
|
|
122
|
+
return 0
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _cmd_bash_lib(args: argparse.Namespace) -> int:
|
|
126
|
+
print(_LIB)
|
|
127
|
+
return 0
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _cmd_pod_bootstrap(args: argparse.Namespace) -> int:
|
|
131
|
+
print(_POD)
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _cmd_version(args: argparse.Namespace) -> int:
|
|
136
|
+
print(f"tailscalekit {__version__}")
|
|
137
|
+
return 0
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
_COMMANDS = {
|
|
141
|
+
"devices": _cmd_devices, "device": _cmd_device, "ip": _cmd_ip,
|
|
142
|
+
"authkey": _cmd_authkey, "keys": _cmd_keys, "revoke": _cmd_revoke,
|
|
143
|
+
"delete": _cmd_delete, "wait-online": _cmd_wait_online, "policy-check": _cmd_policy_check,
|
|
144
|
+
"bash-lib": _cmd_bash_lib, "pod-bootstrap": _cmd_pod_bootstrap, "version": _cmd_version,
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
_HELP = {
|
|
148
|
+
"devices": "list tailnet devices as JSON (node/machine keys hidden unless --all-fields)",
|
|
149
|
+
"device": "print one device (by hostname or ID) as JSON; exit 3 if not found",
|
|
150
|
+
"ip": "print a device's tailnet IP (by hostname or ID); exit 3 if not found",
|
|
151
|
+
"authkey": "mint a device auth key and print it (single-use, ephemeral, pre-approved, 15 min by default)",
|
|
152
|
+
"keys": "list the tailnet's keys as JSON (never their values)",
|
|
153
|
+
"revoke": "revoke a key by ID, print the HTTP status, and verify it is invalid",
|
|
154
|
+
"delete": "remove a device (by hostname or ID) and print the HTTP status",
|
|
155
|
+
"wait-online": "wait for a device to connect and print its IP; exit 3 on timeout",
|
|
156
|
+
"policy-check": "print default-allow or restricted for the tailnet policy",
|
|
157
|
+
"bash-lib": "print the path to the Bash library",
|
|
158
|
+
"pod-bootstrap": "print the path to the pod-side join script",
|
|
159
|
+
"version": "print the tailscalekit version",
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _positive(text: str) -> float:
|
|
164
|
+
try:
|
|
165
|
+
value = float(text)
|
|
166
|
+
except ValueError:
|
|
167
|
+
raise argparse.ArgumentTypeError(f"not a number: {text!r}") from None
|
|
168
|
+
if not 0 < value < float("inf"):
|
|
169
|
+
raise argparse.ArgumentTypeError("must be greater than zero")
|
|
170
|
+
return value
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _parser() -> argparse.ArgumentParser:
|
|
174
|
+
parser = _Parser(
|
|
175
|
+
prog="tailscalekit",
|
|
176
|
+
description=("Manage a tailnet using TS_API_KEY, or TS_OAUTH_CLIENT_ID + "
|
|
177
|
+
"TS_OAUTH_CLIENT_SECRET. Exit codes: 0 ok, 1 error, 2 usage, 3 not found / timeout."),
|
|
178
|
+
)
|
|
179
|
+
parser.add_argument("--version", action="version", version=f"tailscalekit {__version__}")
|
|
180
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
181
|
+
for name in _COMMANDS:
|
|
182
|
+
command = commands.add_parser(name, help=_HELP[name], description=_HELP[name])
|
|
183
|
+
if name in {"device", "ip", "delete"}:
|
|
184
|
+
command.add_argument("target", help="device hostname or ID")
|
|
185
|
+
if name in {"devices", "device"}:
|
|
186
|
+
command.add_argument("--all-fields", action="store_true",
|
|
187
|
+
help="include node, machine and tailnet-lock keys")
|
|
188
|
+
if name == "ip":
|
|
189
|
+
command.add_argument("--ipv6", action="store_true", help="print the IPv6 address")
|
|
190
|
+
if name == "revoke":
|
|
191
|
+
command.add_argument("key_id", help="key ID (not the key itself)")
|
|
192
|
+
if name == "authkey":
|
|
193
|
+
command.add_argument("--tag", action="append", metavar="tag:NAME",
|
|
194
|
+
help="tag for devices using this key; repeatable (required with OAuth)")
|
|
195
|
+
command.add_argument("--reusable", action="store_true", help="allow more than one use")
|
|
196
|
+
command.add_argument("--ephemeral", action=argparse.BooleanOptionalAction, default=True,
|
|
197
|
+
help="remove the device when it goes offline (default: on)")
|
|
198
|
+
command.add_argument("--no-preauthorized", action="store_true",
|
|
199
|
+
help="require admin approval for devices using this key")
|
|
200
|
+
command.add_argument("--expiry", type=int, default=900,
|
|
201
|
+
help="key lifetime in seconds (default: %(default)s)")
|
|
202
|
+
command.add_argument("--description", default="tailscalekit",
|
|
203
|
+
help="shown in the admin console (max 50 chars)")
|
|
204
|
+
command.add_argument("--json", action="store_true", help='print {"id","key","expires"}')
|
|
205
|
+
if name == "wait-online":
|
|
206
|
+
command.add_argument("hostname")
|
|
207
|
+
command.add_argument("--timeout", type=_positive, default=240,
|
|
208
|
+
help="maximum wait in seconds (default: %(default)s)")
|
|
209
|
+
command.add_argument("--after", help="only devices created after this ISO-8601 time")
|
|
210
|
+
command.add_argument("--tag", help="only devices carrying this tag")
|
|
211
|
+
command.add_argument("--json", action="store_true", help="print the device JSON")
|
|
212
|
+
return parser
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def main(argv: Optional[list[str]] = None) -> int:
|
|
216
|
+
try:
|
|
217
|
+
try:
|
|
218
|
+
args = _parser().parse_args(argv)
|
|
219
|
+
except SystemExit as error:
|
|
220
|
+
if isinstance(error.code, int):
|
|
221
|
+
return error.code
|
|
222
|
+
return 0 if error.code is None else 2
|
|
223
|
+
code = _COMMANDS[args.command](args)
|
|
224
|
+
sys.stdout.flush()
|
|
225
|
+
return code
|
|
226
|
+
except BrokenPipeError:
|
|
227
|
+
try:
|
|
228
|
+
sys.stdout = open(os.devnull, "w", encoding="utf-8")
|
|
229
|
+
except OSError:
|
|
230
|
+
pass
|
|
231
|
+
return 1
|
|
232
|
+
except KeyboardInterrupt:
|
|
233
|
+
return 130
|
|
234
|
+
except (TailscaleError, ValueError, TypeError, OSError) as error:
|
|
235
|
+
_error(error)
|
|
236
|
+
return 1
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
if __name__ == "__main__":
|
|
240
|
+
raise SystemExit(main())
|
tailscalekit/client.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
"""Standard-library Tailscale API client: devices, auth keys, waiting for a node to come online.
|
|
2
|
+
|
|
3
|
+
Live-verified shapes (2026-12-01):
|
|
4
|
+
GET /tailnet/-/devices -> {"devices": [{"addresses", "id", "nodeId", "name", "hostname",
|
|
5
|
+
"connectedToControl", "lastSeen", "authorized", ...}]}
|
|
6
|
+
POST /tailnet/-/keys -> {"id", "key": "tskey-auth-…", "keyType": "auth", "expirySeconds",
|
|
7
|
+
"created", "expires", "capabilities", "description", "userId"}
|
|
8
|
+
DELETE /tailnet/-/keys/{id} -> 200, and again 200; afterwards GET still returns 200 with
|
|
9
|
+
"revoked": <ts>, "invalid": true, and the key leaves the list.
|
|
10
|
+
Errors are {"message": "..."}; a bad token is 401 "API token invalid".
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import http.client
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import time
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.parse
|
|
21
|
+
import urllib.request
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
from typing import Iterable, Optional, Union
|
|
24
|
+
|
|
25
|
+
from . import __version__
|
|
26
|
+
|
|
27
|
+
DEFAULT_API_URL = "https://api.tailscale.com/api/v2"
|
|
28
|
+
_SECRET_RE = re.compile(r"tskey-[A-Za-z]+-[A-Za-z0-9_-]+")
|
|
29
|
+
_HIDDEN_DEVICE_FIELDS = ("machineKey", "nodeKey", "tailnetLockKey")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TailscaleError(RuntimeError):
|
|
33
|
+
def __init__(self, message: str, status: Optional[int] = None, body: str = "") -> None:
|
|
34
|
+
super().__init__(message)
|
|
35
|
+
self.status = status
|
|
36
|
+
self.body = body[:500]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class TailscaleTimeoutError(TailscaleError):
|
|
40
|
+
"""Raised by wait_online when the deadline passes; status is always None."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, message: str) -> None:
|
|
43
|
+
super().__init__(message)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def redact(text: str, *secrets: Optional[str]) -> str:
|
|
47
|
+
"""Remove every tskey-* token plus any explicitly given secret from text."""
|
|
48
|
+
for secret in secrets:
|
|
49
|
+
if secret and len(secret) >= 8:
|
|
50
|
+
text = text.replace(secret, "[REDACTED]")
|
|
51
|
+
return _SECRET_RE.sub("[REDACTED]", text)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def device_ip(device: object, version: int = 4) -> Optional[str]:
|
|
55
|
+
"""The device's tailnet address (100.x for IPv4, fd7a: for IPv6), or None."""
|
|
56
|
+
if not isinstance(device, dict) or not isinstance(device.get("addresses"), list):
|
|
57
|
+
return None
|
|
58
|
+
for address in device["addresses"]:
|
|
59
|
+
if not isinstance(address, str):
|
|
60
|
+
continue
|
|
61
|
+
if version == 4 and address.count(".") == 3:
|
|
62
|
+
return address
|
|
63
|
+
if version == 6 and ":" in address:
|
|
64
|
+
return address
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def public_device(device: dict) -> dict:
|
|
69
|
+
"""A copy of a device without node/machine/lock keys (safe to print)."""
|
|
70
|
+
return {k: v for k, v in device.items() if k not in _HIDDEN_DEVICE_FIELDS}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _parse_time(value: object) -> Optional[datetime]:
|
|
74
|
+
if isinstance(value, datetime):
|
|
75
|
+
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
|
76
|
+
if not isinstance(value, str) or not value:
|
|
77
|
+
return None
|
|
78
|
+
text = value.strip()
|
|
79
|
+
if text.endswith("Z"):
|
|
80
|
+
text = text[:-1] + "+00:00"
|
|
81
|
+
try:
|
|
82
|
+
parsed = datetime.fromisoformat(text)
|
|
83
|
+
except ValueError:
|
|
84
|
+
return None
|
|
85
|
+
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def policy_allows_all(policy: object) -> bool:
|
|
89
|
+
"""True when a tailnet policy (parsed JSON) lets any source reach any destination.
|
|
90
|
+
|
|
91
|
+
Looks for the default-allow ACL rule ({"action":"accept","src":["*"],"dst":["*:*"]})
|
|
92
|
+
and the equivalent grant ({"src":["*"],"dst":["*"],"ip":["*"]}).
|
|
93
|
+
"""
|
|
94
|
+
if not isinstance(policy, dict):
|
|
95
|
+
return False
|
|
96
|
+
for rule in policy.get("acls") or []:
|
|
97
|
+
if (isinstance(rule, dict) and rule.get("action") == "accept"
|
|
98
|
+
and "*" in (rule.get("src") or []) and "*:*" in (rule.get("dst") or [])):
|
|
99
|
+
return True
|
|
100
|
+
for grant in policy.get("grants") or []:
|
|
101
|
+
if (isinstance(grant, dict) and "*" in (grant.get("src") or [])
|
|
102
|
+
and "*" in (grant.get("dst") or []) and "*" in (grant.get("ip") or [])):
|
|
103
|
+
return True
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _error_message(method: str, path: str, status: int, body: str, reason: object = "") -> str:
|
|
108
|
+
prefix = f"{method} {path} → HTTP {status}"
|
|
109
|
+
try:
|
|
110
|
+
data = json.loads(body)
|
|
111
|
+
except (ValueError, TypeError):
|
|
112
|
+
data = None
|
|
113
|
+
if isinstance(data, dict) and isinstance(data.get("message"), str) and data["message"]:
|
|
114
|
+
return f"{prefix}: {data['message']}"
|
|
115
|
+
detail = " ".join((body or str(reason or "")).split())[:200]
|
|
116
|
+
return f"{prefix}: {detail}" if detail else prefix
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _is_transient(error: TailscaleError) -> bool:
|
|
120
|
+
return error.status is None or error.status == 429 or error.status >= 500
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _positive_seconds(value: Union[int, float], name: str) -> None:
|
|
124
|
+
if (isinstance(value, bool) or not isinstance(value, (int, float))
|
|
125
|
+
or not 0 < value < float("inf")):
|
|
126
|
+
raise ValueError(f"{name} must be a finite number greater than zero")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _segment(value: object, name: str) -> str:
|
|
130
|
+
if not isinstance(value, str) or not value:
|
|
131
|
+
raise ValueError(f"{name} must be a non-empty str")
|
|
132
|
+
return urllib.parse.quote(value, safe="")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class Tailscale:
|
|
136
|
+
"""Tailscale API v2 client.
|
|
137
|
+
|
|
138
|
+
Credentials, in order: ``api_key=`` / ``oauth_client_id=`` + ``oauth_client_secret=``
|
|
139
|
+
arguments; else the ``TS_OAUTH_CLIENT_ID`` + ``TS_OAUTH_CLIENT_SECRET`` environment pair
|
|
140
|
+
(recommended: scoped, non-expiring); else ``TS_API_KEY`` (a personal key: full admin,
|
|
141
|
+
expires within 90 days). ``tailnet`` defaults to ``TS_TAILNET`` or ``"-"`` (the
|
|
142
|
+
credential's own tailnet).
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
def __init__(self, api_key: Optional[str] = None, *,
|
|
146
|
+
oauth_client_id: Optional[str] = None, oauth_client_secret: Optional[str] = None,
|
|
147
|
+
tailnet: Optional[str] = None, base_url: Optional[str] = None,
|
|
148
|
+
timeout: float = 30) -> None:
|
|
149
|
+
_positive_seconds(timeout, "timeout")
|
|
150
|
+
if api_key is None and oauth_client_id is None and oauth_client_secret is None:
|
|
151
|
+
oauth_client_id = os.environ.get("TS_OAUTH_CLIENT_ID") or None
|
|
152
|
+
oauth_client_secret = os.environ.get("TS_OAUTH_CLIENT_SECRET") or None
|
|
153
|
+
if not (oauth_client_id and oauth_client_secret):
|
|
154
|
+
oauth_client_id = oauth_client_secret = None
|
|
155
|
+
api_key = os.environ.get("TS_API_KEY") or None
|
|
156
|
+
if api_key is not None and not isinstance(api_key, str):
|
|
157
|
+
raise TypeError("api_key must be a str")
|
|
158
|
+
if (oauth_client_id is None) != (oauth_client_secret is None):
|
|
159
|
+
raise TailscaleError("an OAuth client needs both a client id and a client secret")
|
|
160
|
+
if not api_key and not oauth_client_id:
|
|
161
|
+
raise TailscaleError(
|
|
162
|
+
"no Tailscale credential: set TS_API_KEY, or TS_OAUTH_CLIENT_ID and "
|
|
163
|
+
"TS_OAUTH_CLIENT_SECRET"
|
|
164
|
+
)
|
|
165
|
+
url = base_url if base_url is not None else (os.environ.get("TS_API_URL") or DEFAULT_API_URL)
|
|
166
|
+
if not isinstance(url, str) or not url.rstrip("/"):
|
|
167
|
+
raise ValueError("base_url must be a non-empty str")
|
|
168
|
+
net = tailnet if tailnet is not None else (os.environ.get("TS_TAILNET") or "-")
|
|
169
|
+
self._api_key = api_key or None
|
|
170
|
+
self._client_id = oauth_client_id
|
|
171
|
+
self._client_secret = oauth_client_secret
|
|
172
|
+
self._token: Optional[str] = None
|
|
173
|
+
self._token_expires = 0.0
|
|
174
|
+
self.base_url = url.rstrip("/")
|
|
175
|
+
self.tailnet = _segment(net, "tailnet")
|
|
176
|
+
self.timeout = timeout
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def uses_oauth(self) -> bool:
|
|
180
|
+
return self._client_id is not None
|
|
181
|
+
|
|
182
|
+
def __repr__(self) -> str:
|
|
183
|
+
kind = "oauth" if self.uses_oauth else "api_key"
|
|
184
|
+
return f"Tailscale(base_url={self.base_url!r}, tailnet={self.tailnet!r}, auth={kind!r})"
|
|
185
|
+
|
|
186
|
+
def _redact(self, text: str) -> str:
|
|
187
|
+
return redact(text, self._api_key, self._client_secret, self._token)
|
|
188
|
+
|
|
189
|
+
# ----- transport -------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
def _bearer(self) -> str:
|
|
192
|
+
if self._api_key:
|
|
193
|
+
return self._api_key
|
|
194
|
+
if self._token and time.monotonic() < self._token_expires:
|
|
195
|
+
return self._token
|
|
196
|
+
form = urllib.parse.urlencode({
|
|
197
|
+
"client_id": self._client_id, "client_secret": self._client_secret,
|
|
198
|
+
}).encode("ascii")
|
|
199
|
+
status, data = self._send("POST", "/oauth/token", form,
|
|
200
|
+
"application/x-www-form-urlencoded", auth=False)
|
|
201
|
+
token = data.get("access_token") if isinstance(data, dict) else None
|
|
202
|
+
if not isinstance(token, str) or not token:
|
|
203
|
+
raise TailscaleError(self._redact(f"POST /oauth/token → HTTP {status}: no access_token"),
|
|
204
|
+
status=status)
|
|
205
|
+
lifetime = data.get("expires_in") if isinstance(data.get("expires_in"), (int, float)) else 3600
|
|
206
|
+
self._token = token
|
|
207
|
+
self._token_expires = time.monotonic() + max(lifetime - 60, 30)
|
|
208
|
+
return token
|
|
209
|
+
|
|
210
|
+
def _send(self, method: str, path: str, payload: Optional[bytes], content_type: str,
|
|
211
|
+
auth: bool = True) -> tuple[int, object]:
|
|
212
|
+
headers = {"Accept": "application/json",
|
|
213
|
+
"User-Agent": f"tailscalekit/{__version__} (+https://github.com/kcherry497/tailscale-kit)"}
|
|
214
|
+
if payload is not None:
|
|
215
|
+
headers["Content-Type"] = content_type
|
|
216
|
+
if auth:
|
|
217
|
+
headers["Authorization"] = "Bearer " + self._bearer()
|
|
218
|
+
request = urllib.request.Request(self.base_url + path, data=payload, method=method,
|
|
219
|
+
headers=headers)
|
|
220
|
+
try:
|
|
221
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
222
|
+
status = getattr(response, "status", None)
|
|
223
|
+
if status is None:
|
|
224
|
+
status = response.getcode()
|
|
225
|
+
raw = response.read()
|
|
226
|
+
except urllib.error.HTTPError as error:
|
|
227
|
+
try:
|
|
228
|
+
text = error.read().decode("utf-8", errors="replace")
|
|
229
|
+
except Exception:
|
|
230
|
+
text = ""
|
|
231
|
+
finally:
|
|
232
|
+
error.close()
|
|
233
|
+
if error.code == 401 and self._token:
|
|
234
|
+
self._token = None # force a fresh OAuth token next time
|
|
235
|
+
raise TailscaleError(
|
|
236
|
+
self._redact(_error_message(method, path, error.code, text, error.reason)),
|
|
237
|
+
status=error.code, body=self._redact(text),
|
|
238
|
+
) from None
|
|
239
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError,
|
|
240
|
+
OSError, http.client.HTTPException) as error:
|
|
241
|
+
raise TailscaleError(self._redact(f"{method} {path} → {type(error).__name__}: {error}")) from None
|
|
242
|
+
if not raw:
|
|
243
|
+
return status, {}
|
|
244
|
+
text = raw.decode("utf-8", errors="replace")
|
|
245
|
+
try:
|
|
246
|
+
return status, json.loads(text)
|
|
247
|
+
except ValueError:
|
|
248
|
+
raise TailscaleError(self._redact(f"{method} {path} → HTTP {status}: invalid JSON response"),
|
|
249
|
+
status=status, body=self._redact(text)) from None
|
|
250
|
+
|
|
251
|
+
def _request(self, method: str, path: str, body: Optional[dict] = None) -> tuple[int, object]:
|
|
252
|
+
try:
|
|
253
|
+
payload = json.dumps(body).encode("utf-8") if body is not None else None
|
|
254
|
+
except (TypeError, ValueError) as error:
|
|
255
|
+
raise ValueError(f"{method} {path}: invalid request body ({error})") from None
|
|
256
|
+
return self._send(method, path, payload, "application/json")
|
|
257
|
+
|
|
258
|
+
def _shape_error(self, method: str, path: str, status: int, data: object,
|
|
259
|
+
expected: str) -> TailscaleError:
|
|
260
|
+
return TailscaleError(self._redact(f"{method} {path} → HTTP {status}: expected {expected}"),
|
|
261
|
+
status=status, body=self._redact(repr(data)))
|
|
262
|
+
|
|
263
|
+
# ----- devices ---------------------------------------------------------------------
|
|
264
|
+
|
|
265
|
+
def list_devices(self) -> list[dict]:
|
|
266
|
+
path = f"/tailnet/{self.tailnet}/devices"
|
|
267
|
+
status, data = self._request("GET", path)
|
|
268
|
+
devices = data.get("devices") if isinstance(data, dict) else None
|
|
269
|
+
if not isinstance(devices, list) or any(not isinstance(d, dict) for d in devices):
|
|
270
|
+
raise self._shape_error("GET", path, status, data, "a dict with a devices list of dicts")
|
|
271
|
+
return devices
|
|
272
|
+
|
|
273
|
+
def get_device(self, device_id: str) -> Optional[dict]:
|
|
274
|
+
path = "/device/" + _segment(device_id, "device_id")
|
|
275
|
+
try:
|
|
276
|
+
status, data = self._request("GET", path)
|
|
277
|
+
except TailscaleError as error:
|
|
278
|
+
if error.status == 404:
|
|
279
|
+
return None
|
|
280
|
+
raise
|
|
281
|
+
if not isinstance(data, dict):
|
|
282
|
+
raise self._shape_error("GET", path, status, data, "a device dict")
|
|
283
|
+
return data
|
|
284
|
+
|
|
285
|
+
def find_device(self, hostname: str, *, created_after: object = None,
|
|
286
|
+
tag: Optional[str] = None) -> Optional[dict]:
|
|
287
|
+
"""First device whose hostname matches (case-insensitive), optionally created after a
|
|
288
|
+
time and carrying a tag. Tailscale may append "-1", "-2" to a duplicate hostname;
|
|
289
|
+
those count as matches too, newest first."""
|
|
290
|
+
if not isinstance(hostname, str) or not hostname:
|
|
291
|
+
raise ValueError("hostname must be a non-empty str")
|
|
292
|
+
after = _parse_time(created_after) if created_after is not None else None
|
|
293
|
+
if created_after is not None and after is None:
|
|
294
|
+
raise ValueError("created_after must be a datetime or an ISO-8601 string")
|
|
295
|
+
wanted = hostname.lower()
|
|
296
|
+
dup = re.compile(re.escape(wanted) + r"-\d+$")
|
|
297
|
+
matches = []
|
|
298
|
+
for device in self.list_devices():
|
|
299
|
+
name = str(device.get("hostname") or "").lower()
|
|
300
|
+
if name != wanted and not dup.match(name):
|
|
301
|
+
continue
|
|
302
|
+
if tag is not None and tag not in (device.get("tags") or []):
|
|
303
|
+
continue
|
|
304
|
+
created = _parse_time(device.get("created"))
|
|
305
|
+
if after is not None and (created is None or created <= after):
|
|
306
|
+
continue
|
|
307
|
+
matches.append((created or datetime.min.replace(tzinfo=timezone.utc), device))
|
|
308
|
+
if not matches:
|
|
309
|
+
return None
|
|
310
|
+
exact = [m for m in matches if str(m[1].get("hostname") or "").lower() == wanted]
|
|
311
|
+
pool = exact or matches
|
|
312
|
+
return max(pool, key=lambda m: m[0])[1]
|
|
313
|
+
|
|
314
|
+
def delete_device(self, device_id: str) -> int:
|
|
315
|
+
path = "/device/" + _segment(device_id, "device_id")
|
|
316
|
+
try:
|
|
317
|
+
status, _ = self._request("DELETE", path)
|
|
318
|
+
except TailscaleError as error:
|
|
319
|
+
if error.status == 404:
|
|
320
|
+
return 404
|
|
321
|
+
raise
|
|
322
|
+
return status
|
|
323
|
+
|
|
324
|
+
# ----- auth keys -------------------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
def create_auth_key(self, *, reusable: bool = False, ephemeral: bool = True,
|
|
327
|
+
preauthorized: bool = True, tags: Optional[Iterable[str]] = None,
|
|
328
|
+
expiry_seconds: int = 900, description: str = "tailscalekit") -> dict:
|
|
329
|
+
"""Mint a device auth key. Defaults are the safe ones for handing to a machine you do
|
|
330
|
+
not fully trust: single-use, ephemeral, pre-approved, 15-minute expiry.
|
|
331
|
+
|
|
332
|
+
Returns the API response: {"id", "key", "expires", ...}. The ``key`` value is the only
|
|
333
|
+
copy; nothing in tailscalekit logs or prints it except where you ask for it.
|
|
334
|
+
"""
|
|
335
|
+
for name, flag in (("reusable", reusable), ("ephemeral", ephemeral),
|
|
336
|
+
("preauthorized", preauthorized)):
|
|
337
|
+
if not isinstance(flag, bool):
|
|
338
|
+
raise TypeError(f"{name} must be a bool")
|
|
339
|
+
tag_list = list(tags) if tags is not None else []
|
|
340
|
+
if any(not isinstance(t, str) or not t.startswith("tag:") or len(t) < 5 for t in tag_list):
|
|
341
|
+
raise ValueError('tags must look like "tag:name"')
|
|
342
|
+
if self.uses_oauth and not tag_list:
|
|
343
|
+
raise ValueError("keys minted with an OAuth client must carry at least one tag")
|
|
344
|
+
if (isinstance(expiry_seconds, bool) or not isinstance(expiry_seconds, int)
|
|
345
|
+
or not 1 <= expiry_seconds <= 90 * 24 * 3600):
|
|
346
|
+
raise ValueError("expiry_seconds must be an int between 1 and 7776000 (90 days)")
|
|
347
|
+
if not isinstance(description, str) or len(description) > 50:
|
|
348
|
+
raise ValueError("description must be a str of at most 50 characters")
|
|
349
|
+
create = {"reusable": reusable, "ephemeral": ephemeral, "preauthorized": preauthorized}
|
|
350
|
+
if tag_list:
|
|
351
|
+
create["tags"] = tag_list
|
|
352
|
+
body = {"capabilities": {"devices": {"create": create}},
|
|
353
|
+
"expirySeconds": expiry_seconds, "description": description}
|
|
354
|
+
path = f"/tailnet/{self.tailnet}/keys"
|
|
355
|
+
status, data = self._request("POST", path, body)
|
|
356
|
+
if (not isinstance(data, dict) or not isinstance(data.get("id"), str) or not data["id"]
|
|
357
|
+
or not isinstance(data.get("key"), str) or not data["key"].startswith("tskey-")):
|
|
358
|
+
raise TailscaleError(f"POST {path} → HTTP {status}: response has no key id/value",
|
|
359
|
+
status=status)
|
|
360
|
+
return data
|
|
361
|
+
|
|
362
|
+
def list_keys(self) -> list[dict]:
|
|
363
|
+
path = f"/tailnet/{self.tailnet}/keys"
|
|
364
|
+
status, data = self._request("GET", path)
|
|
365
|
+
keys = data.get("keys") if isinstance(data, dict) else None
|
|
366
|
+
if not isinstance(keys, list) or any(not isinstance(k, dict) for k in keys):
|
|
367
|
+
raise self._shape_error("GET", path, status, data, "a dict with a keys list of dicts")
|
|
368
|
+
return keys
|
|
369
|
+
|
|
370
|
+
def get_key(self, key_id: str) -> Optional[dict]:
|
|
371
|
+
path = f"/tailnet/{self.tailnet}/keys/" + _segment(key_id, "key_id")
|
|
372
|
+
try:
|
|
373
|
+
status, data = self._request("GET", path)
|
|
374
|
+
except TailscaleError as error:
|
|
375
|
+
if error.status == 404:
|
|
376
|
+
return None
|
|
377
|
+
raise
|
|
378
|
+
if not isinstance(data, dict):
|
|
379
|
+
raise self._shape_error("GET", path, status, data, "a key dict")
|
|
380
|
+
data.pop("key", None) # never carry a secret around by accident
|
|
381
|
+
return data
|
|
382
|
+
|
|
383
|
+
def revoke_key(self, key_id: str) -> int:
|
|
384
|
+
path = f"/tailnet/{self.tailnet}/keys/" + _segment(key_id, "key_id")
|
|
385
|
+
try:
|
|
386
|
+
status, _ = self._request("DELETE", path)
|
|
387
|
+
except TailscaleError as error:
|
|
388
|
+
if error.status == 404:
|
|
389
|
+
return 404
|
|
390
|
+
raise
|
|
391
|
+
return status
|
|
392
|
+
|
|
393
|
+
def key_revoked(self, key_id: str) -> bool:
|
|
394
|
+
"""True when the key can no longer be used. The API keeps revoked keys readable
|
|
395
|
+
(HTTP 200 with "invalid": true and a "revoked" timestamp), so status alone proves nothing."""
|
|
396
|
+
key = self.get_key(key_id)
|
|
397
|
+
if key is None:
|
|
398
|
+
return True
|
|
399
|
+
return key.get("invalid") is True or bool(key.get("revoked"))
|
|
400
|
+
|
|
401
|
+
# ----- policy ----------------------------------------------------------------------
|
|
402
|
+
|
|
403
|
+
def get_policy(self) -> dict:
|
|
404
|
+
path = f"/tailnet/{self.tailnet}/acl"
|
|
405
|
+
status, data = self._request("GET", path)
|
|
406
|
+
if not isinstance(data, dict):
|
|
407
|
+
raise self._shape_error("GET", path, status, data, "a policy dict")
|
|
408
|
+
return data
|
|
409
|
+
|
|
410
|
+
# ----- waiting ---------------------------------------------------------------------
|
|
411
|
+
|
|
412
|
+
def wait_online(self, hostname: str, timeout: float = 240, poll: float = 5, *,
|
|
413
|
+
created_after: object = None, tag: Optional[str] = None) -> dict:
|
|
414
|
+
"""Poll until a matching device is connected to the control plane; return it.
|
|
415
|
+
Transport errors, 429 and 5xx are retried until the deadline."""
|
|
416
|
+
_positive_seconds(timeout, "timeout")
|
|
417
|
+
_positive_seconds(poll, "poll")
|
|
418
|
+
deadline = time.monotonic() + timeout
|
|
419
|
+
last = "not seen yet"
|
|
420
|
+
while True:
|
|
421
|
+
try:
|
|
422
|
+
device = self.find_device(hostname, created_after=created_after, tag=tag)
|
|
423
|
+
except TailscaleError as error:
|
|
424
|
+
if not _is_transient(error):
|
|
425
|
+
raise
|
|
426
|
+
device, last = None, str(error)
|
|
427
|
+
else:
|
|
428
|
+
if device is not None:
|
|
429
|
+
if device.get("connectedToControl") is True and device_ip(device):
|
|
430
|
+
return device
|
|
431
|
+
last = "seen, not connected yet"
|
|
432
|
+
remaining = deadline - time.monotonic()
|
|
433
|
+
if remaining <= 0:
|
|
434
|
+
raise TailscaleTimeoutError(
|
|
435
|
+
self._redact(f"{hostname!r} not online after {timeout:g}s ({last})"))
|
|
436
|
+
time.sleep(min(poll, remaining))
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Usage: . "$(tailscalekit bash-lib)"
|
|
2
|
+
# ts_authkey [authkey flags...]: mint a key, print it; returns the CLI status.
|
|
3
|
+
# ts_ip HOST|ID: tailnet IPv4; returns 0, or 1 when unknown.
|
|
4
|
+
# ts_wait_online HOST [TIMEOUT]: wait for a connected device, print its IP; failures return 1.
|
|
5
|
+
# ts_delete HOST|ID: remove a device, print the HTTP code; missing returns 0 (already gone).
|
|
6
|
+
# ts_revoke KEYID: revoke a key and verify it; returns the CLI status.
|
|
7
|
+
# Missing required arguments return 2 with stderr.
|
|
8
|
+
# Credentials: TS_API_KEY, or TS_OAUTH_CLIENT_ID + TS_OAUTH_CLIENT_SECRET, exported only in the
|
|
9
|
+
# CLI subshell, never argv. TAILSCALEKIT_CLI overrides the CLI command (default tailscalekit).
|
|
10
|
+
|
|
11
|
+
# Keep exports and function-CLI side effects out of the sourcing shell.
|
|
12
|
+
_tsk_cli() (
|
|
13
|
+
local name
|
|
14
|
+
for name in TS_API_KEY TS_OAUTH_CLIENT_ID TS_OAUTH_CLIENT_SECRET TS_TAILNET TS_API_URL; do
|
|
15
|
+
if [ -n "${!name:-}" ]; then
|
|
16
|
+
export "$name"
|
|
17
|
+
fi
|
|
18
|
+
done
|
|
19
|
+
"${TAILSCALEKIT_CLI:-tailscalekit}" "$@"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
ts_authkey() {
|
|
23
|
+
_tsk_cli authkey "$@"
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
ts_ip() {
|
|
27
|
+
if [ -z "${1:-}" ]; then
|
|
28
|
+
printf '%s\n' 'ts_ip: HOST is required' >&2
|
|
29
|
+
return 2
|
|
30
|
+
fi
|
|
31
|
+
_tsk_cli ip "$1" || return 1
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
ts_wait_online() {
|
|
35
|
+
if [ -z "${1:-}" ]; then
|
|
36
|
+
printf '%s\n' 'ts_wait_online: HOST is required' >&2
|
|
37
|
+
return 2
|
|
38
|
+
fi
|
|
39
|
+
_tsk_cli wait-online "$1" --timeout "${2:-240}" || return 1
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
# A device that is already gone is the outcome the caller wanted.
|
|
43
|
+
ts_delete() {
|
|
44
|
+
local status=0
|
|
45
|
+
if [ -z "${1:-}" ]; then
|
|
46
|
+
printf '%s\n' 'ts_delete: HOST is required' >&2
|
|
47
|
+
return 2
|
|
48
|
+
fi
|
|
49
|
+
_tsk_cli delete "$1" || status=$?
|
|
50
|
+
case "$status" in
|
|
51
|
+
0|3) return 0 ;;
|
|
52
|
+
*) return 1 ;;
|
|
53
|
+
esac
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
ts_revoke() {
|
|
57
|
+
if [ -z "${1:-}" ]; then
|
|
58
|
+
printf '%s\n' 'ts_revoke: KEYID is required' >&2
|
|
59
|
+
return 2
|
|
60
|
+
fi
|
|
61
|
+
_tsk_cli revoke "$1"
|
|
62
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# tailscalekit pod bootstrap: join a container (e.g. a RunPod pod) to your tailnet.
|
|
3
|
+
#
|
|
4
|
+
# TS_AUTHKEY=tskey-auth-... TS_HOSTNAME=llm-mypod bash bootstrap.sh
|
|
5
|
+
#
|
|
6
|
+
# - Userspace networking (no TUN device needed in containers). Inbound tailnet traffic reaches
|
|
7
|
+
# local listeners, including ones bound to 127.0.0.1.
|
|
8
|
+
# - State lives in $TS_STATE_DIR (default /workspace/tailscale) so a restarted container
|
|
9
|
+
# rejoins without a new key. TS_AUTHKEY is used only when not yet authenticated.
|
|
10
|
+
# - The key is never printed or put in argv (it goes to tailscale via a 0600 file), and is
|
|
11
|
+
# unset from the environment immediately.
|
|
12
|
+
# - Installs the static tailscale binaries (pinned version) when missing.
|
|
13
|
+
# Prints "TAILSCALEKIT TAILNET_UP ip=<100.x> hostname=<name>" on success; exits 1 on failure.
|
|
14
|
+
set -uo pipefail
|
|
15
|
+
|
|
16
|
+
TS_VERSION="${TS_VERSION:-1.104.7}"
|
|
17
|
+
# sha256 of tailscale_1.104.7_amd64.tgz from pkgs.tailscale.com (checked 2026-12-01).
|
|
18
|
+
TS_SHA256_DEFAULT_AMD64="e56693ff74a64f2591b7e819c280635a100aae1ddfb0ef058fcd052b7cd8d16c"
|
|
19
|
+
STATE_DIR="${TS_STATE_DIR:-/workspace/tailscale}"
|
|
20
|
+
SOCKET="${TS_SOCKET:-/tmp/tailscaled.sock}"
|
|
21
|
+
HOSTNAME_WANTED="${TS_HOSTNAME:-${RUNPOD_POD_ID:-$(hostname)}}"
|
|
22
|
+
KEY="${TS_AUTHKEY:-}"
|
|
23
|
+
unset TS_AUTHKEY
|
|
24
|
+
|
|
25
|
+
log() { printf 'TAILSCALEKIT %s\n' "$*"; }
|
|
26
|
+
|
|
27
|
+
if ! command -v tailscaled >/dev/null 2>&1; then
|
|
28
|
+
arch=$(uname -m); case "$arch" in x86_64) arch=amd64 ;; aarch64|arm64) arch=arm64 ;; esac
|
|
29
|
+
tmp=$(mktemp -d)
|
|
30
|
+
if ! curl -fsSL "https://pkgs.tailscale.com/stable/tailscale_${TS_VERSION}_${arch}.tgz" -o "$tmp/ts.tgz"; then
|
|
31
|
+
log "INSTALL_FAILED version=$TS_VERSION"; exit 1
|
|
32
|
+
fi
|
|
33
|
+
if [ "$TS_VERSION" = 1.104.7 ] && [ "$arch" = amd64 ]; then
|
|
34
|
+
echo "$TS_SHA256_DEFAULT_AMD64 $tmp/ts.tgz" | sha256sum -c - >/dev/null 2>&1 \
|
|
35
|
+
|| { log "INSTALL_FAILED reason=sha256-mismatch"; exit 1; }
|
|
36
|
+
fi
|
|
37
|
+
tar -xzf "$tmp/ts.tgz" -C "$tmp"
|
|
38
|
+
install -m 0755 "$tmp/tailscale_${TS_VERSION}_${arch}/tailscale" "$tmp/tailscale_${TS_VERSION}_${arch}/tailscaled" /usr/local/bin/
|
|
39
|
+
fi
|
|
40
|
+
|
|
41
|
+
mkdir -p "$STATE_DIR" "$(dirname "$SOCKET")"
|
|
42
|
+
if ! tailscale --socket="$SOCKET" status >/dev/null 2>&1; then
|
|
43
|
+
nohup tailscaled --tun=userspace-networking --statedir="$STATE_DIR" --socket="$SOCKET" \
|
|
44
|
+
>"$STATE_DIR/tailscaled.log" 2>&1 &
|
|
45
|
+
for _ in $(seq 1 30); do
|
|
46
|
+
# The daemon is ready once it answers status (it does even before login).
|
|
47
|
+
tailscale --socket="$SOCKET" status --json >/dev/null 2>&1 && break
|
|
48
|
+
sleep 1
|
|
49
|
+
done
|
|
50
|
+
fi
|
|
51
|
+
|
|
52
|
+
up_args=(--hostname="$HOSTNAME_WANTED" --accept-dns=false)
|
|
53
|
+
backend=$(tailscale --socket="$SOCKET" status --json 2>/dev/null | python3 -c 'import json,sys; print(json.load(sys.stdin).get("BackendState",""))' 2>/dev/null || true)
|
|
54
|
+
if [ "$backend" != "Running" ]; then
|
|
55
|
+
if [ -n "$KEY" ]; then
|
|
56
|
+
# Hand the key over in a 0600 file, not argv (argv is world-readable via /proc). Prefer
|
|
57
|
+
# RAM-backed /dev/shm, and remove the file even if we are interrupted.
|
|
58
|
+
keyfile=$(umask 077; mktemp -p /dev/shm 2>/dev/null || mktemp)
|
|
59
|
+
trap 'rm -f "$keyfile"' EXIT
|
|
60
|
+
trap 'rm -f "$keyfile"; exit 1' INT TERM HUP
|
|
61
|
+
printf '%s' "$KEY" > "$keyfile"
|
|
62
|
+
KEY=""
|
|
63
|
+
joined=0
|
|
64
|
+
timeout 60 tailscale --socket="$SOCKET" up "${up_args[@]}" --auth-key="file:$keyfile" >/dev/null 2>&1 && joined=1
|
|
65
|
+
rm -f "$keyfile"
|
|
66
|
+
trap - EXIT INT TERM HUP
|
|
67
|
+
[ "$joined" = 1 ] || { log "TAILNET_JOIN_FAILED"; exit 1; }
|
|
68
|
+
else
|
|
69
|
+
timeout 30 tailscale --socket="$SOCKET" up "${up_args[@]}" >/dev/null 2>&1 \
|
|
70
|
+
|| { log "TAILNET_JOIN_FAILED reason=no-key-and-no-saved-state"; exit 1; }
|
|
71
|
+
fi
|
|
72
|
+
fi
|
|
73
|
+
KEY=""
|
|
74
|
+
ip=$(tailscale --socket="$SOCKET" ip -4 2>/dev/null | head -n1)
|
|
75
|
+
log "TAILNET_UP ip=${ip:-unknown} hostname=$HOSTNAME_WANTED"
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tailscalekit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Dependency-free Tailscale API control for Python, Bash and the CLI: devices, single-use auth keys, container join
|
|
5
|
+
Author: Kevin Cherry
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/kcherry497/tailscale-kit
|
|
8
|
+
Project-URL: Issues, https://github.com/kcherry497/tailscale-kit/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/kcherry497/tailscale-kit/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: tailscale,vpn,wireguard,auth-keys,containers,cli
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: POSIX
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
24
|
+
Classifier: Programming Language :: Unix Shell
|
|
25
|
+
Classifier: Topic :: System :: Networking
|
|
26
|
+
Classifier: Topic :: System :: Systems Administration
|
|
27
|
+
Requires-Python: >=3.9
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# tailscalekit
|
|
33
|
+
|
|
34
|
+
[](https://github.com/kcherry497/tailscale-kit/actions/workflows/ci.yml)
|
|
35
|
+

|
|
36
|
+

|
|
37
|
+

|
|
38
|
+
[](LICENSE)
|
|
39
|
+
|
|
40
|
+
A small, dependency-free toolkit for putting machines you don't fully trust (GPU pods, CI runners, containers) on your [Tailscale](https://tailscale.com/) tailnet, then cleaning them up. It works from Python, Bash and the command line, and it is the sibling of [runpodkit](https://github.com/kcherry497/runpod-kit).
|
|
41
|
+
|
|
42
|
+
- **Mint safe auth keys:** single-use, pre-approved, short-lived (15 min by default), ephemeral or tagged.
|
|
43
|
+
- **Join a container:** `pod/bootstrap.sh` runs tailscaled in userspace mode (no TUN device). The key goes to tailscale through a 0600 file, **never argv**, and is never printed.
|
|
44
|
+
- **Find, wait for, and remove devices** by hostname. Tailscale's `-1` duplicate suffixes are handled.
|
|
45
|
+
- **Verify revocation properly.** The API keeps revoked keys readable (HTTP 200 with `"invalid": true`), so tailscalekit checks the flag, not the status code.
|
|
46
|
+
- **Check your policy** for the default allow-everything ACL before you expose a service.
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pipx install tailscalekit # CLI
|
|
52
|
+
python3 -m pip install tailscalekit # library, inside a venv
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
For development, clone it and run `./install.sh python3`, which links the clone into an interpreter so `git pull` updates every user on the host. That link carries no package metadata, so a package that declares `tailscalekit` as a dependency should use the pip install above.
|
|
56
|
+
|
|
57
|
+
## Credentials
|
|
58
|
+
|
|
59
|
+
tailscalekit reads credentials from the environment only. There are no key flags, so a credential never lands in argv or shell history.
|
|
60
|
+
|
|
61
|
+
| Variables | Use |
|
|
62
|
+
| --- | --- |
|
|
63
|
+
| `TS_OAUTH_CLIENT_ID` + `TS_OAUTH_CLIENT_SECRET` | **Recommended.** An [OAuth client](https://tailscale.com/kb/1215/oauth-clients) scoped to `auth_keys` (write) and `devices:core` (read/write), plus `policy_file` (read) for `policy-check`. It doesn't expire and can only do what you scoped. Keys minted with it must carry a tag. |
|
|
64
|
+
| `TS_API_KEY` | A personal API key (`tskey-api-…`). Simpler, but it is full-admin and expires within 90 days. |
|
|
65
|
+
| `TS_TAILNET` | Tailnet name; defaults to `-` (the credential's own tailnet). |
|
|
66
|
+
|
|
67
|
+
Letting an AI coding agent drive this? Store the credential in [cred-broker](https://github.com/kcherry497/cred-broker) and run `cred exec tailscale -- tailscalekit …`. The agent uses the credential without ever seeing it.
|
|
68
|
+
|
|
69
|
+
## Quick start
|
|
70
|
+
|
|
71
|
+
**Put a container on the tailnet**
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
# on your machine: mint a single-use key for one container (expires in 15 minutes)
|
|
75
|
+
KEY=$(tailscalekit authkey --tag tag:llm-starter)
|
|
76
|
+
|
|
77
|
+
# in the container (image with curl; static tailscale is downloaded and sha256-checked if missing)
|
|
78
|
+
TS_AUTHKEY="$KEY" TS_HOSTNAME=llm-pod1 bash "$(tailscalekit pod-bootstrap)"
|
|
79
|
+
# TAILSCALEKIT TAILNET_UP ip=100.x.y.z hostname=llm-pod1
|
|
80
|
+
|
|
81
|
+
# back on your machine
|
|
82
|
+
tailscalekit wait-online llm-pod1 # prints the tailnet IP once it is connected
|
|
83
|
+
tailscalekit delete llm-pod1 # when you're done
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**Python**
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from tailscalekit import Tailscale, device_ip
|
|
90
|
+
|
|
91
|
+
ts = Tailscale() # env credentials
|
|
92
|
+
key = ts.create_auth_key(tags=["tag:llm-starter"], expiry_seconds=600)
|
|
93
|
+
# … hand key["key"] to the machine (e.g. as a pod environment variable) …
|
|
94
|
+
device = ts.wait_online("llm-pod1", timeout=300)
|
|
95
|
+
print(device_ip(device))
|
|
96
|
+
ts.revoke_key(key["id"]); assert ts.key_revoked(key["id"])
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
**Bash**
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
. "$(tailscalekit bash-lib)"
|
|
103
|
+
ip=$(ts_wait_online llm-pod1 300) && curl "http://$ip:11434/api/tags"
|
|
104
|
+
ts_delete llm-pod1
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Lock it down: the tailnet policy
|
|
108
|
+
|
|
109
|
+
The default Tailscale policy lets every device reach every other device. If the machine you add runs a service with no authentication of its own (an Ollama server, a Jupyter kernel), anyone on the tailnet can use it. And if that machine is compromised, it can reach your laptop and NAS. `tailscalekit policy-check` prints `default-allow` when that is the case. A minimal policy for one tagged service:
|
|
110
|
+
|
|
111
|
+
```jsonc
|
|
112
|
+
{
|
|
113
|
+
"tagOwners": { "tag:llm-starter": ["autogroup:admin"] },
|
|
114
|
+
"grants": [
|
|
115
|
+
// your own devices may reach the service port on tagged machines…
|
|
116
|
+
{ "src": ["autogroup:member"], "dst": ["tag:llm-starter"], "ip": ["tcp:11434"] }
|
|
117
|
+
// …and nothing is granted FROM tag:llm-starter, so the pod can't reach your devices.
|
|
118
|
+
]
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Merge this into your existing policy rather than replacing it. Minting a tagged key fails with HTTP 400 ("not permitted") until the minting identity owns the tag.
|
|
123
|
+
|
|
124
|
+
## Reference
|
|
125
|
+
|
|
126
|
+
### Python (`tailscalekit.Tailscale`)
|
|
127
|
+
|
|
128
|
+
| Method | Result |
|
|
129
|
+
| --- | --- |
|
|
130
|
+
| `list_devices()` | All devices (dicts) |
|
|
131
|
+
| `find_device(hostname, created_after=None, tag=None)` | Newest exact match (then `hostname-N` duplicates), or `None` |
|
|
132
|
+
| `get_device(id)` / `delete_device(id)` | Device or `None` on 404 / HTTP status (404 = already gone) |
|
|
133
|
+
| `create_auth_key(reusable=False, ephemeral=True, preauthorized=True, tags=None, expiry_seconds=900, description="tailscalekit")` | `{"id", "key", "expires", …}`; the only copy of the key |
|
|
134
|
+
| `list_keys()` / `get_key(id)` | Key metadata, never values |
|
|
135
|
+
| `revoke_key(id)` / `key_revoked(id)` | HTTP status / `True` once the key is unusable |
|
|
136
|
+
| `get_policy()` | The tailnet policy as JSON |
|
|
137
|
+
| `wait_online(hostname, timeout=240, poll=5, created_after=None, tag=None)` | The device once `connectedToControl` with an IP; retries transport errors, 429 and 5xx; raises `TailscaleTimeoutError` |
|
|
138
|
+
|
|
139
|
+
Helpers: `device_ip(device, version=4)`, `public_device(device)` (drops node, machine and lock keys), `policy_allows_all(policy)`, `redact(text, *secrets)` (removes every `tskey-…`).
|
|
140
|
+
|
|
141
|
+
### CLI
|
|
142
|
+
|
|
143
|
+
| Command | Output | Exit |
|
|
144
|
+
| --- | --- | --- |
|
|
145
|
+
| `devices [--all-fields]` | JSON; node, machine and lock keys hidden by default | 0 |
|
|
146
|
+
| `device HOST\|ID [--all-fields]` | Device JSON | 0, or 3 if not found |
|
|
147
|
+
| `ip HOST\|ID [--ipv6]` | Tailnet IP | 0, or 3 if not found |
|
|
148
|
+
| `authkey [--tag T]… [--reusable] [--no-ephemeral] [--no-preauthorized] [--expiry S] [--description D] [--json]` | The key, or `{"id","key","expires"}` | 0 |
|
|
149
|
+
| `keys` | Key metadata JSON | 0 |
|
|
150
|
+
| `revoke KEYID` | HTTP status; then verifies the key is invalid | 0, or 1 if still valid |
|
|
151
|
+
| `delete HOST\|ID` | HTTP status | 0, or 3 if not found |
|
|
152
|
+
| `wait-online HOST [--timeout N] [--after ISO] [--tag T] [--json]` | IP or device JSON | 0, or 3 on timeout |
|
|
153
|
+
| `policy-check` | `default-allow` or `restricted` | 0 |
|
|
154
|
+
| `bash-lib` / `pod-bootstrap` / `version` / `--version` | Path / path / version | 0 |
|
|
155
|
+
|
|
156
|
+
All commands also use 1 for errors (one `tailscalekit:` line on stderr, secrets redacted), 2 for usage errors, and 130 on Ctrl-C.
|
|
157
|
+
|
|
158
|
+
### Bash library
|
|
159
|
+
|
|
160
|
+
`ts_authkey [flags]`, `ts_ip HOST`, `ts_wait_online HOST [TIMEOUT]`, `ts_delete HOST` (an already-missing device counts as success), `ts_revoke KEYID`. Credentials are exported only inside the CLI's subshell. The library is safe under `set -uo pipefail` and works on Bash 3.2.
|
|
161
|
+
|
|
162
|
+
### Pod bootstrap (`tailscalekit pod-bootstrap`)
|
|
163
|
+
|
|
164
|
+
| Variable | Default | Meaning |
|
|
165
|
+
| --- | --- | --- |
|
|
166
|
+
| `TS_AUTHKEY` | – | Used only if the node isn't already authenticated; unset immediately and passed via a 0600 file |
|
|
167
|
+
| `TS_HOSTNAME` | `$RUNPOD_POD_ID`, else `hostname` | Tailnet hostname |
|
|
168
|
+
| `TS_STATE_DIR` | `/workspace/tailscale` | Keep it on a persistent volume so a restarted container rejoins without a new key |
|
|
169
|
+
| `TS_VERSION` | `1.104.7` | Static build to install if tailscale is missing (sha256-pinned for amd64) |
|
|
170
|
+
|
|
171
|
+
Ephemeral vs. tagged: an **ephemeral** node vanishes shortly after it goes offline, which suits throwaway runs. A **tagged, non-ephemeral** node (`--no-ephemeral --tag …`) keeps its identity across stop/start through the saved state, and tagged devices don't hit key expiry. Delete it explicitly when you're done.
|
|
172
|
+
|
|
173
|
+
## Security notes
|
|
174
|
+
|
|
175
|
+
- Keys come from the environment only. Error output redacts the configured secret and **any** `tskey-…` token.
|
|
176
|
+
- A key given to a machine should be assumed readable by whoever controls that machine's platform. Single-use, short expiry and revoke-after-join keep the blast radius small.
|
|
177
|
+
- `authkey` prints the minted key, on purpose: piping it to a machine is its job.
|
|
178
|
+
- Tests are offline; every unmocked network call fails the test.
|
|
179
|
+
|
|
180
|
+
## Development
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
python3 -m unittest discover -s tests -v
|
|
184
|
+
TAILSCALEKIT_TEST_BASHES=/path/to/bash3.2:/bin/bash python3 -m unittest tests.test_bash -v
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
## License
|
|
188
|
+
|
|
189
|
+
MIT. See [LICENSE](LICENSE). Not affiliated with or endorsed by Tailscale Inc.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
tailscalekit/__init__.py,sha256=_VvHCSYoIQUygViKL_t69wdldxjYXUlRFN9wQSGgOXo,436
|
|
2
|
+
tailscalekit/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
|
|
3
|
+
tailscalekit/cli.py,sha256=ntEw_0mdZylFENNjMptZA9IMAJ2YewsdRU-gnGnu-fg,9027
|
|
4
|
+
tailscalekit/client.py,sha256=tBW5qwH19JT589S7PtWsmPVaFoae9A1iUH_QvTS_HVE,20538
|
|
5
|
+
tailscalekit/lib/tailscale.sh,sha256=LZHzP1EG4zCCVUVNM5s6-TJjqzjp5lg2TsPSBXSA0LU,1881
|
|
6
|
+
tailscalekit/pod/bootstrap.sh,sha256=wgm5Wze1UwGL_HkECyimUz5l4X5IKkJSIy_cJYUddv8,3759
|
|
7
|
+
tailscalekit-0.1.0.dist-info/licenses/LICENSE,sha256=vGOU6bzfNbWhA-EgY207i7BYQbHHnyxH1oK3v8hiVk8,1069
|
|
8
|
+
tailscalekit-0.1.0.dist-info/METADATA,sha256=Xkv9BJCJcskuuupjBcjqUykD0VPOVRIUzC3nKVasxPw,10350
|
|
9
|
+
tailscalekit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
tailscalekit-0.1.0.dist-info/entry_points.txt,sha256=_ZSdjeZaMYlr0Vqqbu_zHshI8AnlKNA8NzRKXE4d2RE,55
|
|
11
|
+
tailscalekit-0.1.0.dist-info/top_level.txt,sha256=r8RXfgM4SzOuuyopKvjQY2eKqnn4y_0BcMmuXaG2qhY,13
|
|
12
|
+
tailscalekit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kevin Cherry
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tailscalekit
|