elan-cli 0.1.5__tar.gz → 0.1.7__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 (32) hide show
  1. {elan_cli-0.1.5 → elan_cli-0.1.7}/CHANGELOG.md +28 -0
  2. {elan_cli-0.1.5 → elan_cli-0.1.7}/PKG-INFO +2 -2
  3. {elan_cli-0.1.5 → elan_cli-0.1.7}/pyproject.toml +2 -2
  4. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/adk.py +51 -2
  5. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/invoke.py +39 -3
  6. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/main.py +48 -4
  7. elan_cli-0.1.7/src/elan_cli/scan.py +172 -0
  8. {elan_cli-0.1.5 → elan_cli-0.1.7}/.gitignore +0 -0
  9. {elan_cli-0.1.5 → elan_cli-0.1.7}/LICENSE +0 -0
  10. {elan_cli-0.1.5 → elan_cli-0.1.7}/README.md +0 -0
  11. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/__init__.py +0 -0
  12. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/auth.py +0 -0
  13. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/child.py +0 -0
  14. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/client.py +0 -0
  15. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/config.py +0 -0
  16. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/deploy.py +0 -0
  17. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/destroy.py +0 -0
  18. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/doctor.py +0 -0
  19. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/env.py +0 -0
  20. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/files.py +0 -0
  21. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/logs.py +0 -0
  22. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/manifests.py +0 -0
  23. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/project.py +0 -0
  24. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/projects.py +0 -0
  25. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/prompt.py +0 -0
  26. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/rollback.py +0 -0
  27. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/scaffold.py +0 -0
  28. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/secret.py +0 -0
  29. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/stream.py +0 -0
  30. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/tenant.py +0 -0
  31. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/validate.py +0 -0
  32. {elan_cli-0.1.5 → elan_cli-0.1.7}/src/elan_cli/wallet.py +0 -0
@@ -3,6 +3,34 @@
3
3
  Versions follow the tag that published them — `cli/v*`. A version with no date
4
4
  has not been published yet.
5
5
 
6
+ ## 0.1.7 — 2026-11-18
7
+
8
+ ### Added
9
+ - `elan invoke --security-context FILE` (or `-` for stdin): credentials the
10
+ agent may act with for the run (ADR-0249). Read from a file, never argv, and
11
+ never printed — only the credential names are.
12
+ - `elan adk web|run … --security-context FILE`: the same, for a local run.
13
+ Validated before ADK starts and handed to it by path.
14
+
15
+ ## 0.1.6 — 2026-11-15
16
+
17
+ ### Added
18
+ - **`elan scan` re-scans what your project runs, now.** A deploy checks its image
19
+ once, so a vulnerability published afterwards is found only by checking
20
+ again. For each image it prints the counts by severity and each CRITICAL
21
+ finding, as `elan deploy` does. Anything new since the last scan that would
22
+ refuse a deploy today is listed separately; your organization's admins are
23
+ told about it too. A link to the project's Security page in the console
24
+ follows. If the vulnerability database has not changed since the image's
25
+ last scan, the answer is the same, so it says so and nothing is charged.
26
+ Pass `--project` outside a project directory.
27
+ - **`elan scan schedule` shows or sets how often running images are re-scanned:**
28
+ `off`, `daily`, `weekly` (Sunday), `monthly` (the 1st), or `every <N>` days
29
+ from 1 to 90, for example `elan scan schedule every 14`. It prints the next
30
+ check, the last one and the platform's estimate of scans a month. Re-scans
31
+ are off until you choose a schedule, because each completed one is charged.
32
+ Times are midnight UTC, printed in your own time zone.
33
+
6
34
  ## 0.1.5 — 2026-11-15
7
35
 
8
36
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: elan-cli
3
- Version: 0.1.5
3
+ Version: 0.1.7
4
4
  Summary: The command line a developer deploys an agent with
5
5
  Project-URL: Homepage, https://openelan.ai
6
6
  Project-URL: Documentation, https://openelan.ai/app/docs
@@ -16,7 +16,7 @@ Classifier: Programming Language :: Python :: 3.13
16
16
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
17
  Requires-Python: >=3.12
18
18
  Requires-Dist: certifi>=2024.2.2
19
- Requires-Dist: elan-agentkit-contracts>=0.1.1
19
+ Requires-Dist: elan-agentkit-contracts>=0.2.0
20
20
  Requires-Dist: elan-sdk
21
21
  Requires-Dist: httpx>=0.27
22
22
  Requires-Dist: keyring>=25.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "elan-cli"
3
- version = "0.1.5"
3
+ version = "0.1.7"
4
4
  description = "The command line a developer deploys an agent with"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -29,7 +29,7 @@ dependencies = [
29
29
  # so `uv tool install elan-cli` no longer pulls a token verifier, a
30
30
  # database layer and a Pub/Sub broker onto a developer's laptop to read one
31
31
  # YAML file.
32
- "elan-agentkit-contracts>=0.1.1",
32
+ "elan-agentkit-contracts>=0.2.0",
33
33
  # THE SHARED CLIENT CODE, ONE WAY (ADR-0104). `text_of` and the certifi
34
34
  # context live there now; this re-exports them. The dependency runs
35
35
  # elan-cli -> elan-sdk and never back: the SDK must not import `elan_cli`,
@@ -136,8 +136,48 @@ def argv_for(args: list[str], root: Path, slugs: list[str]) -> list[str]:
136
136
  return list(args)
137
137
 
138
138
 
139
+ #: The one flag `elan adk` takes for itself; everything else is ADK's.
140
+ SECURITY_CONTEXT_FLAG = "--security-context"
141
+
142
+
143
+ def take_security_context(args: list[str]) -> tuple[str | None, list[str]]:
144
+ """Split `--security-context FILE` (or `=FILE`) out of ADK's arguments.
145
+
146
+ OURS AND NOT ADK'S, so it is removed before ADK sees the command line —
147
+ ADK would refuse an option it does not know, naming a flag the developer
148
+ typed correctly.
149
+ """
150
+ rest: list[str] = []
151
+ path: str | None = None
152
+ items = iter(args)
153
+ for item in items:
154
+ if item == SECURITY_CONTEXT_FLAG:
155
+ path = next(items, None)
156
+ if path is None:
157
+ raise ValueError(f"{SECURITY_CONTEXT_FLAG} needs a file")
158
+ elif item.startswith(SECURITY_CONTEXT_FLAG + "="):
159
+ path = item.split("=", 1)[1]
160
+ else:
161
+ rest.append(item)
162
+ return path, rest
163
+
164
+
139
165
  def run(args: list[str], start: Path | None = None,
140
166
  python: str | None = None) -> int:
167
+ # THE CREDENTIALS A LOCAL RUN ACTS WITH (ADR-0249), validated here so a bad
168
+ # file is refused naming the field before ADK starts — then handed to the
169
+ # child by PATH, never by value, so they are in no process listing.
170
+ try:
171
+ context_file, args = take_security_context(args)
172
+ if context_file is not None:
173
+ from elan_cli.invoke import load_security_context # noqa: PLC0415
174
+
175
+ load_security_context(context_file)
176
+ context_file = str(Path(context_file).resolve())
177
+ except (OSError, ValueError) as exc:
178
+ print(f"error: {SECURITY_CONTEXT_FLAG}: {exc}")
179
+ return 2
180
+
141
181
  if not args:
142
182
  print("error: `elan adk` passes its arguments to ADK's own CLI.\n\n"
143
183
  " elan adk web the dev UI, every target in this repo\n"
@@ -183,10 +223,12 @@ def run(args: list[str], start: Path | None = None,
183
223
  print(flush=True)
184
224
  # SUPERVISED RATHER THAN `subprocess.run`, because `adk web` is the one
185
225
  # child here with a graceful shutdown worth protecting — see `child.py`.
186
- return supervise(argv, cwd=project.root, env=_environment())
226
+ if context_file is not None:
227
+ print(f"credentials from {context_file} (local only)")
228
+ return supervise(argv, cwd=project.root, env=_environment(context_file))
187
229
 
188
230
 
189
- def _environment() -> dict[str, str]:
231
+ def _environment(context_file: str | None = None) -> dict[str, str]:
190
232
  """ADK's own environment, plus the one thing it must not inherit.
191
233
 
192
234
  `TARGET_SLUG` NAMES WHICH AGENT A POD RUNS, and a developer who has it set
@@ -194,6 +236,13 @@ def _environment() -> dict[str, str]:
194
236
  one target for every shim, because `Settings` reads it. The shim passes
195
237
  its slug explicitly; removing this makes sure nothing overrides it.
196
238
  """
239
+ from elan_agentkit_contracts.security_context import LOCAL_CONTEXT_ENV # noqa: PLC0415
240
+
197
241
  env = dict(os.environ)
198
242
  env.pop("TARGET_SLUG", None)
243
+ # AN INHERITED ONE IS DROPPED TOO, so a run started without the flag acts
244
+ # with no credentials rather than with whatever a previous shell exported.
245
+ env.pop(LOCAL_CONTEXT_ENV, None)
246
+ if context_file:
247
+ env[LOCAL_CONTEXT_ENV] = context_file
199
248
  return env
@@ -23,9 +23,11 @@ minutes reads as a failure.
23
23
 
24
24
  from __future__ import annotations
25
25
 
26
+ import json
26
27
  import sys
27
28
  import time
28
29
  import uuid
30
+ from typing import Any
29
31
 
30
32
  from elan_cli.client import Api, ApiError
31
33
  from elan_cli.stream import (
@@ -58,9 +60,36 @@ ANSWERED_BY = {
58
60
  }
59
61
 
60
62
 
63
+ def load_security_context(path: str, *, stdin=None) -> dict[str, Any]:
64
+ """A security context from a JSON file, or `-` for stdin (ADR-0249).
65
+
66
+ A FILE AND NEVER AN ARGUMENT, because argv lands in shell history, in `ps`
67
+ for every user on the machine, and in CI logs — and these are another
68
+ service's credentials for somebody. Validated here so a refusal names the
69
+ field before anything is sent; the value is returned revealed only because
70
+ the request body is the one place it has to be.
71
+ """
72
+ from elan_agentkit_contracts.security_context import ( # noqa: PLC0415
73
+ parse_security_context,
74
+ )
75
+
76
+ if path == "-":
77
+ raw = (stdin or sys.stdin).read()
78
+ else:
79
+ with open(path, encoding="utf-8") as handle:
80
+ raw = handle.read()
81
+ try:
82
+ data = json.loads(raw)
83
+ except json.JSONDecodeError as exc:
84
+ # NOT `exc.doc`, which is the file — and the file is credentials.
85
+ raise ValueError(f"{path}: not JSON (line {exc.lineno}, column {exc.colno})") from None
86
+ return parse_security_context(data).to_wire()
87
+
88
+
61
89
  def run(api: Api, target: str, text: str, *, session: str = "",
62
90
  project: str = "", timeout: float = DEFAULT_TIMEOUT,
63
- now=time.monotonic, open_socket=None) -> int:
91
+ now=time.monotonic, open_socket=None,
92
+ security_context: dict[str, Any] | None = None) -> int:
64
93
  """Send one message and print what comes back. Returns the exit code.
65
94
 
66
95
  THE CLOCK IS INJECTED so a timeout can be reached without waiting for one.
@@ -85,9 +114,12 @@ def run(api: Api, target: str, text: str, *, session: str = "",
85
114
  with watching(api.config.api, api.token(), session_id,
86
115
  open_socket=open_socket) as socket:
87
116
  try:
88
- started = api.request("POST", "/v1/invocations", json={
117
+ body: dict[str, Any] = {
89
118
  "target_slug": target, "text": text,
90
- "session_id": session_id, "project": project})
119
+ "session_id": session_id, "project": project}
120
+ if security_context is not None:
121
+ body["security_context"] = security_context
122
+ started = api.request("POST", "/v1/invocations", json=body)
91
123
  except ApiError as exc:
92
124
  print(f"{exc}", file=sys.stderr)
93
125
  return 1
@@ -95,6 +127,10 @@ def run(api: Api, target: str, text: str, *, session: str = "",
95
127
  invocation = started.get("invocation_id", "")
96
128
  print(f"invocation {invocation}")
97
129
  print(f"session {session_id}")
130
+ if security_context:
131
+ # NAMES ONLY. The values were sent and are never printed.
132
+ names = ", ".join(c["name"] for c in security_context["credentials"])
133
+ print(f"credentials {names or '(none)'}")
98
134
  print()
99
135
  try:
100
136
  return _follow(socket, invocation, target, session_id,
@@ -37,6 +37,7 @@ from elan_cli import doctor as doctor_cmd
37
37
  from elan_cli import invoke as invoke_cmd
38
38
  from elan_cli import logs as logs_cmd
39
39
  from elan_cli import projects as projects_cmd
40
+ from elan_cli import scan as scan_cmd
40
41
  from elan_cli.auth import AuthError
41
42
  from elan_cli.client import Api, ApiError
42
43
  from elan_cli.config import Config, ConfigError
@@ -62,7 +63,8 @@ from elan_cli.wallet import WalletError
62
63
  #: subclasses and asserts each one appears here — guilty until named, because a
63
64
  #: positive predicate over an open set is a sampling method rather than a guard.
64
65
  REFUSALS = (ProjectError, ConfigError, AuthError, ApiError, SecretError,
65
- WalletError, FilesError, ManifestError, StreamError)
66
+ WalletError, FilesError, ManifestError, StreamError,
67
+ scan_cmd.ScanError)
66
68
 
67
69
 
68
70
  def version_line() -> str:
@@ -142,8 +144,11 @@ def build_parser() -> argparse.ArgumentParser:
142
144
  # documents.
143
145
  passthrough = sub.add_parser(
144
146
  "adk", help="run ADK's own tools against this repo (web, run, eval)")
145
- passthrough.add_argument("args", nargs=argparse.REMAINDER,
146
- help="Passed to ADK unchanged.")
147
+ passthrough.add_argument(
148
+ "args", nargs=argparse.REMAINDER,
149
+ help="Passed to ADK unchanged, except --security-context FILE: the "
150
+ "credentials a local run acts with, as JSON (ADR-0249), e.g. "
151
+ "`elan adk web --security-context ctx.json`.")
147
152
 
148
153
  # `env` TAKES NOTHING, for the same reason `init` lost its flag: the
149
154
  # runtime resolves from the index by name.
@@ -192,6 +197,10 @@ def build_parser() -> argparse.ArgumentParser:
192
197
  help="seconds to wait for a reply (default 300; a "
193
198
  "sleeping agent has to be scheduled and started "
194
199
  "before it reads its queue)")
200
+ send.add_argument("--security-context", metavar="FILE", default=None,
201
+ help="credentials the agent may act with for this run, "
202
+ "as JSON — a file, or - for stdin. Never on the "
203
+ "command line, which shell history and ps can read")
195
204
 
196
205
  log = sub.add_parser("logs", help="a build's output, or a workload's")
197
206
  # OPTIONAL, BECAUSE `--workload` REPLACES IT. argparse cannot express "one of
@@ -235,6 +244,22 @@ def build_parser() -> argparse.ArgumentParser:
235
244
  status = sub.add_parser("status", help="how a deployment is getting on")
236
245
  status.add_argument("deployment_id")
237
246
 
247
+ # RE-SCANS OF WHAT IS RUNNING (ADR-0240). `--project` IS DECLARED ON BOTH
248
+ # LEVELS UNDER TWO NAMES, because argparse lets a subparser's default
249
+ # overwrite its parent's value: one dest would make
250
+ # `elan scan --project x schedule` forget the `x`.
251
+ scan = sub.add_parser("scan", help="re-scan what this project runs, now")
252
+ scan.add_argument("--project", default="",
253
+ help="defaults to the project in elan.yaml")
254
+ scan_sub = scan.add_subparsers(dest="scan_command")
255
+ scan_schedule = scan_sub.add_parser(
256
+ "schedule", help="show or set how often running images are re-scanned")
257
+ scan_schedule.add_argument(
258
+ "when", nargs="*",
259
+ help="off | daily | weekly | monthly | every <N> (N from 1 to 90 days)")
260
+ scan_schedule.add_argument("--project", dest="schedule_project", default="",
261
+ help="defaults to the project in elan.yaml")
262
+
238
263
  # PLATFORM STAFF ONLY, enforced by the service rather than here. A CLI that
239
264
  # refused locally would be a second rule to keep in step with the one that
240
265
  # actually holds the credential.
@@ -514,6 +539,16 @@ def _dispatch(args, parser) -> int:
514
539
  finally:
515
540
  api.close()
516
541
 
542
+ if args.command == "scan":
543
+ api = Api(Config.load())
544
+ try:
545
+ if args.scan_command == "schedule":
546
+ project = scan_cmd.project_of(args.schedule_project or args.project)
547
+ return scan_cmd.schedule(api, project, args.when)
548
+ return scan_cmd.now(api, scan_cmd.project_of(args.project))
549
+ finally:
550
+ api.close()
551
+
517
552
  if args.command == "agents":
518
553
  config = Config.load()
519
554
  api = Api(config)
@@ -547,10 +582,19 @@ def _dispatch(args, parser) -> int:
547
582
  # FROM elan.yaml, WHICH IS THE ONLY PLACE THAT KNOWS. `invoke` is
548
583
  # run inside a project, and the deploy file names it — so this is
549
584
  # read rather than asked for, the same way `deploy` reads it.
585
+ security_context = None
586
+ if args.security_context:
587
+ try:
588
+ security_context = invoke_cmd.load_security_context(
589
+ args.security_context)
590
+ except (OSError, ValueError) as exc:
591
+ print(f"--security-context: {exc}", file=sys.stderr)
592
+ return 2
550
593
  return invoke_cmd.run(api, args.target, args.text,
551
594
  session=args.session,
552
595
  project=_project_here(),
553
- timeout=args.timeout)
596
+ timeout=args.timeout,
597
+ security_context=security_context)
554
598
  finally:
555
599
  api.close()
556
600
 
@@ -0,0 +1,172 @@
1
+ """`elan scan`: re-scan what a project runs, and how often that happens by itself.
2
+
3
+ A DEPLOY CHECKS ITS IMAGE ONCE. A vulnerability published the next day is
4
+ found only by checking again — on the project's schedule, or now. Both cost
5
+ the tenant a scan (`security.rescan`), which is why the schedule is off until
6
+ somebody chooses one, and why `elan scan schedule` prints the monthly estimate
7
+ the platform computes beside whatever it sets (ADR-0240).
8
+
9
+ EVERY RULE AND EVERY LINK IS THE PLATFORM'S. What a schedule may be, when it
10
+ next runs and what it is estimated to cost all come back from the API, so this
11
+ package spells no slot rule and no console path that could drift from the
12
+ service's.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from datetime import datetime
18
+ from urllib.parse import quote
19
+
20
+ from elan_cli.client import Api
21
+ from elan_cli.deploy import SEVERITIES, SHOWN
22
+ from elan_cli.project import ProjectError, find
23
+
24
+
25
+ class ScanError(Exception):
26
+ """A scan command that cannot be sent, already phrased for the developer."""
27
+
28
+
29
+ def project_of(explicit: str) -> str:
30
+ """The project to act in: what was asked for, or what `elan.yaml` says —
31
+ the rule `elan wallet` and `elan deploy` already follow."""
32
+ if explicit.strip():
33
+ return explicit.strip()
34
+ try:
35
+ return find().spec.project
36
+ except ProjectError as exc:
37
+ raise ScanError("which project? run this inside one, or pass --project "
38
+ f"({exc})") from exc
39
+
40
+
41
+ def _path(project: str, tail: str) -> str:
42
+ return f"/v1/projects/{quote(project, safe='')}/{tail}"
43
+
44
+
45
+ def _when(iso: str) -> str:
46
+ """An instant in the reader's own zone, named, so nobody converts in their
47
+ head. The service sends UTC."""
48
+ if not iso:
49
+ return ""
50
+ moment = datetime.fromisoformat(iso.replace("Z", "+00:00")).astimezone()
51
+ return moment.strftime("%Y-%m-%d %H:%M %Z")
52
+
53
+
54
+ def now(api: Api, project: str) -> int:
55
+ """Scan every image the project runs, now, and say what came back."""
56
+ print(f"scanning what {project} runs…")
57
+ result = api.request("POST", _path(project, "scans"))
58
+ for image in result.get("images") or []:
59
+ _image(image)
60
+ link = (result.get("links") or {}).get("security", "")
61
+ if link:
62
+ print(f"\n full report: {link}")
63
+ # A SCAN THAT COULD NOT BE RECORDED is the service's fault, and a script
64
+ # running this must be able to tell.
65
+ return 1 if result.get("errors") else 0
66
+
67
+
68
+ def _image(image: dict) -> None:
69
+ targets = ", ".join(image.get("targets") or []) or image.get("image_digest", "")
70
+ print(f"\n {targets}")
71
+ if image.get("skipped"):
72
+ print(f" skipped: {image['skipped']}")
73
+ return
74
+ found = image.get("result")
75
+ if not found:
76
+ return
77
+ scan = found.get("scan") or {}
78
+ if found.get("deduped"):
79
+ print(" unchanged: the vulnerability database has not moved since the "
80
+ "last scan, so the answer is the same and this was not charged")
81
+ elif not scan.get("completed"):
82
+ reason = scan.get("incomplete_reason") or "no reason recorded"
83
+ print(f" not scanned: {reason}")
84
+ print(" which is not the same as clean")
85
+ return
86
+ _findings(scan)
87
+ fresh = image.get("newly_blocking") or []
88
+ if fresh:
89
+ print(f" NEW since the last scan, and each would refuse a deploy today "
90
+ f"({len(fresh)}); your organization's admins have been told:")
91
+ for finding in fresh[:SHOWN]:
92
+ print(f" {finding.get('severity')} {finding.get('cve')} "
93
+ f"{finding.get('package')} {finding.get('installed_version')} "
94
+ f"(fixed in {finding.get('fixed_version')})")
95
+ if len(fresh) > SHOWN:
96
+ print(f" … and {len(fresh) - SHOWN} more")
97
+
98
+
99
+ def _findings(scan: dict) -> None:
100
+ """The tally and the CRITICAL findings, as `elan deploy` prints them."""
101
+ findings = scan.get("findings") or []
102
+ if not findings:
103
+ print(" nothing found")
104
+ return
105
+ counts = scan.get("counts") or {}
106
+ tally = ", ".join(f"{counts[name]} {label}"
107
+ for name, label in SEVERITIES.items() if counts.get(name))
108
+ print(f" {len(findings)} findings — {tally}")
109
+ critical = sorted((f for f in findings if f.get("severity") == "CRITICAL"),
110
+ key=lambda f: not f.get("fixable"))
111
+ for finding in critical[:SHOWN]:
112
+ fix = (f"fixed in {finding.get('fixed_version')}" if finding.get("fixable")
113
+ else "no fix available")
114
+ print(f" CRITICAL {finding.get('cve')} {finding.get('package')} "
115
+ f"{finding.get('installed_version')} ({fix})")
116
+ if len(critical) > SHOWN:
117
+ print(f" … and {len(critical) - SHOWN} more critical")
118
+
119
+
120
+ #: What `elan scan schedule` accepts, as the reader types it.
121
+ WORDS = ("off", "daily", "weekly", "monthly")
122
+
123
+
124
+ def _body(words: list[str]) -> dict:
125
+ """`["every", "14"]` to the API's body. The NUMBER is the service's to
126
+ judge, so a bad one is refused there, in the service's own words."""
127
+ said = [word.lower() for word in words]
128
+ if said and said[-1] == "days":
129
+ said = said[:-1]
130
+ if len(said) == 1 and said[0] in WORDS:
131
+ return {"schedule": said[0]}
132
+ if said and said[0] == "every":
133
+ if len(said) != 2:
134
+ raise ScanError("say how many days: elan scan schedule every 14")
135
+ return {"schedule": "interval", "interval_days": said[1]}
136
+ raise ScanError("choose one of: off, daily, weekly, monthly, or every <N> "
137
+ "(for example: elan scan schedule every 14)")
138
+
139
+
140
+ def schedule(api: Api, project: str, words: list[str]) -> int:
141
+ """Show how often the project's running images are re-scanned, or set it."""
142
+ path = _path(project, "scan-schedule")
143
+ if words:
144
+ view = api.request("PUT", path, json=_body(words))
145
+ print(f"{project}: re-scans set to {view.get('label', '')}")
146
+ else:
147
+ view = api.request("GET", path)
148
+ print(f"{project}: re-scans {view.get('label', '')}")
149
+ _view(view)
150
+ return 0
151
+
152
+
153
+ def _view(view: dict) -> None:
154
+ images = view.get("images", 0)
155
+ if view.get("schedule") == "off":
156
+ print(" next: never — re-scans are off, and nothing is charged for them")
157
+ elif view.get("next_run_is_due"):
158
+ print(" next: due now — the hourly check scans it within the hour")
159
+ elif view.get("next_run"):
160
+ print(f" next: {_when(view['next_run'])} (within the hour after)")
161
+ else:
162
+ print(" next: once something is deployed")
163
+ last = _when(view.get("last_run", ""))
164
+ print(f" last: {last or 'never'}")
165
+ if view.get("schedule") != "off":
166
+ estimate = view.get("estimated_scans_per_month", 0)
167
+ print(f" estimate: about {estimate:g} scans a month "
168
+ f"({images} image{'' if images == 1 else 's'}; one image is one "
169
+ "scan however many agents run it)")
170
+ link = (view.get("links") or {}).get("security", "")
171
+ if link:
172
+ print(f" manage: {link}")
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes