Skip to content

[backport/1.4] core: move setup_ssh() over to startup_blueos_update#3898

Open
patrickelectric wants to merge 1 commit intobluerobotics:1.4-devfrom
joaoantoniocardoso:backports/1.4/setup_ssh
Open

[backport/1.4] core: move setup_ssh() over to startup_blueos_update#3898
patrickelectric wants to merge 1 commit intobluerobotics:1.4-devfrom
joaoantoniocardoso:backports/1.4/setup_ssh

Conversation

@patrickelectric
Copy link
Copy Markdown
Member

@patrickelectric patrickelectric commented Apr 24, 2026

This is a backport of #3050

Summary by Sourcery

New Features:

  • Add SSH setup routine that generates and stores an SSH key pair in the container config volume and ensures the public key is present in the target user's authorized_keys on startup.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Apr 24, 2026

Reviewer's Guide

Backports automatic SSH key generation and authorized_keys setup into the BlueOS startup update script, and wires it into the script entrypoint so SSH is configured on startup.

Sequence diagram for BlueOS startup SSH setup and main execution

sequenceDiagram
    actor System
    participant PythonInterpreter as Python_interpreter
    participant Module as blueos_startup_update
    participant SSH as setup_ssh
    participant Main as main

    System->>PythonInterpreter: Invoke blueos_startup_update.py
    PythonInterpreter->>Module: Load module
    PythonInterpreter->>SSH: Call setup_ssh
    SSH-->>PythonInterpreter: bool (success or failure)
    PythonInterpreter->>Module: Log error if setup_ssh raised
    PythonInterpreter->>Main: Call main
    Main-->>PythonInterpreter: int exit_code
    PythonInterpreter-->>System: Exit with code
Loading

Flow diagram for setup_ssh logic in BlueOS startup update

flowchart TD
    A["Start setup_ssh"] --> B["Log 'Setting up SSH...'"]
    B --> C["Set key_path to /root/.config/.ssh"]
    C --> D["Set private_key to key_path/id_rsa"]
    D --> E["Set public_key to private_key with .pub suffix"]
    E --> F["Read SSH_USER or default pi"]
    F --> G["Read USER_GID or default 1000 and convert to int"]
    G --> H["Read USER_UID or default 1000 and convert to int"]
    H --> I["Set authorized_keys path to /home/user/.ssh/authorized_keys"]
    I --> J["Create key_path directory (parents, exist_ok)"]
    J --> K{"Does public_key file exist?"}
    K -- "No" --> L["Run ssh-keygen to create RSA key pair"]
    L --> M["Log 'Generated new SSH key pair'"]
    K -- "Yes" --> N["Skip key generation"]
    M --> O["Read public_key text (UTF-8)"]
    N --> O
    O --> P{"Can read authorized_keys?"}
    P -- "Yes" --> Q["Read authorized_keys text (UTF-8)"]
    P -- "FileNotFoundError" --> R["Log missing authorized_keys file"]
    R --> S["Set authorized_keys_text to empty string"]
    Q --> T{"Does authorized_keys_text contain public_key_text?"}
    S --> T
    T -- "No" --> U{"Does authorized_keys_text end with newline?"}
    U -- "No" --> V["Append newline to authorized_keys_text"]
    U -- "Yes" --> W["Skip newline append"]
    V --> X["Append public_key_text to authorized_keys_text"]
    W --> X
    X --> Y["Write authorized_keys_text back to authorized_keys (UTF-8)"]
    Y --> Z["Log 'Added public key to authorized_keys'"]
    T -- "Yes" --> AA["Skip updating authorized_keys"]
    Z --> AB["Change owner of authorized_keys to uid,gid"]
    AA --> AB
    AB --> AC["Set permissions of authorized_keys to 600"]
    AC --> AD["Return True"]
    subgraph ErrorHandling
        AE["Any Exception raised"] --> AF["Log 'Error setting up ssh:' with exception"]
        AF --> AG["Return False"]
    end
Loading

File-Level Changes

Change Details Files
Introduce SSH setup routine that generates an SSH key pair in the container config volume and ensures the public key is present in the target user's authorized_keys with correct permissions.
  • Add setup_ssh() helper that creates /root/.config/.ssh, generates an RSA key pair if missing, and reads the public key
  • Ensure the public key is appended to /home/<SSH_USER>/.ssh/authorized_keys if not already present, creating the file content as needed
  • Apply correct ownership and 0600 permissions on authorized_keys based on USER_UID/USER_GID environment variables
  • Log key generation, file creation, and error conditions, and return a boolean success flag
core/tools/blueos_startup_update/blueos_startup_update.py
Hook SSH setup into the startup script entrypoint so it runs before the main update logic.
  • Invoke setup_ssh() in the main section before calling main()
  • Wrap setup_ssh() call in a try/except and log any exceptions without preventing main() from running
core/tools/blueos_startup_update/blueos_startup_update.py

Possibly linked issues

  • #(unassigned): Issue reports failed SSH key registration blocking updates; PR runs setup_ssh in blueos_startup_update to generate/register keys.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • Consider ensuring the parent directory for authorized_keys (e.g. /home/<user>/.ssh) exists and has appropriate permissions before writing the file, otherwise authorized_keys.write_text() and os.chown() may fail on a fresh system.
  • The broad except Exception inside setup_ssh() combined with another broad try/except around setup_ssh() in __main__ is redundant; you could either let setup_ssh() raise and handle it at the call site, or handle/log everything inside setup_ssh() and remove the outer try/except.
  • Since setup_ssh() returns a boolean to indicate success, consider using that return value in __main__ (or removing the return type) to avoid suggesting callers can rely on a success/failure signal that is currently ignored.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider ensuring the parent directory for `authorized_keys` (e.g. `/home/<user>/.ssh`) exists and has appropriate permissions before writing the file, otherwise `authorized_keys.write_text()` and `os.chown()` may fail on a fresh system.
- The broad `except Exception` inside `setup_ssh()` combined with another broad `try/except` around `setup_ssh()` in `__main__` is redundant; you could either let `setup_ssh()` raise and handle it at the call site, or handle/log everything inside `setup_ssh()` and remove the outer try/except.
- Since `setup_ssh()` returns a boolean to indicate success, consider using that return value in `__main__` (or removing the return type) to avoid suggesting callers can rely on a success/failure signal that is currently ignored.

## Individual Comments

### Comment 1
<location path="core/tools/blueos_startup_update/blueos_startup_update.py" line_range="678" />
<code_context>
+    user = os.environ.get("SSH_USER", "pi")
+    gid = int(os.environ.get("USER_GID", 1000))
+    uid = int(os.environ.get("USER_UID", 1000))
+    authorized_keys = Path(f"/home/{user}/.ssh/authorized_keys")
+
+    try:
</code_context>
<issue_to_address>
**issue:** Writing to `authorized_keys` assumes the parent `.ssh` directory exists, which can cause failures on fresh systems.

On a fresh setup `/home/{user}/.ssh` may not exist, so this will raise `FileNotFoundError` despite the missing file handling above. Consider creating the parent directory first with `authorized_keys.parent.mkdir(parents=True, exist_ok=True)` (and then applying the appropriate `chown`/`chmod`) before writing the file.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

user = os.environ.get("SSH_USER", "pi")
gid = int(os.environ.get("USER_GID", 1000))
uid = int(os.environ.get("USER_UID", 1000))
authorized_keys = Path(f"/home/{user}/.ssh/authorized_keys")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Writing to authorized_keys assumes the parent .ssh directory exists, which can cause failures on fresh systems.

On a fresh setup /home/{user}/.ssh may not exist, so this will raise FileNotFoundError despite the missing file handling above. Consider creating the parent directory first with authorized_keys.parent.mkdir(parents=True, exist_ok=True) (and then applying the appropriate chown/chmod) before writing the file.

@patrickelectric
Copy link
Copy Markdown
Member Author

I would hold this PR until we do the stable release for RadCam.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants