devnomads-cli 0.15.0__tar.gz → 0.16.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/PKG-INFO +26 -9
  2. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/README.md +25 -8
  3. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/devnomads_cli.egg-info/PKG-INFO +26 -9
  4. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/devnomads_cli.egg-info/SOURCES.txt +1 -0
  5. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/dncli.py +446 -30
  6. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/pyproject.toml +1 -1
  7. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_sites_publish.py +8 -0
  8. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_sites_ssh.py +38 -0
  9. devnomads_cli-0.16.0/tests/test_ssh_keys.py +309 -0
  10. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/LICENSE +0 -0
  11. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/devnomads_cli.egg-info/dependency_links.txt +0 -0
  12. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/devnomads_cli.egg-info/entry_points.txt +0 -0
  13. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/devnomads_cli.egg-info/requires.txt +0 -0
  14. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/devnomads_cli.egg-info/top_level.txt +0 -0
  15. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/setup.cfg +0 -0
  16. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_agent_features.py +0 -0
  17. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_cert.py +0 -0
  18. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_cli.py +0 -0
  19. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_config.py +0 -0
  20. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_generate.py +0 -0
  21. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_generated_cli.py +0 -0
  22. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_helpers.py +0 -0
  23. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_hook.py +0 -0
  24. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_transfer.py +0 -0
  25. {devnomads_cli-0.15.0 → devnomads_cli-0.16.0}/tests/test_versions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: devnomads-cli
3
- Version: 0.15.0
3
+ Version: 0.16.0
4
4
  Summary: Manage your DevNomads services from the command line
5
5
  Author-email: DevNomads <support@devnomads.nl>
6
6
  License: MIT
@@ -111,7 +111,8 @@ the full detail for one group, for scripts and AI agents.
111
111
  ## Logging in to a site
112
112
 
113
113
  `dncli sites ssh` opens an SSH session as the site's system user,
114
- `site<service_id>`, so you don't need to know that name:
114
+ `site` + the service id padded to five digits (service 2467 is
115
+ `site02467`), so you don't need to know that name:
115
116
 
116
117
  ```sh
117
118
  dncli sites ssh example.com
@@ -124,10 +125,25 @@ on several hosts (an HA cluster) asks which one; pick it with `--host`
124
125
  to skip the question, for example in a script. Anything after `--`
125
126
  goes to ssh: extra options (`-- -p 2222`) or a remote command.
126
127
 
127
- ssh logs in with your SSH key when the site has it (`dncli sites keys
128
- attach`); otherwise ssh itself asks for the site's password. dncli never
129
- sees or stores that password. Scripts and other runs without a terminal
130
- cannot answer a password prompt, so they need key login.
128
+ ssh logs in with your SSH key when the site has it; otherwise ssh itself
129
+ asks for the site's password. dncli never sees or stores that password.
130
+ Scripts and other runs without a terminal cannot answer a password
131
+ prompt, so they need key login.
132
+
133
+ dncli helps with the key. Before it connects, it compares the public
134
+ keys you have here (the ssh agent's, and the `~/.ssh/id_*` files ssh
135
+ would use) with the keys attached to the site. When none of yours is
136
+ attached, it offers to attach one, adding it to your DevNomads account
137
+ first if it isn't there yet. `--attach-key` does that without asking
138
+ (for scripts), `--no-attach-key` skips the check. Only public keys are
139
+ read and sent; your private key never leaves `~/.ssh`. You can also do
140
+ it on its own:
141
+
142
+ ```sh
143
+ dncli sites keys attach-local example.com # add to the account if needed, then attach
144
+ dncli keys add-local # only add it to your account
145
+ dncli keys add-local --key ~/.ssh/deploy.pub --name ci
146
+ ```
131
147
 
132
148
  ## Publishing a site
133
149
 
@@ -140,7 +156,7 @@ dncli sites publish example.com ./dist # new and changed files
140
156
  dncli sites publish example.com ./dist --delete # also remove files not in ./dist
141
157
  ```
142
158
 
143
- Files go to `/home/site<service_id>/domains/<domain>/public_html`. `.git/`
159
+ Files go to `/home/site<NNNNN>/domains/<domain>/public_html`. `.git/`
144
160
  is never uploaded; `--exclude` leaves out more (repeat it). You need
145
161
  rsync locally and on the server.
146
162
 
@@ -188,8 +204,9 @@ of them.
188
204
 
189
205
  **From a CI pipeline.** A pipeline has no terminal, so ssh cannot ask
190
206
  for a password or whether to trust a host it has not seen before. Give
191
- the pipeline an SSH key that is attached to the site (`dncli sites keys
192
- attach`), the hosts' keys in `known_hosts` and the API key in `DN_API_KEY`:
207
+ the pipeline an SSH key that is attached to the site (attach it once with
208
+ `dncli sites keys attach-local example.com --key deploy.pub`), the hosts'
209
+ keys in `known_hosts` and the API key in `DN_API_KEY`:
193
210
 
194
211
  ```sh
195
212
  mkdir -p ~/.ssh && ssh-keyscan web01.example.com >> ~/.ssh/known_hosts
@@ -95,7 +95,8 @@ the full detail for one group, for scripts and AI agents.
95
95
  ## Logging in to a site
96
96
 
97
97
  `dncli sites ssh` opens an SSH session as the site's system user,
98
- `site<service_id>`, so you don't need to know that name:
98
+ `site` + the service id padded to five digits (service 2467 is
99
+ `site02467`), so you don't need to know that name:
99
100
 
100
101
  ```sh
101
102
  dncli sites ssh example.com
@@ -108,10 +109,25 @@ on several hosts (an HA cluster) asks which one; pick it with `--host`
108
109
  to skip the question, for example in a script. Anything after `--`
109
110
  goes to ssh: extra options (`-- -p 2222`) or a remote command.
110
111
 
111
- ssh logs in with your SSH key when the site has it (`dncli sites keys
112
- attach`); otherwise ssh itself asks for the site's password. dncli never
113
- sees or stores that password. Scripts and other runs without a terminal
114
- cannot answer a password prompt, so they need key login.
112
+ ssh logs in with your SSH key when the site has it; otherwise ssh itself
113
+ asks for the site's password. dncli never sees or stores that password.
114
+ Scripts and other runs without a terminal cannot answer a password
115
+ prompt, so they need key login.
116
+
117
+ dncli helps with the key. Before it connects, it compares the public
118
+ keys you have here (the ssh agent's, and the `~/.ssh/id_*` files ssh
119
+ would use) with the keys attached to the site. When none of yours is
120
+ attached, it offers to attach one, adding it to your DevNomads account
121
+ first if it isn't there yet. `--attach-key` does that without asking
122
+ (for scripts), `--no-attach-key` skips the check. Only public keys are
123
+ read and sent; your private key never leaves `~/.ssh`. You can also do
124
+ it on its own:
125
+
126
+ ```sh
127
+ dncli sites keys attach-local example.com # add to the account if needed, then attach
128
+ dncli keys add-local # only add it to your account
129
+ dncli keys add-local --key ~/.ssh/deploy.pub --name ci
130
+ ```
115
131
 
116
132
  ## Publishing a site
117
133
 
@@ -124,7 +140,7 @@ dncli sites publish example.com ./dist # new and changed files
124
140
  dncli sites publish example.com ./dist --delete # also remove files not in ./dist
125
141
  ```
126
142
 
127
- Files go to `/home/site<service_id>/domains/<domain>/public_html`. `.git/`
143
+ Files go to `/home/site<NNNNN>/domains/<domain>/public_html`. `.git/`
128
144
  is never uploaded; `--exclude` leaves out more (repeat it). You need
129
145
  rsync locally and on the server.
130
146
 
@@ -172,8 +188,9 @@ of them.
172
188
 
173
189
  **From a CI pipeline.** A pipeline has no terminal, so ssh cannot ask
174
190
  for a password or whether to trust a host it has not seen before. Give
175
- the pipeline an SSH key that is attached to the site (`dncli sites keys
176
- attach`), the hosts' keys in `known_hosts` and the API key in `DN_API_KEY`:
191
+ the pipeline an SSH key that is attached to the site (attach it once with
192
+ `dncli sites keys attach-local example.com --key deploy.pub`), the hosts'
193
+ keys in `known_hosts` and the API key in `DN_API_KEY`:
177
194
 
178
195
  ```sh
179
196
  mkdir -p ~/.ssh && ssh-keyscan web01.example.com >> ~/.ssh/known_hosts
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: devnomads-cli
3
- Version: 0.15.0
3
+ Version: 0.16.0
4
4
  Summary: Manage your DevNomads services from the command line
5
5
  Author-email: DevNomads <support@devnomads.nl>
6
6
  License: MIT
@@ -111,7 +111,8 @@ the full detail for one group, for scripts and AI agents.
111
111
  ## Logging in to a site
112
112
 
113
113
  `dncli sites ssh` opens an SSH session as the site's system user,
114
- `site<service_id>`, so you don't need to know that name:
114
+ `site` + the service id padded to five digits (service 2467 is
115
+ `site02467`), so you don't need to know that name:
115
116
 
116
117
  ```sh
117
118
  dncli sites ssh example.com
@@ -124,10 +125,25 @@ on several hosts (an HA cluster) asks which one; pick it with `--host`
124
125
  to skip the question, for example in a script. Anything after `--`
125
126
  goes to ssh: extra options (`-- -p 2222`) or a remote command.
126
127
 
127
- ssh logs in with your SSH key when the site has it (`dncli sites keys
128
- attach`); otherwise ssh itself asks for the site's password. dncli never
129
- sees or stores that password. Scripts and other runs without a terminal
130
- cannot answer a password prompt, so they need key login.
128
+ ssh logs in with your SSH key when the site has it; otherwise ssh itself
129
+ asks for the site's password. dncli never sees or stores that password.
130
+ Scripts and other runs without a terminal cannot answer a password
131
+ prompt, so they need key login.
132
+
133
+ dncli helps with the key. Before it connects, it compares the public
134
+ keys you have here (the ssh agent's, and the `~/.ssh/id_*` files ssh
135
+ would use) with the keys attached to the site. When none of yours is
136
+ attached, it offers to attach one, adding it to your DevNomads account
137
+ first if it isn't there yet. `--attach-key` does that without asking
138
+ (for scripts), `--no-attach-key` skips the check. Only public keys are
139
+ read and sent; your private key never leaves `~/.ssh`. You can also do
140
+ it on its own:
141
+
142
+ ```sh
143
+ dncli sites keys attach-local example.com # add to the account if needed, then attach
144
+ dncli keys add-local # only add it to your account
145
+ dncli keys add-local --key ~/.ssh/deploy.pub --name ci
146
+ ```
131
147
 
132
148
  ## Publishing a site
133
149
 
@@ -140,7 +156,7 @@ dncli sites publish example.com ./dist # new and changed files
140
156
  dncli sites publish example.com ./dist --delete # also remove files not in ./dist
141
157
  ```
142
158
 
143
- Files go to `/home/site<service_id>/domains/<domain>/public_html`. `.git/`
159
+ Files go to `/home/site<NNNNN>/domains/<domain>/public_html`. `.git/`
144
160
  is never uploaded; `--exclude` leaves out more (repeat it). You need
145
161
  rsync locally and on the server.
146
162
 
@@ -188,8 +204,9 @@ of them.
188
204
 
189
205
  **From a CI pipeline.** A pipeline has no terminal, so ssh cannot ask
190
206
  for a password or whether to trust a host it has not seen before. Give
191
- the pipeline an SSH key that is attached to the site (`dncli sites keys
192
- attach`), the hosts' keys in `known_hosts` and the API key in `DN_API_KEY`:
207
+ the pipeline an SSH key that is attached to the site (attach it once with
208
+ `dncli sites keys attach-local example.com --key deploy.pub`), the hosts'
209
+ keys in `known_hosts` and the API key in `DN_API_KEY`:
193
210
 
194
211
  ```sh
195
212
  mkdir -p ~/.ssh && ssh-keyscan web01.example.com >> ~/.ssh/known_hosts
@@ -18,5 +18,6 @@ tests/test_helpers.py
18
18
  tests/test_hook.py
19
19
  tests/test_sites_publish.py
20
20
  tests/test_sites_ssh.py
21
+ tests/test_ssh_keys.py
21
22
  tests/test_transfer.py
22
23
  tests/test_versions.py
@@ -21,6 +21,7 @@ from __future__ import annotations
21
21
  import base64
22
22
  import configparser
23
23
  import csv
24
+ import getpass
24
25
  import hashlib
25
26
  import hmac
26
27
  import io
@@ -32,6 +33,7 @@ import re
32
33
  import secrets
33
34
  import shlex
34
35
  import shutil
36
+ import socket
35
37
  import stat
36
38
  import subprocess # nosec B404 - `dncli upgrade`, and ssh/rsync for sites
37
39
  import sys
@@ -68,7 +70,7 @@ from rich.markup import escape
68
70
  from rich.table import Table
69
71
  from typer.core import TyperGroup
70
72
 
71
- __version__ = "0.15.0"
73
+ __version__ = "0.16.0"
72
74
 
73
75
  # Distribution names, for reporting versions via `dncli version`.
74
76
  CLI_PACKAGE = "devnomads-cli"
@@ -1626,6 +1628,8 @@ def main(
1626
1628
  # Handwritten commands that change something (the generated ones say so in
1627
1629
  # COMMAND_META); for `dncli commands`.
1628
1630
  HANDWRITTEN_CHANGES = {
1631
+ "keys add-local",
1632
+ "sites keys attach-local",
1629
1633
  "sites publish",
1630
1634
  "sites rollback",
1631
1635
  "sites ssh",
@@ -3957,7 +3961,8 @@ agent.
3957
3961
  `service_id` and an `entity` (its domain or name). `dncli services list`
3958
3962
  shows all of them with their `type`.
3959
3963
  - **Site system user**: every site runs as the system user
3960
- `site<service_id>` (service 12055 is `site12055`), which is also its
3964
+ `site` + its service id padded to five digits (service 2467 is `site02467`,
3965
+ 12055 is `site12055`), which is also its
3961
3966
  SFTP/SSH login. It is always built from the service id that
3962
3967
  `dncli sites show` returns, never from another id. `dncli sites ssh
3963
3968
  <site>` logs in as that user (see "Common tasks").
@@ -4060,18 +4065,21 @@ dncli databases users create 2 --client-id 12 --username shop --generate-passwor
4060
4065
  dncli databases permissions create <database> --user-id shop --permissions all # service id or entity
4061
4066
  ```
4062
4067
 
4063
- Run a command on a site over SSH (as `site<service_id>`), on the host the
4068
+ Run a command on a site over SSH (as `site<NNNNN>`, see above), on the host the
4064
4069
  API lists for the site (`site.hosts` in `dncli sites show`). A site on
4065
4070
  several hosts (an HA cluster) needs `--host <one of them>` without a
4066
4071
  terminal. Without `--` and a command it opens an interactive shell, which an
4067
4072
  agent cannot use. ssh logs in with the user's SSH key when the site has it,
4068
4073
  else it asks for the site's password, which an agent cannot answer either
4069
- (dncli never handles that password). So before running commands, check
4070
- `dncli sites show <site> --out json` for the user's key under `keys`; if it
4071
- is missing, propose `dncli sites keys attach <site> --key-id <key>` (key
4072
- from `dncli keys list`, by id or name):
4074
+ (dncli never handles that password). Without a terminal, dncli prints a note
4075
+ when none of the local keys is attached. Attaching a key grants access to the
4076
+ site, so ask the user first, then run `dncli sites keys attach-local <site>`:
4077
+ it adds the local public key to their account when it is missing and attaches
4078
+ it (or pass `--attach-key` to `sites ssh` / `sites publish`). `dncli keys
4079
+ add-local` only adds it to the account. Only public keys are read and sent:
4073
4080
 
4074
4081
  ```sh
4082
+ dncli sites keys attach-local example.com --dry-run # what it would add and attach
4075
4083
  dncli sites ssh example.com --dry-run -- ls -la # prints the ssh command
4076
4084
  dncli sites ssh example.com --host web01.example.com -- php -v # HA site
4077
4085
  dncli sites ssh example.com -- wp cache flush
@@ -4086,7 +4094,7 @@ dncli sites publish example.com ./dist # upload new and changed
4086
4094
  dncli sites publish example.com ./dist --delete --yes # also remove files not in ./dist
4087
4095
  ```
4088
4096
 
4089
- Files go to `/home/site<service_id>/domains/<domain>/public_html`. A site is
4097
+ Files go to `/home/site<NNNNN>/domains/<domain>/public_html`. A site is
4090
4098
  in one of two modes, and its document root says which:
4091
4099
 
4092
4100
  - **Plain** (document root e.g. `/public`): files are uploaded into
@@ -5646,7 +5654,7 @@ gen_servers = typer.Typer(
5646
5654
  app.add_typer(gen_servers, name="servers")
5647
5655
  gen_sites = typer.Typer(
5648
5656
  cls=PrefixGroup,
5649
- help="PHP web hosting sites. Each runs as system user site<service_id> (e.g. site12055), also its SFTP/SSH login.",
5657
+ help="PHP web hosting sites. Each runs as system user site + its service id padded to five digits (service 2467 is site02467), also its SFTP/SSH login.",
5650
5658
  no_args_is_help=True,
5651
5659
  )
5652
5660
  app.add_typer(gen_sites, name="sites")
@@ -11025,7 +11033,7 @@ def gen_services_sites_show(
11025
11033
  ) -> None:
11026
11034
  """Show a site.
11027
11035
 
11028
- The site runs as system user site<service_id> (service 12055 is site12055), which is also its SFTP/SSH login.
11036
+ The site runs as system user site + its service id padded to five digits (service 2467 is site02467, 12055 is site12055), which is also its SFTP/SSH login.
11029
11037
  """
11030
11038
 
11031
11039
  _generated_call(
@@ -11060,7 +11068,7 @@ def gen_services_sites_store(
11060
11068
  ),
11061
11069
  password: str | None = typer.Option(
11062
11070
  None,
11063
- help="SFTP/SSH password of the site's system user site<service_id>: at least 8 characters with upper and lower case letters, a number and a symbol. Pass - to read it from stdin. Required unless --generate-password is given.",
11071
+ help="SFTP/SSH password of the site's system user (site + the service id padded to five digits, e.g. site02467): at least 8 characters with upper and lower case letters, a number and a symbol. Pass - to read it from stdin. Required unless --generate-password is given.",
11064
11072
  ),
11065
11073
  generate_password: bool = typer.Option(
11066
11074
  False,
@@ -11193,7 +11201,7 @@ def gen_services_sites_update(
11193
11201
  ),
11194
11202
  password: str | None = typer.Option(
11195
11203
  None,
11196
- help="SFTP/SSH password of the site's system user site<service_id>: at least 8 characters with upper and lower case letters, a number and a symbol. Pass - to read it from stdin.",
11204
+ help="SFTP/SSH password of the site's system user (site + the service id padded to five digits, e.g. site02467): at least 8 characters with upper and lower case letters, a number and a symbol. Pass - to read it from stdin.",
11197
11205
  ),
11198
11206
  generate_password: bool = typer.Option(
11199
11207
  False,
@@ -11795,13 +11803,15 @@ class SiteLogin:
11795
11803
  document_root: str
11796
11804
  hosts: list[str] # the hosts this command works on, from the API
11797
11805
  host: str # the one host this login is for
11806
+ keys: list[str] = field(default_factory=list) # attached keys' bodies
11798
11807
 
11799
11808
  def on(self, host: str) -> SiteLogin:
11800
11809
  return replace(self, host=host)
11801
11810
 
11802
11811
  @property
11803
11812
  def user(self) -> str:
11804
- return f"site{self.service_id}"
11813
+ # the service id padded to five digits: service 2467 is site02467
11814
+ return f"site{self.service_id.zfill(5)}"
11805
11815
 
11806
11816
  @property
11807
11817
  def target(self) -> str:
@@ -11848,7 +11858,12 @@ def site_login(state: AppState, service_id: str, host: str | None) -> SiteLogin:
11848
11858
  )
11849
11859
  hosts = [host]
11850
11860
  document_root = str(_dig(site, "site.document_root") or "/")
11851
- return SiteLogin(str(sid), domain, cluster_id, document_root, hosts, hosts[0])
11861
+ keys = [
11862
+ blob
11863
+ for row in site.get("keys") or []
11864
+ if isinstance(row, dict) and (blob := _key_blob(row.get("key")))
11865
+ ]
11866
+ return SiteLogin(str(sid), domain, cluster_id, document_root, hosts, hosts[0], keys)
11852
11867
 
11853
11868
 
11854
11869
  def _choose_host(login: SiteLogin) -> SiteLogin:
@@ -11913,6 +11928,7 @@ def sites_ssh(
11913
11928
  "several (see `dncli sites show`).",
11914
11929
  ),
11915
11930
  ] = None,
11931
+ attach_key: AttachKeyOption = None,
11916
11932
  dry_run: Annotated[
11917
11933
  bool,
11918
11934
  typer.Option("--dry-run", help="Print the ssh command instead of running it."),
@@ -11920,17 +11936,21 @@ def sites_ssh(
11920
11936
  ) -> None:
11921
11937
  """Log in to a site over SSH as its system user.
11922
11938
 
11923
- The user is site<service_id>, the host the one the API lists for the
11939
+ The user is site + the service id padded to five digits (site02467),
11940
+ the host the one the API lists for the
11924
11941
  site. A site that runs on several hosts (an HA cluster) asks which one;
11925
11942
  without a terminal, pick it with --host.
11926
11943
 
11927
- ssh logs in with your SSH key when the site has it (dncli sites keys
11928
- attach), else ssh itself asks for the site's password; dncli never sees
11929
- or stores it. Without a terminal (scripts, agents) ssh cannot ask, so
11930
- only key login works there."""
11944
+ ssh logs in with your SSH key when the site has it, else ssh itself
11945
+ asks for the site's password; dncli never sees or stores it. When none
11946
+ of your local keys is attached, dncli offers to attach one (adding it
11947
+ to your account first); --attach-key does that without asking. Without
11948
+ a terminal (scripts, agents) ssh cannot ask for a password, so only key
11949
+ login works there."""
11931
11950
 
11932
11951
  state = state_from(ctx)
11933
11952
  login = _choose_host(site_login(state, service_id, host))
11953
+ ensure_site_key(state, login, attach_key, dry_run)
11934
11954
  argv = ["ssh", login.target, *(ssh_args or [])]
11935
11955
  if dry_run:
11936
11956
  sys.stdout.write(shlex.join(argv) + "\n")
@@ -11948,6 +11968,389 @@ def sites_ssh(
11948
11968
  raise typer.Exit(code=result.returncode)
11949
11969
 
11950
11970
 
11971
+ # ---------------------------------------------------------------------------
11972
+ # Local SSH keys: the public keys ssh would log in with (the ssh agent's,
11973
+ # then the IdentityFiles `ssh -G` names for the host), and getting one onto
11974
+ # the DevNomads account and attached to a site. Only public keys are read
11975
+ # and sent; dncli never opens a private key.
11976
+
11977
+ _KEY_TYPE = re.compile(
11978
+ r"^(ssh-(ed25519|rsa|dss)|ecdsa-sha2-nistp\d+|sk-(ssh-ed25519|ecdsa-sha2-nistp256)@openssh\.com)$"
11979
+ )
11980
+
11981
+
11982
+ @dataclass(frozen=True)
11983
+ class LocalKey:
11984
+ """A public key: its type, base64 body, comment and where it came from."""
11985
+
11986
+ type: str
11987
+ blob: str
11988
+ comment: str
11989
+ source: str # "ssh agent" or the .pub file
11990
+
11991
+ @property
11992
+ def text(self) -> str:
11993
+ return f"{self.type} {self.blob}" + (f" {self.comment}" if self.comment else "")
11994
+
11995
+ @property
11996
+ def fingerprint(self) -> str:
11997
+ digest = hashlib.sha256(base64.b64decode(self.blob)).digest()
11998
+ return "SHA256:" + base64.b64encode(digest).decode().rstrip("=")
11999
+
12000
+ def describe(self) -> str:
12001
+ return f"{self.source} ({self.type} {self.fingerprint})"
12002
+
12003
+
12004
+ def parse_public_key(text: str, source: str = "") -> LocalKey | None:
12005
+ """An OpenSSH public key line, or None when it is not one."""
12006
+
12007
+ parts = text.strip().split(None, 2)
12008
+ if len(parts) < 2 or not _KEY_TYPE.match(parts[0]):
12009
+ return None
12010
+ try:
12011
+ base64.b64decode(parts[1], validate=True)
12012
+ except ValueError:
12013
+ return None
12014
+ return LocalKey(
12015
+ parts[0], parts[1], parts[2].strip() if len(parts) > 2 else "", source
12016
+ )
12017
+
12018
+
12019
+ def _key_blob(text: Any) -> str | None:
12020
+ key = parse_public_key(str(text or ""))
12021
+ return key.blob if key else None
12022
+
12023
+
12024
+ def _quiet_output(argv: list[str]) -> str:
12025
+ """A local helper's stdout, or "" when it fails."""
12026
+
12027
+ try:
12028
+ result = subprocess.run( # nosec B603 - fixed argv, no shell
12029
+ argv,
12030
+ stdin=subprocess.DEVNULL,
12031
+ stdout=subprocess.PIPE,
12032
+ stderr=subprocess.DEVNULL,
12033
+ text=True,
12034
+ timeout=10,
12035
+ check=False,
12036
+ )
12037
+ except (OSError, subprocess.SubprocessError):
12038
+ return ""
12039
+ return result.stdout if result.returncode == 0 else ""
12040
+
12041
+
12042
+ DEFAULT_IDENTITIES = [
12043
+ "id_ed25519",
12044
+ "id_ecdsa",
12045
+ "id_ed25519_sk",
12046
+ "id_ecdsa_sk",
12047
+ "id_rsa",
12048
+ ]
12049
+
12050
+
12051
+ def local_ssh_keys(host: str | None = None) -> list[LocalKey]:
12052
+ """The public keys ssh offers when it logs in to ``host``: the agent's
12053
+ first, then those of the identity files that exist, without repeats."""
12054
+
12055
+ keys: list[LocalKey] = []
12056
+ if ssh_add := shutil.which("ssh-add"):
12057
+ for line in _quiet_output([ssh_add, "-L"]).splitlines():
12058
+ if key := parse_public_key(line, "ssh agent"):
12059
+ keys.append(key)
12060
+ files: list[Path] = []
12061
+ ssh = shutil.which("ssh")
12062
+ config = _quiet_output([ssh, "-G", host or "localhost"]) if ssh else ""
12063
+ for line in config.splitlines():
12064
+ option, _, value = line.partition(" ")
12065
+ if option.lower() == "identityfile" and value.strip():
12066
+ files.append(Path(os.path.expanduser(value.strip())))
12067
+ if not files:
12068
+ files = [Path.home() / ".ssh" / name for name in DEFAULT_IDENTITIES]
12069
+ for private in files:
12070
+ public = Path(f"{private}.pub")
12071
+ if not (private.exists() and public.is_file()):
12072
+ continue
12073
+ try:
12074
+ text = public.read_text(errors="replace")
12075
+ except OSError:
12076
+ continue
12077
+ if key := parse_public_key(text, str(public)):
12078
+ keys.append(key)
12079
+ unique: dict[str, LocalKey] = {}
12080
+ for key in keys:
12081
+ unique.setdefault(key.blob, key)
12082
+ return list(unique.values())
12083
+
12084
+
12085
+ def _pick_local_keys(path: Path | None, host: str | None = None) -> list[LocalKey]:
12086
+ """--key's public key, else every local key in ssh's order."""
12087
+
12088
+ if path is not None:
12089
+ path = path.expanduser()
12090
+ public = path if path.suffix == ".pub" else Path(f"{path}.pub")
12091
+ try:
12092
+ key = parse_public_key(public.read_text(errors="replace"), str(public))
12093
+ except OSError as exc:
12094
+ raise CliError(
12095
+ f"cannot read {public}: {exc.strerror}", kind="usage"
12096
+ ) from exc
12097
+ if key is None:
12098
+ raise CliError(f"{public} is not an SSH public key", kind="usage")
12099
+ return [key]
12100
+ keys = local_ssh_keys(host)
12101
+ if not keys:
12102
+ raise CliError(
12103
+ "no SSH key found here (ssh agent or ~/.ssh); create one with "
12104
+ "`ssh-keygen -t ed25519`, or pass --key",
12105
+ kind="not_found",
12106
+ )
12107
+ return keys
12108
+
12109
+
12110
+ def _default_key_name(taken: set[str]) -> str:
12111
+ try:
12112
+ user = getpass.getuser()
12113
+ except Exception: # no user name in the environment
12114
+ user = "dncli"
12115
+ machine = socket.gethostname().split(".")[0] or "host"
12116
+ base = f"{user}@{machine}"
12117
+ name, number = base, 2
12118
+ while name in taken:
12119
+ name, number = f"{base}-{number}", number + 1
12120
+ return name
12121
+
12122
+
12123
+ @dataclass
12124
+ class KeyPlan:
12125
+ """Which local key to use, and whether the account has it already."""
12126
+
12127
+ key: LocalKey
12128
+ account: dict[str, Any] | None # the account's key, when it is there
12129
+ name: str # its name on the account, existing or to be
12130
+
12131
+ @property
12132
+ def action(self) -> str:
12133
+ if self.account is not None:
12134
+ return f"attach your SSH key {self.key.describe()}, on your account as {self.name},"
12135
+ return (
12136
+ f"add your SSH key {self.key.describe()} to your DevNomads account "
12137
+ f"as {self.name} and attach it"
12138
+ )
12139
+
12140
+
12141
+ def plan_key(state: AppState, keys: list[LocalKey], name: str | None) -> KeyPlan:
12142
+ """The first local key the account has, else the first local key, to be
12143
+ added under ``name`` (default: user@machine, made unique)."""
12144
+
12145
+ rows = _list_rows(state, "/keys")
12146
+ by_blob = {_key_blob(row.get("key")): row for row in rows}
12147
+ for key in keys:
12148
+ if (row := by_blob.get(key.blob)) is not None:
12149
+ return KeyPlan(key, row, str(row.get("name") or row.get("id")))
12150
+ taken = {str(row.get("name")) for row in rows}
12151
+ return KeyPlan(keys[0], None, name or _default_key_name(taken))
12152
+
12153
+
12154
+ def add_account_key(state: AppState, plan: KeyPlan) -> dict[str, Any]:
12155
+ """The account's key for the plan, added when it is not there yet."""
12156
+
12157
+ if plan.account is not None:
12158
+ return plan.account
12159
+ created = get_client(state).request(
12160
+ "POST", "/keys", json_body={"name": plan.name, "key": plan.key.text}
12161
+ )
12162
+ if not isinstance(created, dict) or "id" not in created:
12163
+ raise CliError("the API did not return the new SSH key")
12164
+ state.lookup_cache.pop("/keys", None)
12165
+ err_console.print(
12166
+ f"added {escape(plan.key.describe())} to your account as {escape(plan.name)}"
12167
+ )
12168
+ return created
12169
+
12170
+
12171
+ def attach_site_key(
12172
+ state: AppState, login: SiteLogin, key_id: Any, timeout: int
12173
+ ) -> None:
12174
+ deadline = time.monotonic() + timeout
12175
+ response = get_client(state).send(
12176
+ "POST",
12177
+ f"/services/sites/{login.service_id}/keys",
12178
+ json_body={"key_id": key_id},
12179
+ timeout=timeout,
12180
+ )
12181
+ _wait_jobs(state, response, deadline, f"attaching the SSH key to {login.domain}")
12182
+
12183
+
12184
+ def ensure_site_key(
12185
+ state: AppState,
12186
+ login: SiteLogin,
12187
+ attach: bool | None,
12188
+ dry_run: bool = False,
12189
+ timeout: int = 300,
12190
+ ) -> None:
12191
+ """Before logging in: when none of the local keys is attached to the
12192
+ site, offer to attach one (adding it to the account first if needed).
12193
+ ``attach``: None asks at a terminal, True does it, False skips."""
12194
+
12195
+ if attach is False:
12196
+ return
12197
+ keys = local_ssh_keys(login.hosts[0])
12198
+ if not keys:
12199
+ if attach:
12200
+ raise CliError(
12201
+ "--attach-key: no SSH key found here (ssh agent or ~/.ssh); "
12202
+ "create one with `ssh-keygen -t ed25519`",
12203
+ kind="not_found",
12204
+ )
12205
+ return
12206
+ if any(key.blob in login.keys for key in keys):
12207
+ return
12208
+ plan = plan_key(state, keys, None)
12209
+ action = f"{plan.action} to {login.domain}"
12210
+ if dry_run:
12211
+ err_console.print(f"dry run: would {escape(action)}", soft_wrap=True)
12212
+ return
12213
+ if attach is None:
12214
+ if not stdin_is_terminal():
12215
+ err_console.print(
12216
+ f"note: none of your SSH keys is attached to {escape(login.domain)}, "
12217
+ f"so ssh needs the site's password; --attach-key would {escape(action)}",
12218
+ soft_wrap=True,
12219
+ )
12220
+ return
12221
+ err_console.print(
12222
+ f"None of your SSH keys is attached to {escape(login.domain)}.",
12223
+ soft_wrap=True,
12224
+ )
12225
+ if not typer.confirm(
12226
+ f"{action[0].upper()}{action[1:]}?", default=True, err=True
12227
+ ):
12228
+ err_console.print("ssh asks for the site's password instead")
12229
+ return
12230
+ account = add_account_key(state, plan)
12231
+ attach_site_key(state, login, account["id"], timeout)
12232
+ login.keys.append(plan.key.blob)
12233
+ err_console.print(f"attached {escape(plan.name)} to {escape(login.domain)}")
12234
+
12235
+
12236
+ AttachKeyOption = Annotated[
12237
+ bool | None,
12238
+ typer.Option(
12239
+ "--attach-key/--no-attach-key",
12240
+ help="When none of your local SSH keys is attached to the site: attach "
12241
+ "one, adding it to your account first if needed (--attach-key), or "
12242
+ "don't check (--no-attach-key). Default: ask at a terminal.",
12243
+ ),
12244
+ ]
12245
+ KeyFileOption = Annotated[
12246
+ Path | None,
12247
+ typer.Option(
12248
+ "--key",
12249
+ help="Public key file to use, e.g. ~/.ssh/id_ed25519.pub; default: the "
12250
+ "ssh agent's first key, else the first of ~/.ssh/id_* ssh uses.",
12251
+ ),
12252
+ ]
12253
+ KeyNameOption = Annotated[
12254
+ str | None,
12255
+ typer.Option(
12256
+ "--name",
12257
+ help="Name for the key on your account when it is added; default: "
12258
+ "user@machine.",
12259
+ ),
12260
+ ]
12261
+
12262
+
12263
+ @gen_keys.command("add-local")
12264
+ def keys_add_local(
12265
+ ctx: typer.Context,
12266
+ key: KeyFileOption = None,
12267
+ name: KeyNameOption = None,
12268
+ dry_run: bool = _DRY_RUN_OPT,
12269
+ output: OutputOption = None,
12270
+ columns: ColumnsOption = None,
12271
+ ) -> None:
12272
+ """Add your local SSH public key to your DevNomads account.
12273
+
12274
+ Takes the ssh agent's first key, else the first of ~/.ssh/id_* that ssh
12275
+ would use, or --key. A key the account already has (under any name) is
12276
+ not added again. Shows the account's key either way. Only the public
12277
+ key is read and sent."""
12278
+
12279
+ state = state_from(ctx, output, columns)
12280
+ plan = plan_key(state, _pick_local_keys(key), name)
12281
+ if plan.account is not None:
12282
+ err_console.print(
12283
+ f"{escape(plan.key.describe())} is already on your account as "
12284
+ f"{escape(plan.name)}"
12285
+ )
12286
+ render(state, plan.account)
12287
+ return
12288
+ if dry_run:
12289
+ render(
12290
+ state,
12291
+ {
12292
+ "dry_run": True,
12293
+ "method": "POST",
12294
+ "path": "/keys",
12295
+ "body": {"name": plan.name, "key": plan.key.text},
12296
+ },
12297
+ )
12298
+ return
12299
+ render(state, add_account_key(state, plan))
12300
+
12301
+
12302
+ @gen_sites_keys.command("attach-local")
12303
+ def sites_keys_attach_local(
12304
+ ctx: typer.Context,
12305
+ service_id: SiteArgument,
12306
+ key: KeyFileOption = None,
12307
+ name: KeyNameOption = None,
12308
+ dry_run: bool = _DRY_RUN_OPT,
12309
+ timeout: int = _TIMEOUT_OPT,
12310
+ ) -> None:
12311
+ """Attach your local SSH key to a site, so ssh logs in without a password.
12312
+
12313
+ Adds the key to your account first when it is not there yet, then
12314
+ attaches it and waits until that is done. Takes the key ssh would use
12315
+ for the site's host (the ssh agent's, else ~/.ssh/id_*), or --key.
12316
+ Nothing happens when one of your keys is attached already."""
12317
+
12318
+ state = state_from(ctx)
12319
+ login = site_login(state, service_id, None)
12320
+ keys = _pick_local_keys(key, login.hosts[0])
12321
+ attached = next((k for k in keys if k.blob in login.keys), None)
12322
+ if attached is not None:
12323
+ err_console.print(
12324
+ f"{escape(attached.describe())} is already attached to {escape(login.domain)}"
12325
+ )
12326
+ return
12327
+ plan = plan_key(state, keys, name)
12328
+ if dry_run:
12329
+ requests: list[dict[str, Any]] = []
12330
+ if plan.account is None:
12331
+ requests.append(
12332
+ {
12333
+ "method": "POST",
12334
+ "path": "/keys",
12335
+ "body": {"name": plan.name, "key": plan.key.text},
12336
+ }
12337
+ )
12338
+ requests.append(
12339
+ {
12340
+ "method": "POST",
12341
+ "path": f"/services/sites/{login.service_id}/keys",
12342
+ "body": {
12343
+ "key_id": plan.account["id"] if plan.account else "<the new key>"
12344
+ },
12345
+ }
12346
+ )
12347
+ render(state, {"dry_run": True, "requests": requests})
12348
+ return
12349
+ account = add_account_key(state, plan)
12350
+ attach_site_key(state, login, account["id"], timeout)
12351
+ err_console.print(f"attached {escape(plan.name)} to {escape(login.domain)}")
12352
+
12353
+
11951
12354
  # ---------------------------------------------------------------------------
11952
12355
  # `dncli sites publish / rollback / releases`: upload a folder with rsync.
11953
12356
  #
@@ -12246,6 +12649,14 @@ def _set_document_root(
12246
12649
  json_body={"document_root": root},
12247
12650
  timeout=timeout,
12248
12651
  )
12652
+ _wait_jobs(state, response, deadline, f"changing the document root to {root}")
12653
+
12654
+
12655
+ def _wait_jobs(
12656
+ state: AppState, response: ApiResponse, deadline: float, what: str
12657
+ ) -> None:
12658
+ """Wait for the jobs an async call queued; fail when one did not complete."""
12659
+
12249
12660
  jobs = response.data
12250
12661
  if not isinstance(jobs, list):
12251
12662
  return
@@ -12255,15 +12666,12 @@ def _set_document_root(
12255
12666
  jobs, finished = _wait_for_batch(state, batch, jobs, deadline)
12256
12667
  if not finished:
12257
12668
  raise CliError(
12258
- f"timed out waiting for the document root change (batch {batch}); "
12259
- f"follow it with: dncli jobs batches show {batch}",
12669
+ f"timed out {what} (batch {batch}); follow it with: "
12670
+ f"dncli jobs batches show {batch}",
12260
12671
  kind="timeout",
12261
12672
  )
12262
12673
  if any(job.get("status") != "completed" for job in jobs):
12263
- raise CliError(
12264
- f"changing the document root to {root} failed; see "
12265
- f"dncli jobs batches show {batch}"
12266
- )
12674
+ raise CliError(f"{what} failed; see dncli jobs batches show {batch}")
12267
12675
 
12268
12676
 
12269
12677
  def _prune(releases: list[str], new: str, keep: int) -> list[str]:
@@ -12357,6 +12765,7 @@ def sites_publish(
12357
12765
  ),
12358
12766
  ] = None,
12359
12767
  host: HostOption = None,
12768
+ attach_key: AttachKeyOption = None,
12360
12769
  yes: bool = _YES_OPT,
12361
12770
  dry_run: Annotated[
12362
12771
  bool,
@@ -12371,7 +12780,7 @@ def sites_publish(
12371
12780
  """Upload a folder to a site with rsync.
12372
12781
 
12373
12782
  Plain mode (the default) uploads into
12374
- /home/site<id>/domains/<domain>/public_html: new and changed files only,
12783
+ /home/site<NNNNN>/domains/<domain>/public_html: new and changed files only,
12375
12784
  unless --delete. Release mode uploads each publish into
12376
12785
  public_html/releases/<timestamp>/ and switches the public_html/current
12377
12786
  symlink to it in one step, so visitors never see a half-finished upload;
@@ -12389,10 +12798,12 @@ def sites_publish(
12389
12798
  every host: all are uploaded to (and run the commands) first, then all
12390
12799
  are switched.
12391
12800
 
12392
- Needs rsync and ssh here and on the server. Without a terminal (a CI
12393
- pipeline, an agent) ssh cannot ask for a password or to trust a new
12394
- host key: attach an SSH key to the site and put the hosts' keys in
12395
- known_hosts first (ssh-keyscan)."""
12801
+ Needs rsync and ssh here and on the server. When none of your local SSH
12802
+ keys is attached to the site, dncli offers to attach one (see `dncli
12803
+ sites ssh`). Without a terminal (a CI pipeline, an agent) ssh cannot ask
12804
+ for a password or to trust a new host key: attach an SSH key to the
12805
+ site (--attach-key) and put the hosts' keys in known_hosts first
12806
+ (ssh-keyscan)."""
12396
12807
 
12397
12808
  state = state_from(ctx)
12398
12809
  source = directory.expanduser()
@@ -12414,6 +12825,7 @@ def sites_publish(
12414
12825
  "from the folder alone"
12415
12826
  )
12416
12827
  excludes = DEFAULT_EXCLUDES + list(exclude or [])
12828
+ ensure_site_key(state, login, attach_key, dry_run, timeout)
12417
12829
  commands = [RunStep(command) for command in (run or []) if command.strip()] + [
12418
12830
  RunStep(command, once=True) for command in (run_once or []) if command.strip()
12419
12831
  ]
@@ -12639,6 +13051,7 @@ def sites_releases(
12639
13051
  ctx: typer.Context,
12640
13052
  service_id: SiteArgument,
12641
13053
  host: HostOption = None,
13054
+ attach_key: AttachKeyOption = None,
12642
13055
  output: OutputOption = None,
12643
13056
  columns: ColumnsOption = None,
12644
13057
  ) -> None:
@@ -12647,6 +13060,7 @@ def sites_releases(
12647
13060
 
12648
13061
  state = state_from(ctx, output, columns)
12649
13062
  login = _release_site(state, service_id, host)
13063
+ ensure_site_key(state, login, attach_key)
12650
13064
  with ExitStack() as stack:
12651
13065
  sessions = _open_sessions(stack, login)
12652
13066
  rows: list[dict[str, Any]] = [
@@ -12675,6 +13089,7 @@ def sites_rollback(
12675
13089
  ),
12676
13090
  ] = None,
12677
13091
  host: HostOption = None,
13092
+ attach_key: AttachKeyOption = None,
12678
13093
  yes: bool = _YES_OPT,
12679
13094
  dry_run: Annotated[
12680
13095
  bool,
@@ -12689,6 +13104,7 @@ def sites_rollback(
12689
13104
 
12690
13105
  state = state_from(ctx)
12691
13106
  login = _release_site(state, service_id, host)
13107
+ ensure_site_key(state, login, attach_key, dry_run)
12692
13108
  with ExitStack() as stack:
12693
13109
  sessions = _open_sessions(stack, login)
12694
13110
  currents = sorted({str(session.site.current) for session in sessions})
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "devnomads-cli"
3
- version = "0.15.0"
3
+ version = "0.16.0"
4
4
  description = "Manage your DevNomads services from the command line"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -19,6 +19,14 @@ TARGET = "site12055@srv01.mmx.nl"
19
19
  runner = CliRunner()
20
20
 
21
21
 
22
+ @pytest.fixture(autouse=True)
23
+ def no_local_keys(monkeypatch):
24
+ """No local SSH keys: the attach-key check stays out of these tests
25
+ (tests/test_ssh_keys.py covers it)."""
26
+
27
+ monkeypatch.setattr(dncli, "local_ssh_keys", lambda host=None: [])
28
+
29
+
22
30
  @pytest.fixture
23
31
  def configured(write_profile):
24
32
  write_profile(api_key="testkey-1234567890", api_url=API)
@@ -14,6 +14,14 @@ API = "https://api.test"
14
14
  runner = CliRunner()
15
15
 
16
16
 
17
+ @pytest.fixture(autouse=True)
18
+ def no_local_keys(monkeypatch):
19
+ """No local SSH keys: the attach-key check stays out of these tests
20
+ (tests/test_ssh_keys.py covers it)."""
21
+
22
+ monkeypatch.setattr(dncli, "local_ssh_keys", lambda host=None: [])
23
+
24
+
17
25
  @pytest.fixture
18
26
  def configured(write_profile):
19
27
  write_profile(api_key="testkey-1234567890", api_url=API)
@@ -147,3 +155,33 @@ def test_dry_run_prints_the_command(configured, execs):
147
155
  assert result.exit_code == 0, result.output
148
156
  assert result.stdout == "ssh site12055@srv01.mmx.nl uptime\n"
149
157
  assert execs == []
158
+
159
+
160
+ @respx.mock
161
+ def test_user_is_padded_to_five_digits(configured, execs):
162
+ respx.get(f"{API}/services/sites/2467").mock(
163
+ return_value=Response(
164
+ 200,
165
+ json={
166
+ "service_id": 2467,
167
+ "entity": "example.nl",
168
+ "site": {
169
+ "cluster_id": 4,
170
+ "hosts": [{"hostname": "web04.sites.infrapod.nl", "cluster_id": 4}],
171
+ },
172
+ },
173
+ )
174
+ )
175
+ result = runner.invoke(app, ["sites", "ssh", "2467"])
176
+ assert result.exit_code == 0, result.output
177
+ assert execs == [["ssh", "site02467@web04.sites.infrapod.nl"]]
178
+
179
+
180
+ @pytest.mark.parametrize(
181
+ "service_id,user",
182
+ [("2467", "site02467"), ("12055", "site12055"), ("123456", "site123456")],
183
+ )
184
+ def test_site_user_and_paths(service_id, user):
185
+ login = dncli.SiteLogin(service_id, "example.nl", 4, "/", ["h"], "h")
186
+ assert login.user == user
187
+ assert login.public_html == f"/home/{user}/domains/example.nl/public_html"
@@ -0,0 +1,309 @@
1
+ """Local SSH keys: finding them, matching them against the account and the
2
+ site, and adding/attaching one (keys add-local, sites keys attach-local, and
3
+ the check before sites ssh). HTTP mocked via respx; no real ssh runs."""
4
+
5
+ import json
6
+ import subprocess
7
+
8
+ import pytest
9
+ import respx
10
+ from httpx import Response
11
+ from typer.testing import CliRunner
12
+
13
+ import dncli
14
+ from dncli import app
15
+
16
+ API = "https://api.test"
17
+ runner = CliRunner()
18
+
19
+ ED = "AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl"
20
+ RSA = "AAAAB3NzaC1yc2EAAAADAQABAAABAQC7"
21
+ AGENT = dncli.LocalKey("ssh-ed25519", ED, "loek@laptop", "ssh agent")
22
+ FILE = dncli.LocalKey("ssh-rsa", RSA, "old", "/home/loek/.ssh/id_rsa.pub")
23
+
24
+
25
+ @pytest.fixture
26
+ def configured(write_profile):
27
+ write_profile(api_key="testkey-1234567890", api_url=API)
28
+
29
+
30
+ @pytest.fixture
31
+ def local(monkeypatch):
32
+ """The local keys dncli finds; tests set the list."""
33
+
34
+ keys = [AGENT]
35
+ monkeypatch.setattr(dncli, "local_ssh_keys", lambda host=None: list(keys))
36
+ return keys
37
+
38
+
39
+ @pytest.fixture
40
+ def execs(monkeypatch):
41
+ calls = []
42
+ monkeypatch.setattr(dncli.shutil, "which", lambda name: f"/usr/bin/{name}")
43
+ monkeypatch.setattr(dncli.os, "execv", lambda path, argv: calls.append(argv))
44
+ return calls
45
+
46
+
47
+ def mock_site(keys=()):
48
+ respx.get(f"{API}/services/sites").mock(
49
+ return_value=Response(
50
+ 200, json=[{"service_id": 12055, "entity": "acadejong.nl"}]
51
+ )
52
+ )
53
+ respx.get(f"{API}/services/sites/12055").mock(
54
+ return_value=Response(
55
+ 200,
56
+ json={
57
+ "service_id": 12055,
58
+ "entity": "acadejong.nl",
59
+ "site": {
60
+ "cluster_id": 4,
61
+ "hosts": [{"hostname": "srv01.mmx.nl", "cluster_id": 4}],
62
+ },
63
+ "keys": list(keys),
64
+ },
65
+ )
66
+ )
67
+
68
+
69
+ def mock_account(*keys):
70
+ respx.get(f"{API}/keys").mock(return_value=Response(200, json=list(keys)))
71
+ created = respx.post(f"{API}/keys").mock(
72
+ return_value=Response(
73
+ 201, json={"data": {"id": 31, "name": "x", "key": AGENT.text}}
74
+ )
75
+ )
76
+ attached = respx.post(f"{API}/services/sites/12055/keys").mock(
77
+ return_value=Response(
78
+ 202,
79
+ json=[{"job_id": "j1", "batch_id": "b1", "status": "completed"}],
80
+ )
81
+ )
82
+ return created, attached
83
+
84
+
85
+ def account_key(key, id=7, name="laptop"):
86
+ return {"id": id, "name": name, "key": f"{key.type} {key.blob} other comment"}
87
+
88
+
89
+ # --- finding local keys ----------------------------------------------------
90
+
91
+
92
+ def test_parse_public_key():
93
+ key = dncli.parse_public_key(f"ssh-ed25519 {ED} me@host\n", "x.pub")
94
+ assert key == dncli.LocalKey("ssh-ed25519", ED, "me@host", "x.pub")
95
+ assert key.fingerprint.startswith("SHA256:")
96
+ assert dncli.parse_public_key("ssh-ed25519 not-base64!") is None
97
+ assert dncli.parse_public_key(f"ssh-ed25519-cert-v01@openssh.com {ED}") is None
98
+ assert dncli.parse_public_key("-----BEGIN OPENSSH PRIVATE KEY-----") is None
99
+
100
+
101
+ def test_local_keys_agent_first_then_identity_files(tmp_path, monkeypatch):
102
+ ssh_dir = tmp_path / ".ssh"
103
+ ssh_dir.mkdir()
104
+ (ssh_dir / "id_rsa").write_text("private, never read")
105
+ (ssh_dir / "id_rsa.pub").write_text(f"ssh-rsa {RSA} old\n")
106
+ (ssh_dir / "id_ed25519").write_text("private")
107
+ (ssh_dir / "id_ed25519.pub").write_text(f"ssh-ed25519 {ED} same as agent\n")
108
+ (ssh_dir / "id_ecdsa.pub").write_text(f"ssh-rsa {RSA}x\n") # no private key
109
+
110
+ def run(argv, **kwargs):
111
+ if argv[-1] == "-L":
112
+ out = f"ssh-ed25519 {ED} loek@laptop\n"
113
+ else:
114
+ assert argv[1:] == ["-G", "srv01.mmx.nl"]
115
+ out = "user site1\n" + "".join(
116
+ f"identityfile {ssh_dir / name}\n"
117
+ for name in ("id_ed25519", "id_ecdsa", "id_rsa")
118
+ )
119
+ return subprocess.CompletedProcess(argv, 0, out, "")
120
+
121
+ monkeypatch.setattr(dncli.shutil, "which", lambda name: f"/usr/bin/{name}")
122
+ monkeypatch.setattr(dncli.subprocess, "run", run)
123
+ keys = dncli.local_ssh_keys("srv01.mmx.nl")
124
+ assert [(key.blob, key.source) for key in keys] == [
125
+ (ED, "ssh agent"),
126
+ (RSA, str(ssh_dir / "id_rsa.pub")),
127
+ ]
128
+
129
+
130
+ def test_local_keys_without_an_agent(tmp_path, monkeypatch):
131
+ def run(argv, **kwargs):
132
+ return subprocess.CompletedProcess(argv, 2, "", "no agent")
133
+
134
+ monkeypatch.setattr(dncli.shutil, "which", lambda name: f"/usr/bin/{name}")
135
+ monkeypatch.setattr(dncli.subprocess, "run", run)
136
+ monkeypatch.setattr(dncli.Path, "home", lambda: tmp_path)
137
+ assert dncli.local_ssh_keys("srv01.mmx.nl") == []
138
+
139
+
140
+ # --- keys add-local --------------------------------------------------------
141
+
142
+
143
+ @respx.mock
144
+ def test_add_local_adds_a_new_key(configured, local, monkeypatch):
145
+ monkeypatch.setattr(dncli.getpass, "getuser", lambda: "loek")
146
+ monkeypatch.setattr(dncli.socket, "gethostname", lambda: "laptop.lan")
147
+ created, _ = mock_account(
148
+ {"id": 1, "name": "loek@laptop", "key": f"ssh-rsa {RSA}9"}
149
+ )
150
+ result = runner.invoke(app, ["--out", "json", "keys", "add-local"])
151
+ assert result.exit_code == 0, result.output
152
+ body = json.loads(created.calls.last.request.content)
153
+ # the name is made unique, the key sent is the public key text
154
+ assert body == {"name": "loek@laptop-2", "key": AGENT.text}
155
+
156
+
157
+ @respx.mock
158
+ def test_add_local_does_not_add_a_key_twice(configured, local):
159
+ created, _ = mock_account(account_key(AGENT, name="work laptop"))
160
+ result = runner.invoke(app, ["--out", "json", "keys", "add-local"])
161
+ assert result.exit_code == 0, result.output
162
+ assert "already on your account as work laptop" in result.output
163
+ assert not created.called
164
+
165
+
166
+ @respx.mock
167
+ def test_add_local_dry_run_and_name(configured, local):
168
+ created, _ = mock_account()
169
+ result = runner.invoke(
170
+ app, ["--out", "json", "keys", "add-local", "--name", "ci", "--dry-run"]
171
+ )
172
+ assert result.exit_code == 0, result.output
173
+ assert json.loads(result.stdout)["body"] == {"name": "ci", "key": AGENT.text}
174
+ assert not created.called
175
+
176
+
177
+ @respx.mock
178
+ def test_add_local_from_a_key_file(configured, local, tmp_path):
179
+ (tmp_path / "deploy.pub").write_text(f"ssh-rsa {RSA} deploy\n")
180
+ created, _ = mock_account()
181
+ result = runner.invoke(
182
+ app, ["keys", "add-local", "--key", str(tmp_path / "deploy"), "--name", "ci"]
183
+ )
184
+ assert result.exit_code == 0, result.output
185
+ assert (
186
+ json.loads(created.calls.last.request.content)["key"] == f"ssh-rsa {RSA} deploy"
187
+ )
188
+
189
+
190
+ def test_add_local_without_any_key(configured, local):
191
+ local.clear()
192
+ result = runner.invoke(app, ["keys", "add-local"])
193
+ assert result.exit_code == 3
194
+ assert "ssh-keygen" in result.output
195
+
196
+
197
+ # --- sites keys attach-local -----------------------------------------------
198
+
199
+
200
+ @respx.mock
201
+ def test_attach_local_adds_and_attaches(configured, local):
202
+ mock_site()
203
+ created, attached = mock_account()
204
+ result = runner.invoke(app, ["sites", "keys", "attach-local", "acadejong.nl"])
205
+ assert result.exit_code == 0, result.output
206
+ assert created.called
207
+ assert json.loads(attached.calls.last.request.content) == {"key_id": 31}
208
+ assert "attached" in result.output
209
+
210
+
211
+ @respx.mock
212
+ def test_attach_local_uses_the_account_key(configured, local):
213
+ mock_site()
214
+ created, attached = mock_account(account_key(AGENT))
215
+ result = runner.invoke(app, ["sites", "keys", "attach-local", "acadejong.nl"])
216
+ assert result.exit_code == 0, result.output
217
+ assert not created.called
218
+ assert json.loads(attached.calls.last.request.content) == {"key_id": 7}
219
+
220
+
221
+ @respx.mock
222
+ def test_attach_local_when_already_attached(configured, local):
223
+ local.append(FILE)
224
+ mock_site(keys=[account_key(FILE, id=9)])
225
+ created, attached = mock_account()
226
+ result = runner.invoke(app, ["sites", "keys", "attach-local", "acadejong.nl"])
227
+ assert result.exit_code == 0, result.output
228
+ assert "already attached" in result.output
229
+ assert not created.called and not attached.called
230
+
231
+
232
+ @respx.mock
233
+ def test_attach_local_dry_run(configured, local):
234
+ mock_site()
235
+ created, attached = mock_account()
236
+ result = runner.invoke(
237
+ app,
238
+ ["--out", "json", "sites", "keys", "attach-local", "acadejong.nl", "--dry-run"],
239
+ )
240
+ assert result.exit_code == 0, result.output
241
+ requests = json.loads(result.stdout)["requests"]
242
+ assert [r["path"] for r in requests] == ["/keys", "/services/sites/12055/keys"]
243
+ assert not created.called and not attached.called
244
+
245
+
246
+ # --- the check before sites ssh --------------------------------------------
247
+
248
+
249
+ @respx.mock
250
+ def test_ssh_asks_to_attach_at_a_terminal(configured, local, execs, monkeypatch):
251
+ monkeypatch.setattr(dncli, "stdin_is_terminal", lambda: True)
252
+ mock_site()
253
+ created, attached = mock_account()
254
+ result = runner.invoke(app, ["sites", "ssh", "acadejong.nl"], input="y\n")
255
+ assert result.exit_code == 0, result.output
256
+ assert "None of your SSH keys is attached to acadejong.nl" in result.output
257
+ assert created.called and attached.called
258
+ assert execs == [["ssh", "site12055@srv01.mmx.nl"]]
259
+
260
+
261
+ @respx.mock
262
+ def test_ssh_declined_falls_back_to_the_password(configured, local, execs, monkeypatch):
263
+ monkeypatch.setattr(dncli, "stdin_is_terminal", lambda: True)
264
+ mock_site()
265
+ created, attached = mock_account()
266
+ result = runner.invoke(app, ["sites", "ssh", "acadejong.nl"], input="n\n")
267
+ assert result.exit_code == 0, result.output
268
+ assert not created.called and not attached.called
269
+ assert execs == [["ssh", "site12055@srv01.mmx.nl"]]
270
+
271
+
272
+ @respx.mock
273
+ def test_ssh_without_a_terminal_only_hints(configured, local, execs):
274
+ mock_site()
275
+ created, attached = mock_account()
276
+ result = runner.invoke(app, ["sites", "ssh", "acadejong.nl", "--", "uptime"])
277
+ assert result.exit_code == 0, result.output
278
+ assert "--attach-key would" in result.output
279
+ assert not created.called and not attached.called
280
+
281
+
282
+ @respx.mock
283
+ def test_ssh_attach_key_flag_needs_no_terminal(configured, local, execs):
284
+ mock_site()
285
+ created, attached = mock_account()
286
+ result = runner.invoke(
287
+ app, ["sites", "ssh", "acadejong.nl", "--attach-key", "--", "uptime"]
288
+ )
289
+ assert result.exit_code == 0, result.output
290
+ assert created.called and attached.called
291
+
292
+
293
+ @respx.mock
294
+ def test_ssh_with_an_attached_key_says_nothing(configured, local, execs):
295
+ mock_site(keys=[account_key(AGENT)])
296
+ result = runner.invoke(app, ["sites", "ssh", "acadejong.nl"])
297
+ assert result.exit_code == 0, result.output
298
+ assert "SSH key" not in result.output
299
+
300
+
301
+ @respx.mock
302
+ def test_no_attach_key_skips_the_check(configured, local, execs, monkeypatch):
303
+ def boom(host=None):
304
+ raise AssertionError("must not look for keys")
305
+
306
+ monkeypatch.setattr(dncli, "local_ssh_keys", boom)
307
+ mock_site()
308
+ result = runner.invoke(app, ["sites", "ssh", "acadejong.nl", "--no-attach-key"])
309
+ assert result.exit_code == 0, result.output
File without changes
File without changes