feat: instance-level SSH key selection for container mounting

- Revert mistaken ssh_key_id from ConfigProfile (model, API, resolver, frontend)
- Add ssh_key_ids JSON column to tool_instances via migration
- Update create_instance to accept and store ssh_key_ids
- Update start_instance to mount selected SSH keys to {home_dir}/.ssh
- Update list_instances to return ssh_key_ids
- Frontend CreateSessionForm: multi-select SSH key checkboxes
- Frontend instance-list: SSH key selector for start/restart actions
- Maintain separate SSH key dirs per key to avoid conflicts

Quality gates: pytest (231 passed, 6 pre-existing), tsc --noEmit clean
This commit is contained in:
Alex Blank
2026-05-29 13:30:53 +02:00
parent cbd3436ff7
commit e9364fa70f
14 changed files with 2049 additions and 1524 deletions
@@ -0,0 +1,27 @@
"""add_ssh_key_ids_to_tool_instances
Revision ID: 2026_05_29_add_ssh_key_ids_to_tool_instances
Revises: 2026_05_29_drop_ssh_key_id_from_config_profiles
Create Date: 2026-05-29 12:46:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "2026_05_29_add_ssh_key_ids_to_tool_instances"
down_revision = "2026_05_29_drop_ssh_key_id_from_config_profiles"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column(
"tool_instances",
sa.Column("ssh_key_ids", sa.JSON(), nullable=True),
)
def downgrade() -> None:
op.drop_column("tool_instances", "ssh_key_ids")
@@ -0,0 +1,32 @@
"""drop_ssh_key_id_from_config_profiles
Revision ID: 2026_05_29_drop_ssh_key_id_from_config_profiles
Revises: 069d3da4dc9b
Create Date: 2026-05-29 12:45:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "2026_05_29_drop_ssh_key_id_from_config_profiles"
down_revision = "069d3da4dc9b"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.drop_column("config_profiles", "ssh_key_id")
def downgrade() -> None:
op.add_column(
"config_profiles",
sa.Column(
"ssh_key_id",
sa.Uuid(),
sa.ForeignKey("ssh_keys.id", ondelete="SET NULL"),
nullable=True,
),
)
-7
View File
@@ -188,9 +188,6 @@ class ConfigProfileCreate(BaseModel):
git_mounts: list[GitMountItem] = Field(
default_factory=list, description="Git repository mounts"
)
ssh_key_id: str | None = Field(
default=None, description="Optional SSH key ID to mount into containers"
)
is_default: bool = Field(
default=False, description="Whether this is the default profile for its scope"
)
@@ -252,9 +249,6 @@ class ConfigProfileUpdate(BaseModel):
git_mounts: list[GitMountItem] | None = Field(
default=None, description="Git repository mounts"
)
ssh_key_id: str | None = Field(
default=None, description="Optional SSH key ID to mount into containers"
)
is_default: bool | None = Field(
default=None, description="Whether this is the default profile"
)
@@ -382,7 +376,6 @@ def _profile_to_response(
"mounts": profile.mounts or [],
"git_mounts": profile.git_mounts or [],
"files": profile.files or {},
"ssh_key_id": str(profile.ssh_key_id) if profile.ssh_key_id else None,
"is_default": profile.is_default,
"includes": [
{
+50 -34
View File
@@ -435,6 +435,9 @@ class CreateInstanceRequest(BaseModel):
config_profile_id: str | None = Field(
default=None, description="Optional config profile ID for launch"
)
ssh_key_ids: list[str] = Field(
default_factory=list, description="SSH key IDs to mount into container ~/.ssh"
)
class StartInstanceRequest(BaseModel):
@@ -445,6 +448,9 @@ class StartInstanceRequest(BaseModel):
config_profile_id: str | None = Field(
default=None, description="Config profile ID to apply, or null for none"
)
ssh_key_ids: list[str] = Field(
default_factory=list, description="SSH key IDs to mount into container ~/.ssh"
)
async def _validate_config_profile(
@@ -964,6 +970,7 @@ services:
if data.new_branch
else (data.branch if data.clone_mode == "clone" else None),
selected_config_profile_id=selected_profile_id,
ssh_key_ids=data.ssh_key_ids or None,
)
session.add(instance)
await session.commit()
@@ -1054,6 +1061,7 @@ async def list_instances(
"port": i.port,
"clone_mode": i.clone_mode,
"branch": i.branch,
"ssh_key_ids": i.ssh_key_ids or [],
"created_at": i.created_at.isoformat(),
}
)
@@ -1300,6 +1308,11 @@ async def start_instance(
instance.selected_config_profile_id = selected_profile_id
await session.commit()
# Store SSH key selection if provided
if data and data.ssh_key_ids is not None:
instance.ssh_key_ids = data.ssh_key_ids or None
await session.commit()
if not instance.compose_path or not os.path.exists(instance.compose_path):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="compose file not found"
@@ -1355,40 +1368,6 @@ async def start_instance(
working_directory = profile_hints["working_directory"]
if profile_hints.get("port_override"):
port_override = profile_hints["port_override"]
# Mount SSH key from config profile into container home dir
if resolved.ssh_key_id is not None:
ssh_key = await session.get(SSHKey, resolved.ssh_key_id)
if ssh_key:
try:
ssh_dir = prepare_ssh_key_files(
instance_dir, ssh_key, subdir="mounts/ssh/.ssh"
)
ssh_target = os.path.join(home_dir, ".ssh")
extra_volumes.append(
{
"source": ssh_dir,
"target": ssh_target,
"type": "ro",
}
)
logger.debug(
"Mounted SSH key %s for instance %s to %s",
ssh_key.name,
instance.id,
ssh_target,
)
except Exception as exc:
logger.error(
"Failed to prepare SSH key for instance %s: %s",
instance.id,
exc,
)
else:
logger.warning(
"SSH key %s not found for config profile %s",
resolved.ssh_key_id,
resolved.profile_name,
)
logger.debug(
"Applied config profile %s to instance %s (env=%d, files=%d, mounts=%d, git_mounts=%d)",
resolved.profile_name,
@@ -1422,6 +1401,43 @@ async def start_instance(
"Wrote %d config files for instance %s", len(config_files), instance.id
)
# Mount selected SSH keys into container home dir
if instance.ssh_key_ids:
for key_id in instance.ssh_key_ids:
ssh_key = await session.get(SSHKey, uuid.UUID(key_id))
if ssh_key and ssh_key.user_id == user_id:
try:
ssh_dir = prepare_ssh_key_files(
instance_dir, ssh_key, subdir=f"mounts/ssh/{key_id}/.ssh"
)
ssh_target = os.path.join(home_dir, ".ssh")
extra_volumes.append(
{
"source": ssh_dir,
"target": ssh_target,
"type": "ro",
}
)
logger.debug(
"Mounted SSH key %s for instance %s to %s",
ssh_key.name,
instance.id,
ssh_target,
)
except Exception as exc:
logger.error(
"Failed to prepare SSH key %s for instance %s: %s",
key_id,
instance.id,
exc,
)
else:
logger.warning(
"SSH key %s not found or not authorized for user %s",
key_id,
user_id,
)
# ── MANIFEST-BASED FLOW ──────────────────────────────────────
resolved_manifest = None
-5
View File
@@ -9,7 +9,6 @@ from src.models.base import Base, TimestampMixin, UUIDPrimaryKeyMixin
if TYPE_CHECKING:
from src.models.project import Project
from src.models.ssh_key import SSHKey
from src.models.tool_type import ToolType
from src.models.user import User
@@ -43,15 +42,11 @@ class ConfigProfile(UUIDPrimaryKeyMixin, TimestampMixin, Base):
git_mounts: Mapped[list] = mapped_column(
JSON, default=list, nullable=False
) # [{"remote_url": "https://github.com/user/repo.git", "source_path": ".", "target_path": "/path", "branch": "main"}, ...]
ssh_key_id: Mapped[uuid.UUID | None] = mapped_column(
UUID(), ForeignKey("ssh_keys.id", ondelete="SET NULL"), nullable=True
)
is_default: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
user: Mapped["User"] = relationship()
project: Mapped["Project | None"] = relationship()
tool_type: Mapped["ToolType | None"] = relationship()
ssh_key: Mapped["SSHKey | None"] = relationship()
includes: Mapped[list["ConfigProfileInclude"]] = relationship(
"ConfigProfileInclude",
foreign_keys="ConfigProfileInclude.profile_id",
+1
View File
@@ -59,6 +59,7 @@ class ToolInstance(UUIDPrimaryKeyMixin, TimestampMixin, Base):
selected_config_profile_id: Mapped[uuid.UUID | None] = mapped_column(
UUID(), ForeignKey("config_profiles.id", ondelete="SET NULL"), nullable=True
)
ssh_key_ids: Mapped[list[str] | None] = mapped_column(JSON, nullable=True)
tool_type: Mapped["ToolType"] = relationship()
repository: Mapped["GitRepository"] = relationship()
@@ -51,7 +51,6 @@ class ResolvedProfile:
mounts: dict[str, ResolvedMount] = field(default_factory=dict)
git_mounts: list[dict[str, Any]] = field(default_factory=list)
files: dict[str, str] = field(default_factory=dict)
ssh_key_id: uuid.UUID | None = None
env_overrides: dict[str, str] = field(default_factory=dict)
hint_overrides: dict[str, str] = field(default_factory=dict)
file_overrides: dict[str, str] = field(default_factory=dict)
@@ -319,9 +318,6 @@ async def _resolve_profile_recursive(
result.git_mounts = _merge_git_mounts(
result.git_mounts, included.git_mounts, included.profile_name
)
# Later included profile's SSH key wins
if included.ssh_key_id is not None:
result.ssh_key_id = included.ssh_key_id
# Apply the profile's own settings (selected profile overrides includes)
result.env_vars = _merge_env_vars(
@@ -353,9 +349,6 @@ async def _resolve_profile_recursive(
profile.git_mounts or [],
profile.name,
)
# Own SSH key overrides any inherited one
if profile.ssh_key_id is not None:
result.ssh_key_id = profile.ssh_key_id
return result
@@ -571,5 +564,4 @@ def resolved_profile_to_dict(resolved: ResolvedProfile) -> dict[str, Any]:
},
"git_mounts": resolved.git_mounts,
"included_profiles": resolved.included_profiles,
"ssh_key_id": str(resolved.ssh_key_id) if resolved.ssh_key_id else None,
}