1+ #! /usr/bin/env bash
2+ # Copyright (c) 2025 Tailscale Inc & AUTHORS All rights reserved.
3+ # Use of this source code is governed by a BSD-style
4+ # license that can be found in the LICENSE file.
5+
6+ # This script handles Tailscale authentication during postCreateCommand
7+ # when GitHub Codespaces secrets are guaranteed to be available
8+
9+ if [[ $( id -u) -ne 0 ]]; then
10+ if ! command -v sudo > /dev/null; then
11+ >&2 echo " tailscale auth setup could not run as root."
12+ exit 1
13+ fi
14+ exec sudo --non-interactive -E " $0 " " $@ "
15+ fi
16+
17+ # Move the auth key to a non-exported variable so it is not leaking into child
18+ # process environments.
19+ auth_key=" $TS_AUTH_KEY "
20+ unset TS_AUTH_KEY
21+
22+ TAILSCALED_SOCK=/var/run/tailscale/tailscaled.sock
23+
24+ # Wait for tailscaled to be ready (it should be running from entrypoint)
25+ count=100
26+ while (( count-- )) ; do
27+ [[ -S $TAILSCALED_SOCK ]] && break
28+ sleep 0.1
29+
30+ if (( count == 0 )) ; then
31+ >&2 echo " ERROR: tailscaled socket not found. Is tailscaled running?"
32+ exit 1
33+ fi
34+ done
35+
36+ # Check if already authenticated
37+ if /usr/local/bin/tailscale status --json > /dev/null 2>&1 ; then
38+ # Already authenticated, check if it's working
39+ if /usr/local/bin/tailscale status --json | grep -q ' "BackendState":"Running"' ; then
40+ echo " Tailscale is already running and authenticated"
41+ exit 0
42+ fi
43+ fi
44+
45+ # Authenticate with auth key if available
46+ if [[ -n " $auth_key " ]]; then
47+ if [[ " $auth_key " == " test-auth-key" ]]; then
48+ # Special test case
49+ touch /tmp/test-auth-key-seen
50+ echo " Test auth key detected"
51+ else
52+ echo " Authenticating Tailscale with auth key..."
53+ hostnamearg=" "
54+ if [[ -n " ${CODESPACE_NAME} " ]]; then
55+ hostnamearg=" --hostname=${CODESPACE_NAME} "
56+ fi
57+
58+ if /usr/local/bin/tailscale up --accept-routes --authkey=" $auth_key " $hostnamearg ; then
59+ echo " Tailscale authentication successful"
60+ else
61+ >&2 echo " ERROR: Tailscale authentication failed"
62+ exit 1
63+ fi
64+ fi
65+ else
66+ echo " Tailscale is running. To authenticate, run: sudo tailscale up --accept-routes"
67+ fi
0 commit comments