APIs
The web console terminal’s WebSocket: a bash shell inside the server’s own container.
TerminalConsumer runs a shell.TerminalShell for each connection, in the server
process that accepted it, and so in whichever pod, or container, the load balancer chose. It
passes the browser’s keystrokes to the shell, and the shell’s output to the browser, where
xterm.js draws it. See messages for the protocol.
The shell runs as the server’s operating system user, with the server’s environment, and so with
every credential that the server has. Only a superuser can connect, while
smarter_settings.app_dashboard_web_console_terminal_enable is set, with a single use ticket from
tickets.TerminalTicketApiView. A connection that fails a check is refused before the
WebSocket is accepted, and the refusal is logged.
A session ends when the shell exits, when the WebSocket closes (the page is closed or reloaded,
the connection drops, or the server restarts), after const.TERMINAL_IDLE_TIMEOUT seconds
without input, or after const.TERMINAL_MAX_DURATION seconds. Its shell, and every process
of the shell’s session, is then hung up and killed. Each session’s start and end are logged, with
its user, host and shell, but not what was typed, which can include credentials.
- class smarter.apps.dashboard.views.terminal_emulator.api.consumers.TerminalConsumer(*args, **kwargs)[source]
Bases:
AsyncWebsocketConsumer,SmarterHelperMixinA bash shell for a superuser, over a WebSocket.
See the module’s docstring.
- __init__(*args, **kwargs)[source]
- async connect()[source]
Check the user and the ticket, then accept the connection and start the shell.
- async disconnect(code)[source]
The WebSocket closed: end the shell.
- async receive(text_data=None, bytes_data=None)[source]
Input or a resize from the browser.
A binary message is input. A message that is not valid is ignored.
- async refuse(reason)[source]
Refuse the connection, before accepting it: the browser sees the handshake fail.
- async send_output(data)[source]
Send the shell’s output to the browser.
- sessions: ClassVar[set[TerminalConsumer]] = {}
The sessions that this server process runs.
- async shell_exited(code)[source]
The shell exited: tell the browser why, and close the WebSocket.
- property username: str
The connected user’s name, for the log.
A shell on a pseudo terminal, read and written from an asyncio event loop.
TerminalShell runs bash --login (const.TERMINAL_SHELL) on its own pseudo
terminal, in its own session, as the server’s operating system user, in the server’s environment.
It is the shell of a web console terminal session. See consumers.
The shell is started with setsid --ctty, so that the pseudo terminal is its controlling
terminal: then job control, Ctrl+C and full screen programs such as vim, less and top
work as in any terminal. Without setsid (it is in util-linux, which the Smarter image has), the
shell still runs, in its own session, but without job control.
Everything that the shell writes is read without blocking the event loop, and passed in order to
on_output. When the shell exits, on_exit is called once with its exit status.
TerminalShell.terminate() hangs up the shell, and kills whatever is left of its session.
- smarter.apps.dashboard.views.terminal_emulator.api.shell.ExitCallback
Called once, with the shell’s exit status, after the shell exits.
- smarter.apps.dashboard.views.terminal_emulator.api.shell.OutputCallback
Called with each chunk of the shell’s output, in order.
- class smarter.apps.dashboard.views.terminal_emulator.api.shell.TerminalShell(on_output, on_exit, cols=80, rows=24, command=('bash', '--login'))[source]
Bases:
SmarterHelperMixinA shell on a pseudo terminal.
See the module’s docstring.
- Parameters:
- __init__(on_output, on_exit, cols=80, rows=24, command=('bash', '--login'))[source]
Note: this needs to exist; something in the Python MRO requires it, even if it does nothing.
If you remove this, you will get a mysterious error about something downstream expecting exactly one object.
- argv()[source]
The command line that starts the shell: under
setsid --cttywhere there is one.
- static environment()[source]
The shell’s environment: the server’s, for a color terminal.
- resize(cols, rows)[source]
Resize the shell’s terminal.
- property running: bool
Whether the shell has started, and has not exited.
- static set_size(fd, cols, rows)[source]
Set a terminal’s size. The shell, and the program in its foreground, get a
SIGWINCH.
- async start()[source]
Start the shell, and begin reading its output.
- async terminate()[source]
End the shell: hang it up, as when a terminal is closed, then, after.
const.TERMINAL_TERMINATE_GRACEseconds, kill what is left of its session.The shell’s exit then ends its output, and
on_exitis called. Does nothing if the shell is not running.- Return type:
- async wait_closed()[source]
Wait until the shell’s output has been passed on, and
on_exithas been called.- Return type:
- smarter.apps.dashboard.views.terminal_emulator.api.shell.session_pids(sid)[source]
The processes of a session: the shell, and everything it started that is still running.
A process that started a session of its own, e.g. with
setsidor as a daemon, is not included, nor is a zombie, which has exited, and only waits to be reaped. Reads/proc, so returns an empty list where there is none, e.g. on macOS.
Single use tickets for the web console terminal’s WebSocket.
A browser opens a WebSocket with its session cookie, which the browser also sends when another
site’s page opens the same WebSocket. Channels’ origin check refuses such a connection, and a
ticket refuses it as well: the terminal’s page POSTs, with its CSRF token, to
TerminalTicketApiView, which only a superuser can call, and opens the WebSocket with the
ticket that it returns. consumers.TerminalConsumer accepts the connection only if the
ticket was issued to the same user, within const.TERMINAL_TICKET_TIMEOUT seconds, and has
not been redeemed before.
- smarter.apps.dashboard.views.terminal_emulator.api.tickets.MAX_TICKET_LENGTH = 128
Longer tickets are refused without a cache lookup.
- smarter.apps.dashboard.views.terminal_emulator.api.tickets.TICKET_CACHE_PREFIX = 'smarter.apps.dashboard.terminal.ticket.'
The cache key prefix of a ticket, whose value is the id of the user that it was issued to.
- class smarter.apps.dashboard.views.terminal_emulator.api.tickets.TerminalTicketApiView(**kwargs)[source]
Bases:
SmarterAuthenticatedNeverCachedWebViewIssue a terminal ticket to the signed in superuser.
Wrapped in
enabled.require_terminal()in the url patterns, so that it is a 404 while the terminal is disabled, and for every other user.Response shape (
messages.TerminalTicket):{"ticket": "Vb3...", "url": "/ws/terminal/"}
- dispatch(request, *args, **kwargs)
Dispatch the request, redirecting to login if the user is anonymous.
- Parameters:
request (
HttpRequest) – The HTTP request object.args – Passed to the view.
kwargs – Passed to the view.
- Return type:
- Returns:
The view’s response, which varies on
Cookie, or a redirect to/login/that expires the cache.
- property formatted_class_name: str
Returns a formatted string of the class name for logging purposes.
- post(request, *args, **kwargs)[source]
Issue a ticket.
- Parameters:
request (
HttpRequest) – The POST request, with the CSRF token.args – Additional positional arguments forwarded by the URL dispatcher.
kwargs – Additional keyword arguments forwarded by the URL dispatcher.
- Returns:
The ticket, and the WebSocket’s path.
- Return type:
- smarter.apps.dashboard.views.terminal_emulator.api.tickets.issue_ticket(user_id)[source]
Issue a ticket to a user, valid for
const.TERMINAL_TICKET_TIMEOUTseconds.
- smarter.apps.dashboard.views.terminal_emulator.api.tickets.redeem_ticket(ticket, user_id)[source]
Redeem a ticket: whether it was issued to the user, and is still valid.
A ticket can be redeemed once, by whoever presents it first, even by another user, who is refused.
The messages of the web console terminal’s WebSocket, and of its ticket api.
The browser sends TerminalInputMessage and TerminalResizeMessage as JSON text
messages. The server sends the shell’s output as binary messages, the raw bytes that the shell
wrote to its terminal, and TerminalSessionMessage and TerminalExitMessage as JSON
text messages. See consumers.
- smarter.apps.dashboard.views.terminal_emulator.api.messages.TERMINAL_MAX_INPUT = 65536
The most characters of input in one message, e.g. a paste.
- smarter.apps.dashboard.views.terminal_emulator.api.messages.TERMINAL_MAX_SIZE = 1000
The most columns or rows of a terminal.
- smarter.apps.dashboard.views.terminal_emulator.api.messages.TerminalClientMessage
A message from the browser.
alias of
Annotated[TerminalInputMessage|TerminalResizeMessage, FieldInfo(annotation=NoneType, required=True, discriminator=’type’)]
- class smarter.apps.dashboard.views.terminal_emulator.api.messages.TerminalExitMessage(*, type='exit', reason, code=None)[source]
Bases:
BaseModelThe session ended.
The last message of every session that started.
- model_config = {'extra': 'forbid'}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- reason: Literal['exited', 'idle', 'expired', 'failed']
- type: Literal['exit']
- class smarter.apps.dashboard.views.terminal_emulator.api.messages.TerminalInputMessage(*, type, data)[source]
Bases:
BaseModelKeystrokes, or pasted text, for the shell.
- data: str
- model_config = {'extra': 'forbid'}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- type: Literal['input']
- class smarter.apps.dashboard.views.terminal_emulator.api.messages.TerminalResizeMessage(*, type, cols, rows)[source]
Bases:
BaseModelThe browser’s terminal changed size, so the shell’s terminal does too.
- cols: int
- model_config = {'extra': 'forbid'}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- rows: int
- type: Literal['resize']
- class smarter.apps.dashboard.views.terminal_emulator.api.messages.TerminalSessionMessage(*, type='session', hostname, user, command, pid, idle_timeout, max_duration)[source]
Bases:
BaseModelThe shell started.
The first message of every session.
The browser shows where the shell runs, and how long the session can last, in the banner that it prints above the shell’s prompt.
- command: str
- hostname: str
- idle_timeout: int
- max_duration: int
- model_config = {'extra': 'forbid'}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- pid: int
- type: Literal['session']
- user: str
- class smarter.apps.dashboard.views.terminal_emulator.api.messages.TerminalTicket(*, ticket, url)[source]
Bases:
BaseModelThe ticket api’s response: a single use ticket, and the WebSocket to redeem it at.
- model_config = {'extra': 'forbid'}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- ticket: str
- url: str
- smarter.apps.dashboard.views.terminal_emulator.api.messages.terminal_client_message: TypeAdapter[TerminalInputMessage | TerminalResizeMessage] = TypeAdapter(Annotated[Union[TerminalInputMessage, TerminalResizeMessage], FieldInfo(annotation=NoneType, required=True, discriminator='type')])
terminal_client_message.validate_json(text).- Type:
Validates a message from the browser