Skip to content

AddHost: guard read-check-write with exclusive file lock to prevent duplicate aliases under concurrent --add runs #2

@coderabbitai

Description

@coderabbitai

Summary

In internal/sshconfig/writer.go, the AddHost function performs a read-check-write sequence (read existing hosts → check for duplicate aliases → append new host) that is not atomic. Under concurrent --add invocations, two goroutines/processes can both pass the duplicate-alias check and each append a Host block, resulting in duplicate entries in the SSH config file.

Affected code

internal/sshconfig/writer.goAddHost function, specifically the readExistingHosts → alias comparison loop → append/write sequence.

Suggested fix

Wrap the entire read/check/write sequence with an exclusive file lock (e.g. flock / syscall.Flock on Linux/macOS) or use an atomic temp-file-and-rename approach:

  1. Open (or create) the SSH config file.
  2. Acquire an exclusive lock before calling readExistingHosts.
  3. Perform the alias comparison and decision (return existing host or error).
  4. Append/write the new host block while still holding the lock.
  5. Release the lock only after the file has been fully updated.

Context

Raised during code review in PR #1 by @coderabbitai. Deferred to a follow-up issue so PR #1 stays focused on the --add/--find feature work.

PR reference: #1
Comment reference: #1 (comment)

/cc @machugram

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions