The hang
Every AWS command in my infrastructure tool resolves credentials first. A small script works out where they come from, checks that they are usable, and prints shell exports that the recipe evaluates before the real command runs. When the source is SSO, "usable" means the cached token has not expired. When it has, the script starts the device-code login: it prints a URL and a short code, and waits for someone to open the URL in a browser and approve it.
In September I ran one of those commands with no terminal attached.
Standard input was not a terminal and the output was going to a file.
The token had expired overnight. The script did what it was written
to do. It started the login, the URL and the code went into the log,
and the process sat there. About ten minutes later the code expired,
the login died, and the command failed with a
CalledProcessError and no useful message. Nothing had
been wrong with the command, the account, or the network. The tool
had asked a question into a file.
How it got there
The code that hung was itself a fix from June. The original problem
was the opposite one: the URL and the code were not reaching the
person at the keyboard. The credentials script runs as
eval $(script ...), so the shell captures its standard
output, and writing the prompt to standard error did not reliably
reach the terminal either through the layers of make and
subprocesses. A second helper read the login's output through a
pipe and only printed it after the process exited, which it could
not do until the user had seen the URL. A deadlock, hidden until a
CLI upgrade changed the timing.
The June fix opened /dev/tty directly and handed it to
the login as standard output and standard error, bypassing every
capture in between. That was right. Its fallback was wrong: when
/dev/tty could not be opened, the comment said "CI,
headless", and the code carried on with the inherited descriptors
and launched the login anyway. No terminal means nobody can see the
code. Launching the login in that state is not a fallback, it is a
guaranteed ten-minute wait followed by a failure.
The guard
The fix is a few lines ahead of the login, and it runs before the script writes the lock file that stops two logins racing each other.
try:
tty = open("/dev/tty", "w")
except OSError:
tty = None
if tty is None or os.environ.get("TOOL_NONINTERACTIVE") == "1":
if tty is not None:
tty.close()
print(
f"ERROR: SSO session '{session_name}' has expired and no "
f"terminal is available for the device-code login. "
f"Run: <tool> sso-login session={friendly_session(session_name)}",
file=sys.stderr,
)
raise SystemExit(2)
Three things about it matter more than the code.
It exits non-zero immediately. The recipe wraps the
credentials step as _creds="$(...)" && eval
"$_creds", so exit code 2 stops the recipe before the real
command runs. A scheduled job fails in under a second with a clear
line in its log, instead of ten minutes later with a stack trace.
It prints the exact command a human should run. Not "please log in", but the tool's own login command with the session name filled in. Whoever reads the log can paste it.
A non-interactive flag forces the same path. A job launched from a terminal session can still have a terminal attached even though nobody is watching it. Setting the flag in that job's environment means it never starts a login it cannot finish, terminal or not. The interactive behaviour, with a real terminal and no flag, is unchanged.
Three unit tests pin it: no terminal means exit 2, the hint on standard error, and no login process launched; the flag set means the same, with the terminal handle closed; a terminal available means the login runs and the lock file is gone afterward. The live check is the same command that hung, run with the flag set against a stale token. It fails in the time it takes to print two lines.
A status command, so the next person does not guess
The error tells you what to do. It does not tell you how you got there, and credentials in this tool can come from three places: an SSO token on a laptop, a secrets manager on a server, or a device certificate on an always-on device that has no browser at all. So there is a status command that reads the configuration and the token cache without retrieving any credential, and prints:
- The credential source in effect, and for which account.
- For SSO, one line per session:
valid (0h 50m remaining), orEXPIREDfollowed by the login command to run. - For a device-certificate profile, that no SSO token is needed, which helper provides the credentials, and the certificate's subject and expiry date.
- For a secrets manager, which configuration file is in use, and nothing else.
That last point is deliberate. A status command that prints a secret to prove it has one will end up in a log.
The hint that could not be run
The status command had its own bug, found the same day. Its label
for each token, and therefore the session name in the hint it
printed, came from a heuristic on the login URL: one of two
hard-coded names depending on whether a substring appeared in the
URL. In an environment whose session was named something else, the
command printed EXPIRED next to the wrong name, and the
command it suggested failed with invalid choice. A hint
that cannot be pasted is worse than no hint.
The fix reads the [sso-session] blocks from the AWS
config file, maps each start URL to the session name the tool's own
login command accepts, and only falls back to the old heuristic for
a URL with no matching block. While I was in there, tokens are now
deduplicated per start URL, keeping the freshest. A legacy profile
login and a session login cache the same URL under different file
names, and before the change a stale file printed
EXPIRED beside a perfectly valid token.
One correction to my own notes from that day. I first wrote that the status command was reporting an expired token falsely. It was not. The token had expired, and the SDK had silently refreshed it during the next command I ran, which made the earlier status look wrong in hindsight. Only the label was wrong. Four tests cover the mapping, the fallback, and a missing config file.
For any CLI that might run without a terminal
- Before any interactive step, test for a terminal. Opening
/dev/ttyand catching the failure is the honest test; checking whether standard input is a terminal is not, because pipes and redirects change that without changing who is watching. - No terminal means a non-zero exit now, with the exact command a human should run. Never start a prompt that nobody can answer.
- Offer an explicit non-interactive flag for jobs that have a terminal but no person.
- Ship a status command that says where credentials come from and how long they last, without printing a secret.
- Any name a hint prints must come from the same table the command parses. Guessing it from a URL is how you print a command that does not exist.
- Test the no-terminal path on purpose:
command < /dev/null 2>&1 | catwith a stale token. If it takes longer than a second to fail, it is going to hang in production.