Public Access
Import a Hetzner Cloud project's servers, and forget the token that read it
An estate on Hetzner is already described somewhere: the project lists every server, its addresses, its plan and where it runs. Getting that into a keychain meant copying forty addresses out of a browser by hand, which is the same work the ssh_config importer exists to remove for the machines described in a file. ◆ A WIZARD RATHER THAN A SCREEN, AND THE DIFFERENCE IS WHAT EACH STEP COSTS. ImportScreen reads a file that is already on this machine, so it scans on open and shows a list. This cannot: it needs a credential that has to be made in another company's console first, and then it makes a request over the internet. Those are two moments rather than one, and a screen that mixed the token box in with the list would ask for the credential again every time somebody came back to look at the list. So three steps — token, choose, done — and the first two write nothing. Step two carries one address choice, one login user and one port for the whole import, because an estate is reached the same way throughout and a per-server dropdown would be forty answers to one question. ◆ THE TOKEN IS USED ONCE AND CLEARED, INCLUDING WHEN IT WORKED. The half worth stating is the success path. Clearing only on failure would leave a credential capable of listing somebody's whole estate sitting in a text box for as long as they spend reading forty rows, which is the longest anybody stands on this screen. Nothing writes it to the vault, to settings or to a log, and reopening the wizard restarts at step one rather than resuming — a resumed step two would be a list nothing on screen has the means to refresh, going on looking current for as long as the application stays open. Read is the only permission it needs and the note above the box says so: a Read & Write token would work identically here and would be a credential capable of deleting the estate, pasted in for no gain. The note also says a token belongs to one project — there is no API call that will say which, and none that lists the others — so an account with four projects runs this four times. Without that sentence the wizard looks like it lost most of the estate. ◆ THE ADDRESS IS A CHOICE, AND TWO OF THE THREE FALL BACK WHERE THE THIRD MUST NOT. Public IPv4 and public IPv6 fall back to each other: the same machine over the same internet, so the worst case is a route nobody picked, and the row says which. Private does not fall back at all. A server on no private network is simply not importable under that choice — its tickbox is disabled, and neither direction of the header's tick-all can reach it — because falling back would put an address on the open internet into a bookmark that was asked to stay off it. IPv6 needs saying twice over. Hetzner routes a whole /64 and the API reports the network, which nothing can dial; the address a stock image answers on is the first one in it. That is a convention of Hetzner's own images rather than a fact the API stated, so every use of it carries a warning on the row and in the stored note, and it is computed by setting the low byte rather than by string surgery on the prefix. It is not an edge case either — IPv4 is billed separately now and a project built since then can be entirely IPv6-only. ◆ NOTHING IMPORTED HERE AUTHENTICATES, AND THAT IS SAID BEFORE THE BUTTON. Hetzner has never held the private half of an SSH key. The API will name a project's keys and hand over their public halves; there is no private half to bring. So every host arrives bound to nothing and asks for a password until somebody points it at a key already in the keychain — the same shape an ssh_config import has with its key tick off, and stated above the button on the same reasoning: somebody who is not told will conclude the import was broken. What the note keeps is what does not go stale — the id, the plan, the location, the image, the labels. The power state is a column and never a note: "running" about a machine somebody switched off last March is worse than no note. ◆ WHERE IT LIVES: TWO FLAGS OVER ONE CONTENT COLUMN. Drawn over the Preferences page inside settings mode exactly as ImportScreen is, with SettingsNav unmoved and the titlebar offering "Back to preferences". IsHetznerImportOpen is a second flag rather than a "which importer" enum, because they are two independent facts about the content column and a single value would need a "neither" member IsImportOpen already expresses; what keeps them from both being true is that every path that opens one closes the other. The titlebar and the Preferences page ask IsImporterOpen, which is written against both. Preferences grows a second importer row beside the first rather than one row that asks "from where?", which would put a question in front of the far more common answer. ◆ WHAT IS NOT HERE. Hetzner's Robot — dedicated servers and Storage Boxes — is a different API behind a different credential, and nothing in this touches it. Said on the Preferences row and on the token step rather than left to be discovered by an account that has both. And there is no phone layout. This one would work on Android, unlike the ssh_config importer beside it: it is a token and a network request, the view model is shared already, and scoped storage has nothing to do with it. What is missing is a screen — the desktop draws a five-column table, and the phone version of that is a different layout rather than the same one narrower. Recorded in android-port.md and on the phone's own Preferences screen, because the note there previously read as though no import of any kind could work. ◆ TESTS, AND WHAT IS LEFT FOR A PERSON. HetznerCloudClientTests is 16 cases over the shapes the API actually returns, against a stubbed HttpMessageHandler: paging followed, the token in a header and never a query string, a refused token distinguished from a fault at Hetzner's end, a token with a line break refused before anything is sent, the /64, the private-network asymmetry, and a server the API described without a name. ShellFlowTests.Hetzner.cs is 11 more against this fixture's real vault, real cache and real server — split into a file of its own, as FakeVaultServer keeps its team endpoints. What they establish beyond the reader's own suite is the half it cannot reach: that reading stores nothing, that importing goes through the ordinary create-and-push path and lands on the server with nothing pressing Sync, that a server the keychain already has arrives unticked, and that the token does not outlive the request. Two layout cases measure both steps against the same content budget every other settings page gets, which is also what proves the markup binds to names that exist. Manual checks 2.11a–2.11d are what no test in this repository can do, because there is no account, no token and no network in the ordinary suite: a real project listed against the real console, a wrong token, the private choice, and what an imported host does when you connect to it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
56c19b006d
commit
c270f3fe39
19 files changed
+2903
-17
No files matched your search
@@ -0,0 +1,646 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using DodoSSH.Client.Import;
|
||||
|
||||
namespace DodoSSH.Client.Shell.ViewModels;
|
||||
|
||||
/// <summary>Which of the wizard's three steps is on screen.</summary>
|
||||
/// <remarks>
|
||||
/// A wizard rather than one screen, unlike <see cref="ImportViewModel"/>, and the reason is what each step
|
||||
/// costs. Reading an <c>ssh_config</c> is free and local, so that screen scans the moment it opens and shows
|
||||
/// a list. This one cannot: it needs a credential the user has to go and make in somebody else's console,
|
||||
/// and it then makes a request over the internet. Those are two different moments, and a screen that mixed
|
||||
/// the token box in with the list would ask for the credential again every time somebody came back to look
|
||||
/// at the list.
|
||||
/// </remarks>
|
||||
internal enum HetznerImportStep
|
||||
{
|
||||
/// <summary>Paste a token. Nothing has been sent yet.</summary>
|
||||
Token = 0,
|
||||
|
||||
/// <summary>The project's servers, and what to do with them. Nothing has been stored yet.</summary>
|
||||
Choose = 1,
|
||||
|
||||
/// <summary>What was stored.</summary>
|
||||
Done = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One Hetzner server, as a row somebody decides about.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The address is not a property of the server but of the server <em>and the choice above the list</em>, so
|
||||
/// it is pushed down by <see cref="Refresh"/> rather than computed here — the same shape
|
||||
/// <see cref="ImportRowViewModel.ImportsItsKey"/> has, and for the same reason: a control that decides one
|
||||
/// thing for forty rows belongs above the forty rows.
|
||||
/// </remarks>
|
||||
internal sealed partial class HetznerRowViewModel(HetznerServer server) : ObservableObject
|
||||
{
|
||||
private HetznerAddress? resolved;
|
||||
|
||||
internal HetznerServer Server => server;
|
||||
|
||||
internal string Name => server.Name;
|
||||
|
||||
/// <summary>Whether it is running, off, or somewhere in between — a fact of the moment, never stored.</summary>
|
||||
internal string Status => server.Status;
|
||||
|
||||
/// <summary>The plan and where it runs, as one cell.</summary>
|
||||
internal string Kind => (server.ServerType, server.Location) switch
|
||||
{
|
||||
({ Length: > 0 } plan, { Length: > 0 } place) => $"{plan} · {place}",
|
||||
({ Length: > 0 } plan, _) => plan,
|
||||
(_, { Length: > 0 } place) => place,
|
||||
_ => "—",
|
||||
};
|
||||
|
||||
/// <summary>What this row would dial, or an em dash where the address choice leaves it nothing.</summary>
|
||||
internal string Address => resolved?.Value ?? "—";
|
||||
|
||||
/// <summary>Whether the address choice above the list can reach this server at all.</summary>
|
||||
/// <remarks>
|
||||
/// False is the private-network case: a server on no private network has no private address, and this
|
||||
/// import will not quietly fall back to a public one. Such a row cannot be ticked, which is what stops
|
||||
/// an import that was asked to stay off the internet from putting a public address in the keychain.
|
||||
/// </remarks>
|
||||
internal bool CanImport => resolved is not null;
|
||||
|
||||
/// <summary>Whether the keychain already has a host pointing where this one would.</summary>
|
||||
internal bool AlreadyPresent { get; private set; }
|
||||
|
||||
/// <summary>What had to be assumed to reach that address, if anything.</summary>
|
||||
internal string Warning => resolved?.Warning ?? string.Empty;
|
||||
|
||||
internal bool HasWarning => resolved?.Warning is { Length: > 0 };
|
||||
|
||||
/// <summary>
|
||||
/// The row's own chip: the single most actionable thing true about it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Ordered by what a person has to do something about. "No address" means this row cannot be imported
|
||||
/// at all and wins outright; a warning is a fact about where it will connect and wins over "already
|
||||
/// here", which is only about whether it is worth ticking. Deliberately parallel to
|
||||
/// <see cref="ImportRowViewModel.Meaning"/> — the same three states plus the one that screen cannot
|
||||
/// have, because a resolved <c>ssh_config</c> entry always has a hostname.
|
||||
/// </remarks>
|
||||
internal string Meaning => (CanImport, HasWarning, AlreadyPresent) switch
|
||||
{
|
||||
(false, _, _) => "no address of that kind",
|
||||
(_, true, _) => Warning,
|
||||
(_, _, true) => "already here",
|
||||
_ => "new host",
|
||||
};
|
||||
|
||||
internal bool IsMeaningWarned => !CanImport || HasWarning;
|
||||
|
||||
internal bool IsMeaningExisting => CanImport && !HasWarning && AlreadyPresent;
|
||||
|
||||
internal bool IsMeaningNew => CanImport && !HasWarning && !AlreadyPresent;
|
||||
|
||||
/// <summary>The address, resolved, or null where there is none of the chosen kind.</summary>
|
||||
internal HetznerAddress? Resolved => resolved;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isSelected;
|
||||
|
||||
/// <summary>
|
||||
/// Re-resolves this row against the address choice above the list.
|
||||
/// </summary>
|
||||
/// <param name="kind">Which address the import is dialling.</param>
|
||||
/// <param name="isAlreadyPresent">Whether the keychain already holds a host at a given address.</param>
|
||||
/// <param name="resetSelection">
|
||||
/// Whether to put the tick back to its default. True on a fresh scan and after an import — where the
|
||||
/// question "which of these do you want" is being put again — and false when only the address choice
|
||||
/// moved, because throwing away somebody's ticks because they changed a dropdown would be its own bug.
|
||||
/// A row that has lost its address is unticked either way; there is nothing to import.
|
||||
/// </param>
|
||||
internal void Refresh(
|
||||
HetznerAddressKind kind,
|
||||
Func<HetznerAddress, bool> isAlreadyPresent,
|
||||
bool resetSelection)
|
||||
{
|
||||
resolved = server.Resolve(kind);
|
||||
AlreadyPresent = resolved is not null && isAlreadyPresent(resolved);
|
||||
|
||||
if (resetSelection)
|
||||
{
|
||||
// A server the keychain already points at starts unticked, exactly as the ssh_config import's
|
||||
// rows do: importing it again is allowed — a second bookmark for one machine is a thing people
|
||||
// want — but it should take a click rather than be the default.
|
||||
IsSelected = CanImport && !AlreadyPresent;
|
||||
}
|
||||
else if (!CanImport)
|
||||
{
|
||||
IsSelected = false;
|
||||
}
|
||||
|
||||
OnPropertyChanged(nameof(Address));
|
||||
OnPropertyChanged(nameof(CanImport));
|
||||
OnPropertyChanged(nameof(AlreadyPresent));
|
||||
OnPropertyChanged(nameof(Warning));
|
||||
OnPropertyChanged(nameof(HasWarning));
|
||||
OnPropertyChanged(nameof(Meaning));
|
||||
OnPropertyChanged(nameof(IsMeaningWarned));
|
||||
OnPropertyChanged(nameof(IsMeaningExisting));
|
||||
OnPropertyChanged(nameof(IsMeaningNew));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Importing the servers in a Hetzner Cloud project.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Three steps, and the first two write nothing.</b> Step one takes a token and sends one request; step
|
||||
/// two shows what the project holds and lets somebody choose; step three says what was stored. The split is
|
||||
/// the same argument <see cref="ImportViewModel"/> makes — a project with forty servers is forty questions,
|
||||
/// and only the person reading the list knows which of them they want bookmarked — with one addition this
|
||||
/// import has and that one does not: the credential. It has to be fetched from another company's console
|
||||
/// before anything here can happen at all, which is a step whether or not it is drawn as one.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>The token is never stored.</b> It lives in <see cref="Token"/> while the wizard is open and is cleared
|
||||
/// the moment the read is done. Not in the vault, not in settings, not in a log — the next import asks
|
||||
/// again. That is the same reasoning <see cref="ImportViewModel.ImportsKeys"/> gives for not remembering its
|
||||
/// tick: a remembered answer is an answer to a question that was never put twice, and this one would be a
|
||||
/// stored credential capable of listing somebody's whole estate.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Nothing imported here authenticates.</b> Hetzner has never held the private half of an SSH key, so
|
||||
/// every host arrives bound to nothing and asks for a password until somebody points it at a key already in
|
||||
/// the keychain. The screen says so before the button rather than leaving it to be discovered at connect
|
||||
/// time — see <see cref="AuthenticationNote"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal sealed partial class HetznerImportViewModel(
|
||||
VaultViewModel vault,
|
||||
HetznerCloudClient hetzner,
|
||||
Action? onCancel = null) : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// The user a stock Hetzner Linux image logs in as.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Every image Hetzner publishes puts the project's SSH keys on root and no other account exists yet, so
|
||||
/// this is right far more often than it is wrong — and where it is wrong, it is wrong for a whole
|
||||
/// estate at once, which is why the box is above the list rather than on each row.
|
||||
/// </remarks>
|
||||
internal const string DefaultUsername = "root";
|
||||
|
||||
internal ObservableCollection<HetznerRowViewModel> Rows { get; } = [];
|
||||
|
||||
/// <summary>What the project could not be made to say, at project level.</summary>
|
||||
internal ObservableCollection<string> Warnings { get; } = [];
|
||||
|
||||
[ObservableProperty]
|
||||
private HetznerImportStep step = HetznerImportStep.Token;
|
||||
|
||||
/// <summary>
|
||||
/// The Cloud API token, held only for as long as the wizard needs it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A plain bound string, like the passphrase box on the unlock screen, and it carries the same caveat:
|
||||
/// a .NET string cannot be zeroed, so what this really promises is that nothing here writes it anywhere
|
||||
/// that outlives the process. <see cref="ScanAsync"/> clears it as soon as the read is finished.
|
||||
/// </remarks>
|
||||
[ObservableProperty]
|
||||
private string token = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string status = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isBusy;
|
||||
|
||||
/// <summary>The login user every imported host gets.</summary>
|
||||
[ObservableProperty]
|
||||
private string username = DefaultUsername;
|
||||
|
||||
/// <summary>
|
||||
/// The SSH port, as typed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A string rather than an int because a text box passes through "" and "2" on the way to "22", and a
|
||||
/// bound int would either refuse the keystroke or silently substitute a number nobody typed. Parsed by
|
||||
/// <see cref="Port"/>, which is also what <see cref="IsPortValid"/> reports on.
|
||||
/// </remarks>
|
||||
[ObservableProperty]
|
||||
private string portText = HetznerPort.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private const int HetznerPort = 22;
|
||||
|
||||
[ObservableProperty]
|
||||
private HetznerAddressKind addressKind = HetznerAddressKind.PublicIPv4;
|
||||
|
||||
internal bool IsTokenStep => Step is HetznerImportStep.Token;
|
||||
|
||||
internal bool IsChooseStep => Step is HetznerImportStep.Choose;
|
||||
|
||||
internal bool IsDoneStep => Step is HetznerImportStep.Done;
|
||||
|
||||
/// <summary>"Step 2 of 3", for the header — a wizard that does not say how long it is is a maze.</summary>
|
||||
internal string StepLabel => $"STEP {(int)Step + 1} OF 3";
|
||||
|
||||
/// <summary>What this step is for, in the header, beside <see cref="StepLabel"/>.</summary>
|
||||
internal string StepTitle => Step switch
|
||||
{
|
||||
HetznerImportStep.Token => "Connect to a project",
|
||||
HetznerImportStep.Choose => "Choose what to import",
|
||||
_ => "Imported",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Which of the three address chips above the list is lit.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Read-only bools beside a command that sets the enum, rather than two-way bound ones, because the
|
||||
/// control is a chip that runs <see cref="UseAddressCommand"/> — see <c>HetznerImportScreen.axaml</c>
|
||||
/// for why chips rather than radio buttons, which this application has no style for.
|
||||
/// </remarks>
|
||||
internal bool UsesPublicIPv4 => AddressKind is HetznerAddressKind.PublicIPv4;
|
||||
|
||||
/// <inheritdoc cref="UsesPublicIPv4" />
|
||||
internal bool UsesPublicIPv6 => AddressKind is HetznerAddressKind.PublicIPv6;
|
||||
|
||||
/// <inheritdoc cref="UsesPublicIPv4" />
|
||||
internal bool UsesPrivate => AddressKind is HetznerAddressKind.Private;
|
||||
|
||||
/// <summary>What the chosen address means for the list, said once above it rather than per row.</summary>
|
||||
internal string AddressNote => AddressKind switch
|
||||
{
|
||||
HetznerAddressKind.PublicIPv4 =>
|
||||
"The public IPv4 address, which is how all but the cheapest Hetzner servers are reached. A "
|
||||
+ "server with no IPv4 falls back to its IPv6 and the row says so.",
|
||||
HetznerAddressKind.PublicIPv6 =>
|
||||
"The public IPv6 address. Hetzner routes a whole /64 and the API reports the network rather "
|
||||
+ "than an address, so this is the first address in it — where Hetzner's own images put "
|
||||
+ "the server, and not something the API states.",
|
||||
_ =>
|
||||
"The address on the server's own private network, which only reaches it from inside that "
|
||||
+ "network. Servers on no private network are not importable under this choice, and this "
|
||||
+ "will never quietly fall back to a public address.",
|
||||
};
|
||||
|
||||
internal bool HasRows => Rows.Count > 0;
|
||||
|
||||
internal bool HasWarnings => Warnings.Count > 0;
|
||||
|
||||
/// <summary>The port every imported host gets, or null where what is typed is not one.</summary>
|
||||
internal int? Port =>
|
||||
int.TryParse(PortText, NumberStyles.None, CultureInfo.InvariantCulture, out var port)
|
||||
&& port is >= 1 and <= 65535
|
||||
? port
|
||||
: null;
|
||||
|
||||
internal bool IsPortValid => Port is not null;
|
||||
|
||||
internal int SelectedCount => Rows.Count(row => row.IsSelected && row.CanImport);
|
||||
|
||||
internal string ImportLabel => SelectedCount == 1 ? "IMPORT 1 SERVER" : $"IMPORT {SelectedCount} SERVERS";
|
||||
|
||||
/// <summary>How many rows the address choice can actually reach.</summary>
|
||||
internal int ImportableCount => Rows.Count(row => row.CanImport);
|
||||
|
||||
/// <summary>Whether every importable row is ticked — what the header's tick-all box shows.</summary>
|
||||
internal bool AllTicked => ImportableCount > 0 && SelectedCount == ImportableCount;
|
||||
|
||||
/// <summary>Whether IMPORT would do anything.</summary>
|
||||
internal bool CanImport => SelectedCount > 0 && IsPortValid && !IsBusy;
|
||||
|
||||
/// <summary>
|
||||
/// The vault every import lands in — see <see cref="VaultViewModel.ImportHostsAsync"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Fixed rather than offered as a picker, exactly as the ssh_config importer's is: the import goes
|
||||
/// through the same active vault every other bulk write does, and there is no per-import target to bind.
|
||||
/// Printed as a fact instead of drawn as a dropdown.
|
||||
/// </remarks>
|
||||
internal string VaultName => vault.VaultName;
|
||||
|
||||
/// <summary>How many ticked, out of how many, and where they land.</summary>
|
||||
internal string SelectionSummary
|
||||
{
|
||||
get
|
||||
{
|
||||
var noun = Rows.Count == 1 ? "server" : "servers";
|
||||
|
||||
return $"{SelectedCount} of {Rows.Count} {noun} selected · saving to {VaultName}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sentence that says an imported host will not connect on its own.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Said before the button rather than after, on exactly the reasoning <c>ImportScreen.axaml</c> gives
|
||||
/// for its own version: whether the credential comes with the host is the difference between a bookmark
|
||||
/// that connects and one that asks for a password, and somebody who is not told will conclude the
|
||||
/// import was broken.
|
||||
/// </remarks>
|
||||
internal static string AuthenticationNote =>
|
||||
"Hetzner has never held the private half of an SSH key, so nothing here can bring one. A server "
|
||||
+ "imported this way arrives asking for a password until you bind it to a key already in your "
|
||||
+ "keychain — from the host's own editor, or in bulk from the Hosts screen.";
|
||||
|
||||
/// <summary>What the token step says about the token it is asking for.</summary>
|
||||
/// <remarks>
|
||||
/// Three facts, each of which somebody would otherwise have to learn the hard way: a token is per
|
||||
/// project rather than per account, read-only is enough, and nothing here keeps it. The first is the one
|
||||
/// that surprises people — an account with four projects runs this four times, and a wizard that did not
|
||||
/// say so would look like it had lost most of the estate.
|
||||
/// </remarks>
|
||||
internal static string TokenNote =>
|
||||
"A Cloud API token belongs to one project, so this imports one project's servers — an account with "
|
||||
+ "several runs this once per project. Make one in the Hetzner console under Security → API "
|
||||
+ "tokens; Read is the only permission this needs, and the token is used for a single request "
|
||||
+ "and then forgotten. Dedicated servers live behind Hetzner's Robot instead and are not "
|
||||
+ "covered here.";
|
||||
|
||||
/// <summary>Reads the project. Writes nothing, and forgets the token on the way out.</summary>
|
||||
[RelayCommand]
|
||||
private async Task ScanAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
ClearRows();
|
||||
|
||||
IsBusy = true;
|
||||
|
||||
try
|
||||
{
|
||||
var import = await hetzner.ListServersAsync(Token, cancellationToken).ConfigureAwait(true);
|
||||
|
||||
foreach (var server in import.Servers)
|
||||
{
|
||||
var row = new HetznerRowViewModel(server);
|
||||
|
||||
// The footer counts ticks, so it has to hear about one. Subscribed here rather than bound
|
||||
// from the item template, because a template binding cannot reach the list it is inside
|
||||
// without a parent binding — and the count is on the parent by definition.
|
||||
row.PropertyChanged += OnRowChanged;
|
||||
|
||||
Rows.Add(row);
|
||||
}
|
||||
|
||||
foreach (var warning in import.Warnings)
|
||||
{
|
||||
Warnings.Add(warning);
|
||||
}
|
||||
|
||||
Refresh(resetSelection: true);
|
||||
|
||||
if (Rows.Count == 0)
|
||||
{
|
||||
// Deliberately not an error, and deliberately not a step forward: an empty project is a
|
||||
// real answer to a correct token, and a list screen with nothing on it says less than this.
|
||||
Status = "That project has no servers in it.";
|
||||
return;
|
||||
}
|
||||
|
||||
Status = Rows.Count == 1
|
||||
? "Found 1 server. Nothing is stored until you press the button below."
|
||||
: $"Found {Rows.Count} servers. Nothing is stored until you press the button below.";
|
||||
|
||||
Step = HetznerImportStep.Choose;
|
||||
}
|
||||
catch (HetznerCloudException failure)
|
||||
{
|
||||
// Stays on the token step, which is where the box is. See HetznerCloudException.IsTokenProblem
|
||||
// for why a fault at Hetzner's end is worded differently from a refused token even though both
|
||||
// land here: one of them is something the person reading this can act on.
|
||||
Status = failure.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Cleared whatever happened, including on the way to a list somebody is about to import from:
|
||||
// the read is over and the token has no further use. A failed attempt clears it too, so a
|
||||
// mistyped token is retyped rather than corrected in place — the lesser of the two annoyances
|
||||
// against a credential sitting in a text box for the rest of the session.
|
||||
Token = string.Empty;
|
||||
|
||||
IsBusy = false;
|
||||
RaiseListState();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stores the ticked servers as hosts.</summary>
|
||||
[RelayCommand]
|
||||
private async Task ImportAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (Port is not { } port)
|
||||
{
|
||||
Status = "That is not a port. Give a number between 1 and 65535.";
|
||||
return;
|
||||
}
|
||||
|
||||
var chosen = Rows.Where(row => row.IsSelected && row.CanImport).ToList();
|
||||
|
||||
if (chosen.Count == 0)
|
||||
{
|
||||
Status = "Nothing is ticked.";
|
||||
return;
|
||||
}
|
||||
|
||||
IsBusy = true;
|
||||
|
||||
try
|
||||
{
|
||||
var requests = chosen
|
||||
.Select(row => new ImportedHostRequest(
|
||||
row.Server.ToSecret(row.Resolved!, Username, port),
|
||||
Key: null,
|
||||
KeyPath: null))
|
||||
.ToList();
|
||||
|
||||
var outcome = await vault.ImportHostsAsync(requests, cancellationToken).ConfigureAwait(true);
|
||||
|
||||
// Re-resolved rather than cleared, so a row that was just imported now says "already here" —
|
||||
// which is what makes coming back to the list and importing the rest of the project harmless
|
||||
// and visible rather than harmless and confusing.
|
||||
Refresh(resetSelection: true);
|
||||
|
||||
// This screen's own sentence rather than the vault's, which the push that follows an import
|
||||
// overwrites with a sync report — right on a screen somebody is about to leave, wrong on the one
|
||||
// they are still standing on.
|
||||
Status = outcome.Hosts == 1
|
||||
? "Imported 1 server. It is on the Hosts screen, asking for a password until you bind it "
|
||||
+ "to a key."
|
||||
: $"Imported {outcome.Hosts} servers. They are on the Hosts screen, asking for a password "
|
||||
+ "until you bind them to a key.";
|
||||
|
||||
Step = HetznerImportStep.Done;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
RaiseListState();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Back to the token step, with the list dropped.</summary>
|
||||
/// <remarks>
|
||||
/// The list goes because the token did. Nothing here can refresh what it is showing without asking for a
|
||||
/// credential again, and a "back" that left forty rows on screen over a step that no longer has the
|
||||
/// means to have produced them would be showing a list it cannot stand behind.
|
||||
/// </remarks>
|
||||
[RelayCommand]
|
||||
private void Restart()
|
||||
{
|
||||
ClearRows();
|
||||
Status = string.Empty;
|
||||
Step = HetznerImportStep.Token;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Back from the last step to the list, with what was just stored marked as already here.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Unlike <see cref="Restart"/> this keeps the rows, and it can: they were read before the token was
|
||||
/// cleared and nothing about them has to be fetched again. What it does not do is claim they are fresh —
|
||||
/// a server created in the Hetzner console since the scan is not in this list and no screen here says
|
||||
/// otherwise.
|
||||
/// </remarks>
|
||||
[RelayCommand]
|
||||
private void Review()
|
||||
{
|
||||
if (Rows.Count > 0)
|
||||
{
|
||||
Step = HetznerImportStep.Choose;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Points the whole import at one of the three kinds of address.</summary>
|
||||
[RelayCommand]
|
||||
private void UseAddress(HetznerAddressKind kind) => AddressKind = kind;
|
||||
|
||||
/// <summary>Ticks or unticks every importable row at once.</summary>
|
||||
[RelayCommand]
|
||||
private void ToggleAll()
|
||||
{
|
||||
var importable = Rows.Where(row => row.CanImport).ToList();
|
||||
var target = SelectedCount < importable.Count;
|
||||
|
||||
foreach (var row in importable)
|
||||
{
|
||||
row.IsSelected = target;
|
||||
}
|
||||
|
||||
RaiseListState();
|
||||
}
|
||||
|
||||
/// <summary>The footer's Cancel button: back to the Preferences page, nothing stored.</summary>
|
||||
/// <remarks>
|
||||
/// A delegate rather than a reference up to <c>MainWindowViewModel</c>, on the reasoning
|
||||
/// <see cref="ImportViewModel"/>'s own cancel gives: this type has no business knowing settings mode
|
||||
/// exists, and a null delegate — nothing wired, as in a test building this directly — makes the button a
|
||||
/// no-op rather than a crash.
|
||||
/// </remarks>
|
||||
[RelayCommand]
|
||||
private void Cancel() => onCancel?.Invoke();
|
||||
|
||||
/// <summary>Drops the list, unsubscribing from what it held.</summary>
|
||||
/// <remarks>
|
||||
/// The detach matters: rows outlive the list only through this handler, and a scan run four times would
|
||||
/// otherwise leave three sets of dead rows still calling into a live view model on every tick.
|
||||
/// </remarks>
|
||||
private void ClearRows()
|
||||
{
|
||||
foreach (var row in Rows)
|
||||
{
|
||||
row.PropertyChanged -= OnRowChanged;
|
||||
}
|
||||
|
||||
Rows.Clear();
|
||||
Warnings.Clear();
|
||||
RaiseListState();
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// Only the tick moves the footer. Every other property on a row changes as part of a refresh this type
|
||||
/// started, which already ends in <see cref="RaiseListState"/>.
|
||||
/// </remarks>
|
||||
private void OnRowChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs args)
|
||||
{
|
||||
if (string.Equals(args.PropertyName, nameof(HetznerRowViewModel.IsSelected), StringComparison.Ordinal))
|
||||
{
|
||||
RaiseListState();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Re-resolves every row against the current address choice.</summary>
|
||||
private void Refresh(bool resetSelection)
|
||||
{
|
||||
foreach (var row in Rows)
|
||||
{
|
||||
row.Refresh(AddressKind, IsAlreadyPresent, resetSelection);
|
||||
}
|
||||
|
||||
RaiseListState();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the keychain already holds a host that would dial where this one does.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Matched on address, port and user rather than on name, for the reason
|
||||
/// <see cref="ImportViewModel.IsAlreadyPresent"/> gives at more length: a machine bookmarked under
|
||||
/// another name is the same machine, and matching on the label would offer a duplicate of something
|
||||
/// already stored. Compared against the <em>resolved</em> host so that a stored host inheriting its port
|
||||
/// or user from a group still matches.
|
||||
/// </remarks>
|
||||
private bool IsAlreadyPresent(HetznerAddress address) => vault.Hosts.Any(existing =>
|
||||
string.Equals(existing.Host.Hostname, address.Value, StringComparison.OrdinalIgnoreCase)
|
||||
&& existing.Resolved.Port.Value == Port
|
||||
&& string.Equals(
|
||||
existing.Resolved.Username.Value,
|
||||
string.IsNullOrWhiteSpace(Username) ? null : Username.Trim(),
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
partial void OnStepChanged(HetznerImportStep value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsTokenStep));
|
||||
OnPropertyChanged(nameof(IsChooseStep));
|
||||
OnPropertyChanged(nameof(IsDoneStep));
|
||||
OnPropertyChanged(nameof(StepLabel));
|
||||
OnPropertyChanged(nameof(StepTitle));
|
||||
}
|
||||
|
||||
partial void OnAddressKindChanged(HetznerAddressKind value)
|
||||
{
|
||||
OnPropertyChanged(nameof(UsesPublicIPv4));
|
||||
OnPropertyChanged(nameof(UsesPublicIPv6));
|
||||
OnPropertyChanged(nameof(UsesPrivate));
|
||||
OnPropertyChanged(nameof(AddressNote));
|
||||
|
||||
Refresh(resetSelection: false);
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// The user and the port are half of what "already here" is decided on, so changing either has to
|
||||
/// re-ask the question — otherwise a row would go on claiming the keychain has it while the thing it
|
||||
/// would now store is different.
|
||||
/// </remarks>
|
||||
partial void OnUsernameChanged(string value) => Refresh(resetSelection: false);
|
||||
|
||||
/// <inheritdoc cref="OnUsernameChanged" />
|
||||
partial void OnPortTextChanged(string value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsPortValid));
|
||||
|
||||
Refresh(resetSelection: false);
|
||||
}
|
||||
|
||||
partial void OnIsBusyChanged(bool value) => OnPropertyChanged(nameof(CanImport));
|
||||
|
||||
private void RaiseListState()
|
||||
{
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
OnPropertyChanged(nameof(HasWarnings));
|
||||
OnPropertyChanged(nameof(SelectedCount));
|
||||
OnPropertyChanged(nameof(ImportableCount));
|
||||
OnPropertyChanged(nameof(ImportLabel));
|
||||
OnPropertyChanged(nameof(AllTicked));
|
||||
OnPropertyChanged(nameof(CanImport));
|
||||
OnPropertyChanged(nameof(SelectionSummary));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user