Skip to content

Export devices from the API and import the export back - #3427

Open
lawik wants to merge 1 commit into
mainfrom
feature/device-export-api
Open

lawik wants to merge 1 commit into
mainfrom
feature/device-export-api

Conversation

@lawik

@lawik lawik commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

The devices list's CSV export gets an API endpoint, an option to include certificates, and an import that reads the file back. A product's devices can be exported and imported into another product or instance, with their descriptions, tags and certificates.

Closes #2433. nh gets nh device export and CSV import in nerves-hub/nh#39.

One module writes and reads the CSV

NervesHub.Devices.DeviceCSV replaces Products.devices_export_reducer/4. It writes the export and parses the import, so a file it writes always imports again. The columns are unchanged: identifier, description, tags, product, org, then certificates only when asked for. Each certificate is a PEM block with one blank line between them. A certificate saved before DERs were kept is written as a JSON object of its details, as before. Importing that object saves the record without a DER, using the from_json path DeviceCertificate already had.

Both exports start from Devices.export_query/3, which takes a user or a product API key, so tag-limited roles see only their devices. Both are streamed by NervesHubWeb.Helpers.DeviceCSVDownload.

API

  • GET /api/orgs/:org/products/:product/devices/export takes the devices list's filters[...], sort and sort_direction, plus include_certificates, which defaults to false. It streams every matching device, without paging. A bad filter, sort, advanced query or include_certificates is refused with a 422 before streaming starts.
  • The route has its own pipeline that also accepts Accept: text/csv, which the :api pipeline refuses with a 406. Its errors are still JSON. It sits ahead of the API scope so that /devices/:identifier doesn't take it.
  • POST .../devices/import takes the CSV as a new csv format. It's sent as text/csv, which implies the format, and is read from the raw body, up to 32 MB (413 beyond that). Columns are matched by name in any order. identifier is required, product and org are ignored, and any other column is refused. As with Trust&Go, a file it can't read gets a 422 naming each problem before anything is created. That includes an identifier repeated in the file and a PEM certificate without an authority key identifier. Each device is created with its certificates in one transaction, in the background, and the notification counts them.
  • The OpenAPI spec documents both. APISpecAssertions now checks a non-JSON response by its content type instead of failing on it.

Web UI

  • The devices list's export button opens a menu: "Export as CSV", or "Export with certificates". The old link always included certificates. The browser export now takes include_certificates, like the API.
  • An Import devices button (with device:create) opens a dialog at /devices/import. It reads the CSV and lists what's wrong with a file it can't read. It shows on an empty product too, which is where an import is most useful.
  • The deployment group's CSV import used to require a single identifier column, so it refused the export. It now finds that column among others.

Behaviour to know about

  • Identifiers are unique across the instance, soft-deleted devices included (devices_identifier_index). An import only creates devices the instance doesn't already have; the others count as failed. A round trip on the same instance needs the originals hard-deleted. Within an instance, move is the tool.
  • An invalid tags header on any import, Trust&Go included, is now refused with a 422. Before, every device failed in the background.
  • A device whose identifier is literally export or import is now shadowed by those routes, as new already was.
  • The export doesn't include update mode, managed updates, connecting code, deployment group or shared secrets.

Verified

  • New tests:
    • DeviceCSV, including a round trip with PEM and JSON certificates, and one into another org.
    • API export and CSV import, including a round trip through the API and the text/csv accept handling.
    • Tag-limited members and API keys.
    • API spec cases.
    • The UI menu, the import dialog, and the deployment group import of an export.
  • The full suite passes, as do compile with warnings as errors, format, credo, dialyzer and the spell check. mix deps.unlock --check-unused flags :comeonin, which fails on main too.
  • End to end, nh against a local server: three devices, one with a quoted multi-line description and two certificates and one with a DER-less certificate, were exported with certificates, hard-deleted and imported into another product. The re-export matched apart from the product and org columns. Importing the same file again was counted as 3 failed.

The devices list's CSV export moves into NervesHub.Devices.DeviceCSV, which
both writes the file and reads it back, so every export imports again as it
was: identifier, description, tags and, when asked for, certificates.

- GET /api/orgs/:org/products/:product/devices/export streams the same CSV
  as the web UI's export, filtered and sorted as the devices list is, for
  user tokens and product API keys alike. include_certificates=true adds
  the certificates column, in the API and from the UI's export menu.
- POST .../devices/import reads the CSV as its csv format, sent as
  text/csv, and the devices list gets an Import devices dialog for it.
  A file it can't read is refused with each problem before anything is
  created.
- The deployment group's CSV import finds the identifier column among
  others, so it takes the export too.

Closes #2433
@u7d-bot

u7d-bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Rummager review of 8ee7585a3c

Sensitive areas

  • Authentication: device certificate import, device identity, certificate records saved without DER, authority key identifier check
  • Authorization: membership gate on export, tag-limited roles and API keys in export query, device:create gate on import
  • Access control: new API export route and pipeline, shared API scope pipeline, import devices live route, route ordering
  • Personal data: bulk device export over API, optional device certificates in export

Pass with warnings: 2 warnings, 1 suggestion.

  • Security: 1 finding, inline at lib/nerves_hub/devices/device_csv.ex:185-188.
  • Code quality: 1 finding, inline at lib/nerves_hub/devices/bulk_actions.ex:72-76.
  • Prose, comments and docs: 1 finding, inline at lib/nerves_hub/devices/device_csv.ex:370.
  • No findings: Correctness.

The inline comments are in this review.

Screenshots of the UI changes, before and after (4 views)

Export devices menu open

Before After
Before After

Before, the download button in the header starts the export right away, so there is no menu to show. After, there is a new upload (Import devices) button next to it, and clicking download opens a menu with "Export as CSV" and "Export with certificates", each with a description.

Import devices dialog with file chosen

Before After
none After

New dialog at /devices/import showing the explanatory text, the chosen smartkiosk-devices.csv as a row with a spreadsheet icon and a remove button, and the Import button; this dialog does not exist before the PR.

Import dialog listing file problems

Before After
none After

After clicking Import on a CSV with bad rows, the new problems block reads "Nothing was imported. Fix the file and try again:" and lists the problems by row: a tag with a space, a repeated identifier and an empty identifier.

Import button on empty product

Before After
Before After

On a product with no devices, the header now has the Import devices (upload) button next to Add device, and the export menu stays hidden.

rummager · prompts 885379605730 · automated, verify before acting.

@u7d-bot u7d-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Inline findings for 8ee7585a3c. The summary is in the rummager comment.

Comment on lines +185 to +188
case rows do
[] -> {:error, [{"entries", "must have at least one entry"}]}
rows -> {:ok, rows |> Enum.map(&parse_row(&1, columns)) |> refuse_repeated_identifiers()}
end

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[WARNING] The CSV import caps bytes at 32 MB but not rows, so one request can expand into millions of in-memory entries and background inserts. Security · review

A 32 MB body of rows like a1,b c is roughly 5 million rows; each becomes a cell map, a result tuple, an entry in the seen identifier map and, when invalid, a {path, message} problem. All of that is held at once in the request or LiveView process, then either rendered whole into the 422 JSON, kept whole in the :problems assign (only 8 are shown), or copied into the Task that inserts every device serially. Any member or API key with device:create can repeat this concurrently, so refuse a file over a fixed row count (for example {"entries", "must have at most N entries"}) before mapping the rows, and truncate the problems list returned.

defp record_string(attrs, key) do
case attrs[key] do
value when is_binary(value) and value != "" -> {:ok, value}
_ -> {:error, "has a certificate record without a #{key}"}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[WARNING] With key interpolated, this error reads "has a certificate record without a aki", which is ungrammatical. Prose, comments and docs · definite

This text appears in the import dialog and the API's 422 responses. Dropping the article works for every key (serial, aki, not_before, not_after). The assertion in test/nerves_hub/devices/device_csv_test.exs line 197 also needs updating.

Suggested change
_ -> {:error, "has a certificate record without a #{key}"}
_ -> {:error, "has a certificate record without #{key}"}

Comment on lines +72 to +76
case Tag.cast(tags) do
{:ok, tags} -> {:ok, tags}
{:error, message: message} -> {:error, {:invalid_manifest, [{"tags", message}]}}
:error -> {:error, {:invalid_manifest, [{"tags", "must be comma-separated tags"}]}}
end

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] cast_import_tags/1 repeats the same Tag.cast error handling as the private tags/1 in NervesHub.Devices.DeviceCSV. Code quality · definite

Both copies turn {:error, message: m} and :error into the same messages, so if one changes and the other doesn't, the tags header and the CSV tags column will give different errors. Expose one function, for example DeviceCSV.cast_tags/1 returning {:ok, tags} | {:error, message}, and have both callers wrap its result in their own error shape.

u7d-bot added a commit to lawik/rummager-screenshots that referenced this pull request Dec 3, 2026
u7d-bot added a commit to lawik/rummager-screenshots that referenced this pull request Dec 3, 2026
u7d-bot added a commit to lawik/rummager-screenshots that referenced this pull request Dec 3, 2026
u7d-bot added a commit to lawik/rummager-screenshots that referenced this pull request Dec 3, 2026
u7d-bot added a commit to lawik/rummager-screenshots that referenced this pull request Dec 3, 2026
u7d-bot added a commit to lawik/rummager-screenshots that referenced this pull request Dec 3, 2026
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.

Feature: Export product/devices

2 participants