diff --git a/CHANGELOG.md b/CHANGELOG.md index c3199ea6..6310fe96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,23 @@ release version + date and opens a fresh `[Unreleased]`. demo entry exists, and removing it (the bin icon in the server list) throws everything away. Adding a real server while in the demo switches to it. +- **NOVA hides the buttons your API key cannot use** — with a read-only key (the + VIEWER role), the Docker, VMs and Array tabs and the container, VM and + notification sheets no longer show Start, Stop, Restart, Update, parity check, + Archive or Delete buttons. One note in their place says "View only" and which + permission the key would need, for example DOCKER:UPDATE_ANY, with a link to + the list of permissions. A key with only some permissions keeps exactly the + buttons it may use. If NOVA cannot find out what the key may do, it shows the + buttons as before. And if the server still refuses an action, the message now + names the missing permission instead of "Forbidden resource" (#315, #316). + +- **"Test" in the Add server sheet now checks the key** — it used to report + "Connected" for any key, even a wrong one. Now a key the server does not accept + fails the test, and a working key shows the Unraid and API version and whether it + is "View only" or can control Docker, VMs and so on. The API Key field has a + hint and a "Which permissions?" link to the table of what each feature needs + (#315, #316). + ### Changed - **Restarting a container is one step on newer servers** — on Unraid API 4.36.0 @@ -56,6 +73,11 @@ release version + date and opens a fresh `[Unreleased]`. ### Fixed +- **Resume on a paused container now works** — the Resume button in the Docker tab asked the + server to start the container, which Docker refuses for a paused one, so the container stayed + paused and the app showed an error. Resume now sends the "unpause" action; Start on a stopped + container is unchanged (#345). + - **A turned-off service no longer makes the whole server look offline** — with VMs or Docker switched off, the pill at the top used to read "Offline" even though the server answered. Now only a server that really cannot be reached @@ -68,6 +90,29 @@ release version + date and opens a fresh `[Unreleased]`. every time you open it or come back to it, so the notice is on the first screen. +- **NOVA no longer sends your API key along when a server redirects it** — it + used to follow a redirect and take the key with it, to another address or from + https down to plain http. Now a redirect is not followed: the tab, **Test** + and the action message say "The server redirects to …" and name the address, + and you enter that address in the server's settings. This is what Unraid does + when you type an `http` address while its SSL setting is Yes or Strict: it + points to the `https` address, which is the one to enter (#354). + +- **The Overview explains why it could not load and keeps its attention card** — + when every part of the Overview failed, it always said "Can't reach the server". + It now gives the same reason as the tabs, for example that the server did not + accept the key. And with Docker or VMs switched off, the "Needs attention" card + stays, because the server itself is still reachable (#217). + +- **The "Needs attention" card also appears when Docker or VMs are off, and unknown + counts show a dash** — the card used to disappear whenever Docker or the VM + manager was switched off on the server, or the API key may not read them, even + though the server answered and the array needed you. It now stays. And the + Containers and Virtual machines cards show "—" instead of "0 running · all + healthy" or "0 configured" while NOVA does not know the numbers yet (not + loaded, turned off, not allowed or not reachable). A server that really has + none still shows 0 (#356). + ## [0.1.48] - 2026-11-13 The Overview now tells you when something on your server needs you, and the Docker tab can search and group containers by Compose project. A new "Needs attention" card at the top of the Overview lists what needs you, most urgent first; on a healthy server it is not there, so a quiet Overview is normal. The Docker tab has a search field with a clear button, and a new "Compose" option for the Docker view (Settings, Layout) groups containers by their Compose project. The 0.1.48 beta confirmed the search, the Compose option and the quiet Overview on a real phone. Some groundwork in this release has no visible change yet (detecting the server's API version and what the API key may do, and the rules for later opt-in alerts). As in 0.1.47, NOVA does not install updates itself: "Download" opens the release file in your browser. diff --git a/HANDOFF.md b/HANDOFF.md index 8c29d288..9313af58 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -111,7 +111,7 @@ _Toolchain raised in the 0.1.28 cycle — see ADR-0023 (AGP-9) / ADR-0024 app/src/main/ ├── graphql/io/github/nofuturekid/nova/ │ ├── schema.graphqls hand-written subset of the unraid/api generated-schema.graphql -│ ├── queries.graphql Ping, GetServerInfo/Metrics/NetworkThroughput/Display/Array/DockerContainers/Vms, +│ ├── queries.graphql GetServerInfo/Metrics/NetworkThroughput/Display/Array/DockerContainers/Vms, │ │ notifications (overview + list), plugins, plugin ops, installed .plg, NetworkInterfaces, FetchContainerLogs │ ├── mutations.graphql Array, Docker (start/stop/pause/unpause/update/updateAll), Vm (start/stop/pause/resume/ │ │ forceStop/reboot/reset), parityCheck, notification actions diff --git a/README.md b/README.md index 0f5eb66a..0cbad416 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ A few things bend to taste in **Settings**: 2. On your Unraid server, generate an **API key**: web UI → _Settings → Management Access → API / Connect_ (which rights it needs: [API key permissions](#api-key-permissions)). 3. Open the app → **Add server** and fill in: - **Server name** — a label, e.g. `Tower` - - **Local host** — its address on your home network, e.g. `192.168.1.10`. Flip **Use SSL (HTTPS)** if the server uses HTTPS; for a self-signed certificate also enable **Trust self-signed certificate** and confirm it once + - **Local host** — its address on your home network, e.g. `192.168.1.10`. Flip **Use SSL (HTTPS)** if the server uses HTTPS; for a self-signed certificate also enable **Trust self-signed certificate** and confirm it once. If your server's _Use SSL/TLS_ setting is _Yes_ or _Strict_, it answers a plain `http` request with a redirect to `https`; NOVA does not follow redirects (the API key would travel with it), so enter the address it names, with **Use SSL (HTTPS)** on. A tab or **Test** shows it as "The server redirects to …" - **Remote host (Unraid Connect)** — optional, e.g. `your-server.unraid.net`, for when you're away (with its own **Use SSL (HTTPS)** switch) - **API Key** — the one you just generated 4. Tap **Test** (next to the local and/or remote connection), then **Save**. The pill in the top bar flips between **Local** and **Remote**. @@ -109,7 +109,7 @@ Requires an Unraid 7.x server with the API/Connect plugin enabled. All app featu NOVA talks to your server with one API key per server. **NOVA never needs the ADMIN role or any permission to manage API keys.** Pick whichever of these suits you: -- **Simplest, read-only: a key with the VIEWER role.** It can see everything NOVA shows and cannot change anything, except that servers older than Unraid API 4.37.4 let every key archive and delete notifications [^4]. Buttons that need more rights are refused by the server. +- **Simplest, read-only: a key with the VIEWER role.** It can see everything NOVA shows and cannot change anything, except that servers older than Unraid API 4.37.4 let every key archive and delete notifications [^4]. NOVA hides the buttons that need more rights. - **Simplest, full control: a key with the ADMIN role.** It can do everything NOVA offers. It can also do much more, which NOVA never uses. - **Least privilege: the VIEWER role plus only the controls you want.** See the table below. @@ -155,7 +155,7 @@ The command shape, with the VIEWER role and `DOCKER:UPDATE_ANY`, was run live an ### When a permission is missing -The server decides, not NOVA. An action the key may not do is refused with the message **"Forbidden resource"** and nothing changes on the server (confirmed live for container actions with a VIEWER key). A read the key may not do is refused the same way, so that screen fails to load. A key the server does not accept at all is answered with "API key validation failed". A later version of NOVA will hide the controls a key cannot use instead of showing buttons that are refused. +The server decides, not NOVA. An action the key may not do is refused with the message **"Forbidden resource"** and nothing changes on the server (confirmed live for container actions with a VIEWER key). A read the key may not do is refused the same way, so that screen fails to load. A key the server does not accept at all is answered with "API key validation failed". NOVA asks the server what the key may do and hides the controls it cannot use, with one "View only" note in their place that names the permission. If NOVA cannot find that out, it shows the buttons, and a refused action then says which permission is missing. ### Which Unraid API version you need diff --git a/app/src/main/graphql/io/github/nofuturekid/nova/queries.graphql b/app/src/main/graphql/io/github/nofuturekid/nova/queries.graphql index b9b792de..f5bae79c 100644 --- a/app/src/main/graphql/io/github/nofuturekid/nova/queries.graphql +++ b/app/src/main/graphql/io/github/nofuturekid/nova/queries.graphql @@ -1,7 +1,3 @@ -query Ping { - __typename -} - query FetchContainerLogs($id: PrefixedID!, $tail: Int) { docker { logs(id: $id, tail: $tail) { diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/api/ApolloClientFactory.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/api/ApolloClientFactory.kt index e48ce76a..5160d541 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/api/ApolloClientFactory.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/api/ApolloClientFactory.kt @@ -14,7 +14,11 @@ import javax.inject.Inject import javax.inject.Singleton /** - * Builds per-server [ApolloClient] instances. Four variants: + * Builds per-server [ApolloClient] instances. Four variants. None of them follows a redirect + * (ADR-0051): every client here sends the API key, and OkHttp would send it on to whatever a 3xx + * answer's `Location` names, another host or plain http. A redirect comes back as the response + * (an `ApolloHttpException` with the status and the `Location` header) and is reported as + * [io.github.nofuturekid.nova.data.repository.ErrorReason.Redirected]. * * - [build] — short timeouts (8 s connect, 15 s read/write). Used for * polling queries and short-lived mutations (start/stop/pause/etc.). @@ -28,9 +32,9 @@ import javax.inject.Singleton * Per ADR-0016 these get their own client so the polling timeout * doesn't have to be relaxed globally. * - * - [buildBackground] — the polling client for the background alert check: no redirect is - * followed and no cleartext connection is made, so the API key stays on the https address it - * was sent to. Only the background check uses it; the foreground is unchanged. + * - [buildBackground] — the polling client for the background alert check: like the others it + * follows no redirect, and on top of that no cleartext connection is made, so the API key stays + * on the https address it was sent to. Only the background check uses it. * * - [buildWs] — WebSocket-only client for GraphQL subscriptions. Reuses * the existing self-signed TLS pin (ADR-0041) via [applyTrust]. Uses @@ -50,7 +54,7 @@ open class ApolloClientFactory @Inject constructor() { const val WS_PING_INTERVAL_S = 15L } - private val baseHttpClient: OkHttpClient by lazy { + internal val baseHttpClient: OkHttpClient by lazy { val logging = HttpLoggingInterceptor().apply { level = if (io.github.nofuturekid.nova.BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BASIC @@ -62,10 +66,12 @@ open class ApolloClientFactory @Inject constructor() { .readTimeout(15, TimeUnit.SECONDS) .writeTimeout(15, TimeUnit.SECONDS) .addInterceptor(logging) + .followRedirects(false) + .followSslRedirects(false) .build() } - private val longRunningHttpClient: OkHttpClient by lazy { + internal val longRunningHttpClient: OkHttpClient by lazy { val logging = HttpLoggingInterceptor().apply { level = if (io.github.nofuturekid.nova.BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BASIC @@ -77,6 +83,8 @@ open class ApolloClientFactory @Inject constructor() { .readTimeout(10, TimeUnit.MINUTES) .writeTimeout(10, TimeUnit.MINUTES) .addInterceptor(logging) + .followRedirects(false) + .followSslRedirects(false) .build() } @@ -115,8 +123,9 @@ open class ApolloClientFactory @Inject constructor() { open fun build(baseUrl: String, apiKey: String, trust: TlsTrust = TlsTrust.Default): ApolloClient = cached("short", baseHttpClient, baseUrl, apiKey, trust) - /** Same as [build] but for the background alert check ([backgroundHttpClient]): https only, - * no redirect is followed. The foreground variants are not affected. */ + /** Same as [build] but for the background alert check ([backgroundHttpClient]): https only. + * Like every client here it follows no redirect; the background client states that itself + * so it does not depend on the base client. */ fun buildBackground(baseUrl: String, apiKey: String, trust: TlsTrust = TlsTrust.Default): ApolloClient = cached("bg", backgroundHttpClient, baseUrl, apiKey, trust) diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoState.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoState.kt index 28b106ae..4d8a794a 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoState.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoState.kt @@ -104,11 +104,18 @@ data class DemoState( private fun withContainer(id: String, f: (Container) -> Container) = copy(containers = containers.map { if (it.id == id) f(it) else it }) - fun startContainer(id: String) = withContainer(id) { it.copy(status = ContainerStatus.Running) } + /** Docker refuses `start` for a paused container; it needs [unpauseContainer] (#345). */ + fun startContainer(id: String) = withContainer(id) { + if (it.status == ContainerStatus.Paused) it else it.copy(status = ContainerStatus.Running) + } + + fun unpauseContainer(id: String) = withContainer(id) { + if (it.status == ContainerStatus.Paused) it.copy(status = ContainerStatus.Running) else it + } fun stopContainer(id: String) = withContainer(id) { it.copy(status = ContainerStatus.Exited) } /** Restart ends running, also for a container that was stopped. */ - fun restartContainer(id: String) = startContainer(id) + fun restartContainer(id: String) = withContainer(id) { it.copy(status = ContainerStatus.Running) } fun pauseContainer(id: String) = withContainer(id) { if (it.status == ContainerStatus.Running) it.copy(status = ContainerStatus.Paused) else it diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoUnraid.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoUnraid.kt index 801c6fb4..2953cbd3 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoUnraid.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/demo/DemoUnraid.kt @@ -156,7 +156,8 @@ class DemoUnraid internal constructor( fun startArray() = act { it.startArray() } fun stopArray() = act { it.stopArray() } - fun startContainer(id: String) = act { it.startContainer(id) } + fun startContainer(id: String, paused: Boolean) = + act { if (paused) it.unpauseContainer(id) else it.startContainer(id) } fun stopContainer(id: String) = act { it.stopContainer(id) } fun restartContainer(id: String) = act { it.restartContainer(id) } fun pauseContainer(id: String) = act { it.pauseContainer(id) } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/CapabilityProbe.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/CapabilityProbe.kt index f20ed075..038b8704 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/CapabilityProbe.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/CapabilityProbe.kt @@ -30,6 +30,10 @@ data class ProbeOutcome( /** The version query failed validation: the API is older than 4.15.0. */ val versionFieldMissing: Boolean = false, val access: KeyAccess = KeyAccess.Unknown, + /** Set with [Detection.Failed]: the transport exception (a certificate problem is told apart by the caller). */ + val cause: Throwable? = null, + /** Set with [Detection.Failed] when the server answered with an error NOVA does not classify: its own text. */ + val failureText: String? = null, ) { fun toCapabilities(target: CapabilityTarget?) = ServerCapabilities( target = target, @@ -54,21 +58,21 @@ internal fun classifyErrors(errors: List): ErrorClass = when { else -> ErrorClass.Other } -private fun Error.code(): Any? = extensions?.get("code") +internal fun Error.code(): Any? = extensions?.get("code") private sealed interface VersionStep { data class Got(val unraid: String?, val apiText: String?) : VersionStep data object Missing : VersionStep data object Unknown : VersionStep data object Rejected : VersionStep - data object Failed : VersionStep + data class Failed(val cause: Throwable? = null, val text: String? = null) : VersionStep } private sealed interface AccessStep { data class Got(val access: KeyAccess.Known) : AccessStep data object Unknown : AccessStep data object Rejected : AccessStep - data object TransportFailed : AccessStep + data class TransportFailed(val cause: Throwable? = null) : AccessStep } /** @@ -80,7 +84,7 @@ internal suspend fun probeCapabilities(client: ApolloClient): ProbeOutcome { val version = probeVersion(client) when (version) { VersionStep.Rejected -> return ProbeOutcome(Detection.KeyRejected) - VersionStep.Failed -> return ProbeOutcome(Detection.Failed) + is VersionStep.Failed -> return ProbeOutcome(Detection.Failed, cause = version.cause, failureText = version.text) else -> Unit } val versionKnown = version is VersionStep.Got || version == VersionStep.Missing @@ -98,7 +102,8 @@ internal suspend fun probeCapabilities(client: ApolloClient): ProbeOutcome { is AccessStep.Got -> base.copy(access = access.access) AccessStep.Unknown -> base AccessStep.Rejected -> ProbeOutcome(Detection.KeyRejected) - AccessStep.TransportFailed -> if (versionKnown) base else ProbeOutcome(Detection.Failed) + is AccessStep.TransportFailed -> + if (versionKnown) base else ProbeOutcome(Detection.Failed, cause = access.cause) } } @@ -112,15 +117,15 @@ private suspend fun probeVersion(client: ApolloClient): VersionStep = try { ErrorClass.KeyRejected -> VersionStep.Rejected ErrorClass.ValidationFailed -> VersionStep.Missing ErrorClass.Forbidden -> VersionStep.Unknown - ErrorClass.Other -> VersionStep.Failed + ErrorClass.Other -> VersionStep.Failed(text = errors.first().message) } // Transport failure, or a body without data and without errors. - else -> VersionStep.Failed + else -> VersionStep.Failed(cause = resp.exception) } } catch (e: CancellationException) { throw e } catch (e: Exception) { - VersionStep.Failed + VersionStep.Failed(cause = e) } private suspend fun probeAccess(client: ApolloClient): AccessStep = try { @@ -141,10 +146,10 @@ private suspend fun probeAccess(client: ApolloClient): AccessStep = try { // FORBIDDEN (a key without ME:READ_ANY), validation and any other error: fail open. else -> AccessStep.Unknown } - else -> AccessStep.TransportFailed + else -> AccessStep.TransportFailed(resp.exception) } } catch (e: CancellationException) { throw e } catch (e: Exception) { - AccessStep.TransportFailed + AccessStep.TransportFailed(e) } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/DomainState.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/DomainState.kt index 985f6595..3070f1b1 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/DomainState.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/DomainState.kt @@ -64,6 +64,13 @@ enum class ErrorReason { /** The server is fine but the service behind this domain (Docker, VM manager) is turned off. */ ServiceOff, + /** + * The server answered with a redirect (3xx). The app does not follow it, because the API key + * would go with it (ADR-0051); the message names where it points so the user can enter that + * address. The server is reachable, so this is not a [isConnectionProblem]. + */ + Redirected, + /** Any other error the server reported; its own text is shown. */ ServerError, ; diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt index d8c4a9a7..6ac5cfaf 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifier.kt @@ -8,6 +8,12 @@ import com.apollographql.apollo.exception.ApolloHttpException import com.apollographql.apollo.exception.ApolloNetworkException import io.github.nofuturekid.nova.data.api.CertIssue import io.github.nofuturekid.nova.data.api.certIssue +import io.github.nofuturekid.nova.data.model.Access +import io.github.nofuturekid.nova.data.model.ApiVersion +import io.github.nofuturekid.nova.data.model.KeyAction +import io.github.nofuturekid.nova.data.model.Detection +import io.github.nofuturekid.nova.data.model.ServerCapabilities +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import java.io.InterruptedIOException import java.net.SocketException import java.net.UnknownHostException @@ -42,7 +48,8 @@ fun classifyResponse( ): RespClass = when { exception != null -> { val issue = exception.certIssue() - if (issue != null) RespClass.Cert(issue) else RespClass.Failed(exception.failureMessage("Network error")) + if (issue != null) RespClass.Cert(issue) + else RespClass.Failed(exception.redirectMessage() ?: exception.failureMessage("Network error")) } hasErrors -> RespClass.Failed(errorMessage ?: "Unknown GraphQL error") dataIsNull -> RespClass.Empty @@ -52,7 +59,8 @@ fun classifyResponse( /** * Why a domain query failed, by the response it got. The first matching rule wins * (the bodies behind them were recorded from Unraid 7.4.0, API 4.37.11): - * 1. a transport exception: [ErrorReason.Unreachable]; + * 1. a transport exception: [ErrorReason.Unreachable], or [ErrorReason.Redirected] when the + * server answered with a redirect, which the clients do not follow (ADR-0051); * 2. `UNAUTHENTICATED`: [ErrorReason.KeyRejected]; * 3. `GRAPHQL_VALIDATION_FAILED` or "Cannot query field": [ErrorReason.ApiTooOld]; * 4. `FORBIDDEN`: [ErrorReason.Forbidden]; @@ -62,7 +70,9 @@ fun classifyResponse( * cannot disagree about what an `errors` array means. */ fun classifyErrorReason(exception: ApolloException?, errors: List?): ErrorReason { - if (exception != null) return ErrorReason.Unreachable + if (exception != null) { + return if (exception.redirectMessage() != null) ErrorReason.Redirected else ErrorReason.Unreachable + } val list = errors.orEmpty() return when (classifyErrors(list)) { ErrorClass.KeyRejected -> ErrorReason.KeyRejected @@ -92,6 +102,30 @@ fun graphQlError(message: String, errors: List?): DomainState.Error { /** What Unraid's resolvers throw when the service behind a domain is off (Docker: missing socket; VMs: no hypervisor). */ private val SERVICE_OFF_MARKERS = listOf("Docker socket unavailable", "VMs are not available") +/** The statuses OkHttp follows by default; the clients here follow none of them (ADR-0051). */ +private val REDIRECT_STATUSES = setOf(300, 301, 302, 303, 307, 308) + +/** + * The sentence for a server that answered with a redirect, or null when this failure is not one. + * The clients do not follow redirects (the API key would go with them, ADR-0051), so a 3xx + * arrives here as an [ApolloHttpException] with its `Location` header. The target is shown as + * `scheme://host[:port]` only: the path says nothing the user can act on, a query may carry + * tokens, and `user:password@` must never be echoed. A missing, relative or unparsable + * `Location` gets the same advice without a target. + */ +fun ApolloException.redirectMessage(): String? { + if (this !is ApolloHttpException || statusCode !in REDIRECT_STATUSES) return null + val location = headers.firstOrNull { it.name.equals("Location", ignoreCase = true) }?.value + val target = location?.trim()?.toHttpUrlOrNull()?.newBuilder() + ?.username("")?.password("")?.encodedPath("/")?.query(null)?.fragment(null) + ?.build()?.toString()?.removeSuffix("/") + return if (target != null) { + "The server redirects to $target. Edit the server and enter that address." + } else { + "The server redirects to another address, but doesn't say which. Check the address in this server's settings." + } +} + /** * The text to show for a failed request: the exception's own message plus its * innermost cause. Apollo reports any parsing failure as "Error while reading @@ -145,6 +179,9 @@ private const val MAX_CAUSE_DEPTH = 10 */ fun Throwable.toQueryError(fallback: String): DomainState.Error { val text = failureMessage(fallback) + (this as? ApolloException)?.redirectMessage()?.let { + return DomainState.Error(it, detail = text, reason = ErrorReason.Redirected) + } return if (isServerUnreachable()) DomainState.Error(UNREACHABLE_MESSAGE, detail = text) else DomainState.Error(text) } @@ -153,7 +190,31 @@ fun Throwable.toQueryError(fallback: String): DomainState.Error { * is the honest, cause-carrying text ([failureMessage] for transport errors, * the joined GraphQL error messages otherwise) and is what the user sees. */ -class ActionFailedException(message: String, cause: Throwable? = null) : Exception(message, cause) +class ActionFailedException( + message: String, + cause: Throwable? = null, + /** The server's own wording when [message] replaces it with plain words (a refused permission); else null. */ + val detail: String? = null, +) : Exception(message, cause) + +/** + * The plain sentence for an action the server refused because of the key (#315, ADR-0047), or + * null for any other failure. `FORBIDDEN` names the permission the control needs when + * [operationName] is one of NOVA's mutations ([KeyAction.forOperation]); `UNAUTHENTICATED` says + * the key was not accepted. This is the fallback path: while the key's access is unknown the + * buttons are shown, and the server's refusal is explained here instead of "Forbidden resource". + */ +fun actionRefusalMessage(errors: List?, operationName: String?): String? { + val list = errors.orEmpty() + return when { + list.any { it.code() == "UNAUTHENTICATED" } -> "the server didn't accept the API key" + list.any { it.code() == "FORBIDDEN" } -> { + val needs = operationName?.let { KeyAction.forOperation(it) }?.permission + "your API key isn't allowed to do this" + (needs?.let { " (it needs $it)" } ?: "") + } + else -> null + } +} /** * Throws [ActionFailedException] for a failed action response, using the same @@ -161,32 +222,145 @@ class ActionFailedException(message: String, cause: Throwable? = null) : Excepti * `execute()` never throws for transport or GraphQL errors, so a caller that * does not look at the response sees every failure as success (ADR-0037). */ -fun checkActionResponse(exception: ApolloException?, hasErrors: Boolean, errorMessage: String?) { +fun checkActionResponse( + exception: ApolloException?, + hasErrors: Boolean, + errorMessage: String?, + errors: List? = null, + operationName: String? = null, +) { when (val c = classifyResponse(exception, hasErrors, errorMessage, dataIsNull = false)) { is RespClass.Cert -> throw ActionFailedException(exception!!.failureMessage("Network error"), exception) - is RespClass.Failed -> throw ActionFailedException( - when (exception) { - // Plain wording for the snackbar; the technical cause stays on the exception. - is ApolloHttpException -> "the server answered HTTP ${exception.statusCode}" - is ApolloNetworkException -> "can't reach the server" - else -> c.message - }, - exception, - ) + is RespClass.Failed -> { + val refusal = if (exception == null) actionRefusalMessage(errors, operationName) else null + throw ActionFailedException( + refusal ?: when (exception) { + // Plain wording for the snackbar; the technical cause stays on the exception. + is ApolloHttpException -> exception.redirectMessage()?.replaceFirstChar { it.lowercase() } + ?: "the server answered HTTP ${exception.statusCode}" + is ApolloNetworkException -> "can't reach the server" + else -> c.message + }, + exception, + detail = if (refusal != null) c.message else null, + ) + } RespClass.Empty, RespClass.Ok -> Unit } } /** Returns this response, or throws [ActionFailedException] if it carries a transport or GraphQL error. */ fun ApolloResponse.orThrow(): ApolloResponse { - checkActionResponse(exception, hasErrors(), errors?.joinToString { it.message }) + checkActionResponse(exception, hasErrors(), errors?.joinToString { it.message }, errors, operation.name()) return this } +/** What the tested key may do, in the words of the Add server sheet. [text] is null when it is not known. */ +sealed interface TestControl { + val text: String? + + data object Unknown : TestControl { override val text: String? = null } + + data object ViewOnly : TestControl { override val text = "View only key: NOVA will hide controls" } + + data object Full : TestControl { override val text = "Full control" } + + /** Some controls: [areas] are the ones the key may use, e.g. "Docker", "VMs". */ + data class Some(val areas: List) : TestControl { + override val text = "Can control: ${areas.joinToString(", ")}" + } + + companion object { + /** + * The summary of [caps]. Unknown as soon as one control's access is unknown: a half-known + * key is not described, because a wrong "view only" would be worse than saying nothing. + */ + fun of(caps: ServerCapabilities): TestControl { + val all = KeyAction.entries.associateWith { caps.access(it) } + return when { + all.values.any { it == Access.Unknown } -> Unknown + all.values.all { it == Access.Denied } -> ViewOnly + all.values.all { it == Access.Allowed } -> Full + else -> { + fun ok(a: KeyAction) = all[a] == Access.Allowed + Some( + listOfNotNull( + "Array".takeIf { ok(KeyAction.ControlArray) }, + "Docker".takeIf { ok(KeyAction.ControlDocker) }, + "VMs".takeIf { ok(KeyAction.ControlVms) }, + when { + ok(KeyAction.UpdateNotifications) && ok(KeyAction.DeleteNotifications) -> "Notifications" + ok(KeyAction.UpdateNotifications) -> "Archive notifications" + ok(KeyAction.DeleteNotifications) -> "Delete notifications" + else -> null + }, + ), + ) + } + } + } + } +} + /** Structured result of a connection test (consumed by the Add/Edit sheet). */ sealed interface TestOutcome { - data object Ok : TestOutcome + /** + * The server answered and accepted the key (or could not say it did not). Carries what the + * capability probe learned, so the Add server sheet can say what the key can do (#315). + */ + data class Ok( + val unraidVersion: String? = null, + val apiVersionText: String? = null, + val apiTooOld: Boolean = false, + val control: TestControl = TestControl.Unknown, + ) : TestOutcome { + /** "Connected · Unraid 7.4.0 · API 4.37.11"; the parts that are not known are left out. */ + val title: String + get() = listOfNotNull( + "Connected", + unraidVersion?.takeIf { it.isNotBlank() }?.let { "Unraid $it" }, + apiVersionText?.takeIf { it.isNotBlank() }?.let { "API ${ApiVersion.parse(it) ?: it}" }, + ).joinToString(" · ") + + /** The second line: the API warning if the server is too old, else what the key can do, else a plain "ready". */ + val detail: String + get() = when { + apiTooOld -> + "Connected, but this server's Unraid API is too old. NOVA needs 4.30.0 or newer (Unraid 7.2.5 or newer)." + else -> control.text ?: "Server responded · ready to save" + } + } data class Failed(val message: String) : TestOutcome data class CertUntrusted(val sha256: String) : TestOutcome data class CertChanged(val pinned: String, val presented: String) : TestOutcome } + +/** + * The connection-test result for a capability probe (ADR-0047). A rejected key fails the test with + * the server's own wording; a transport failure keeps its certificate handling (an untrusted or + * changed certificate opens the trust dialog, anything else is the exception's message); a server + * that answered with an error NOVA does not classify shows that error's text. + */ +internal fun testOutcomeOf(probe: ProbeOutcome): TestOutcome = when (probe.detection) { + Detection.KeyRejected -> TestOutcome.Failed("The server didn't accept this API key") + Detection.Failed -> { + val cause = probe.cause + when (val issue = cause?.certIssue()) { + is CertIssue.Untrusted -> TestOutcome.CertUntrusted(issue.sha256) + is CertIssue.Changed -> TestOutcome.CertChanged(issue.pinned, issue.presented) + null -> TestOutcome.Failed( + cause?.failureMessage("Network error") ?: probe.failureText ?: "No response from server", + ) + } + } + // Idle and Detecting are never returned by a probe; treat them as an answer without information. + Detection.Done, Detection.Idle, Detection.Detecting -> { + val caps = probe.toCapabilities(target = null) + TestOutcome.Ok( + unraidVersion = probe.unraidVersion, + apiVersionText = probe.apiVersionText, + apiTooOld = caps.apiTooOld, + control = TestControl.of(caps), + ) + } +} diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGateway.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGateway.kt index 56a93da7..c500498a 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGateway.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGateway.kt @@ -104,7 +104,9 @@ class UnraidGateway @Inject constructor( suspend fun startArray() = action({ real.startArray() }, { demo.startArray() }) suspend fun stopArray() = action({ real.stopArray() }, { demo.stopArray() }) - suspend fun startContainer(id: String) = action({ real.startContainer(id) }, { demo.startContainer(id) }) + /** [paused] picks `unpause` over `start` (#345); the demo resumes or starts the container in its model. */ + suspend fun startContainer(id: String, paused: Boolean) = + action({ real.startContainer(id, paused) }, { demo.startContainer(id, paused) }) suspend fun stopContainer(id: String) = action({ real.stopContainer(id) }, { demo.stopContainer(id) }) /** [atomic] is the real server's choice (#346); the demo restarts the container in its model either way. */ suspend fun restartContainer(id: String, atomic: Boolean) = diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt index 81df2ed5..f8be29e2 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/data/repository/UnraidRepository.kt @@ -97,7 +97,6 @@ import io.github.nofuturekid.nova.graphql.GetVmsQuery import io.github.nofuturekid.nova.graphql.PauseContainerMutation import io.github.nofuturekid.nova.graphql.PauseParityCheckMutation import io.github.nofuturekid.nova.graphql.PauseVmMutation -import io.github.nofuturekid.nova.graphql.PingQuery import io.github.nofuturekid.nova.graphql.RebootVmMutation import io.github.nofuturekid.nova.graphql.ResetVmMutation import io.github.nofuturekid.nova.graphql.RestartContainerMutation @@ -109,6 +108,7 @@ import io.github.nofuturekid.nova.graphql.StartParityCheckMutation import io.github.nofuturekid.nova.graphql.StartVmMutation import io.github.nofuturekid.nova.graphql.StopArrayMutation import io.github.nofuturekid.nova.graphql.StopContainerMutation +import io.github.nofuturekid.nova.graphql.UnpauseContainerMutation import io.github.nofuturekid.nova.graphql.UpdateAllContainersMutation import io.github.nofuturekid.nova.graphql.UpdateContainerMutation import io.github.nofuturekid.nova.graphql.StopVmMutation @@ -287,6 +287,16 @@ class UnraidRepository @Inject constructor( } } + /** + * Starts a container, or resumes it when it is [paused]. Docker refuses `start` for a paused + * container ("cannot start a paused container, try unpause instead"), so a paused one gets + * `unpause` and never `start` (#345). + */ + internal suspend fun startContainer(client: ApolloClient, id: String, paused: Boolean) { + if (paused) client.runAction(UnpauseContainerMutation(id)) + else client.runAction(StartContainerMutation(id)) + } + /** The logs query behind [containerLogs]; `null` = the request failed. */ internal suspend fun fetchContainerLogs(client: ApolloClient, id: String, tail: Int): List? { val resp = try { @@ -1158,7 +1168,10 @@ class UnraidRepository @Inject constructor( suspend fun startArray() { activeClient()?.runAction(StartArrayMutation()) } suspend fun stopArray() { activeClient()?.runAction(StopArrayMutation()) } - suspend fun startContainer(id: String) { activeClient()?.runAction(StartContainerMutation(id)) } + /** [paused]: resume the container with `unpause`; `start` is only for a stopped one (#345). */ + suspend fun startContainer(id: String, paused: Boolean) { + activeClient()?.let { startContainer(it, id, paused) } + } suspend fun stopContainer(id: String) { activeClient()?.runAction(StopContainerMutation(id)) } /** [atomic]: use the server's own `docker.restart` (API 4.36.0+), else stop + start. */ suspend fun restartContainer(id: String, atomic: Boolean) { @@ -1257,6 +1270,10 @@ class UnraidRepository @Inject constructor( * the already-confirmed [pinnedSha256] (null on the first probe): the first * probe surfaces [TestOutcome.CertUntrusted] so the sheet can show the * fingerprint dialog; after the user confirms, a re-probe with the pin matches. + * + * The probe is the capability detection (ADR-0047: version and `me`), not `Ping`: the server + * answers a bare `__typename` for any key, so Ping passed with a wrong key (#315). Here a + * rejected key fails the test, and an accepted one reports what it can do. */ suspend fun testConnection( baseUrl: String, @@ -1269,27 +1286,9 @@ class UnraidRepository @Inject constructor( } else { TlsTrust.Default } - val resp = apolloFactory.build(baseUrl, apiKey, trust).query(PingQuery()).execute() - when (val c = classifyResponse( - exception = resp.exception, - hasErrors = resp.hasErrors(), - errorMessage = resp.errors?.firstOrNull()?.message, - dataIsNull = resp.data == null, - )) { - is RespClass.Cert -> when (val i = c.issue) { - is CertIssue.Untrusted -> TestOutcome.CertUntrusted(i.sha256) - is CertIssue.Changed -> TestOutcome.CertChanged(i.pinned, i.presented) - } - is RespClass.Failed -> TestOutcome.Failed(c.message) - RespClass.Empty -> TestOutcome.Failed("No response from server") - RespClass.Ok -> TestOutcome.Ok - } - } catch (e: ApolloException) { - when (val i = e.certIssue()) { - is CertIssue.Untrusted -> TestOutcome.CertUntrusted(i.sha256) - is CertIssue.Changed -> TestOutcome.CertChanged(i.pinned, i.presented) - null -> TestOutcome.Failed(e.failureMessage("Network error")) - } + testOutcomeOf(probeCapabilities(apolloFactory.build(baseUrl, apiKey, trust))) + } catch (e: CancellationException) { + throw e } catch (e: Exception) { TestOutcome.Failed(e.message ?: "Unknown error") } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/components/ViewOnlyNote.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/components/ViewOnlyNote.kt new file mode 100644 index 00000000..b84b8156 --- /dev/null +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/components/ViewOnlyNote.kt @@ -0,0 +1,102 @@ +package io.github.nofuturekid.nova.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import io.github.nofuturekid.nova.data.model.Access +import io.github.nofuturekid.nova.data.model.KeyAction +import io.github.nofuturekid.nova.ui.theme.UnraidAlpha +import io.github.nofuturekid.nova.ui.theme.UnraidTheme + +/** The README section that says which permission each feature needs (#316). */ +const val PERMISSIONS_HELP_URL = "https://github.com/hellwand/nova#api-key-permissions" + +/** + * The two lines of a "View only" note (#315): what the key cannot do, and the permission it would + * need. Pure, so a test can pin every wording; the composable below only draws it. + */ +data class ViewOnly(val title: String, val needs: String) { + companion object { + val Containers = ViewOnly( + "View only. This API key can't start, stop or update containers.", + "Needs ${KeyAction.ControlDocker.permission}", + ) + val Vms = ViewOnly( + "View only. This API key can't start or stop virtual machines.", + "Needs ${KeyAction.ControlVms.permission}", + ) + val Array = ViewOnly( + "View only. This API key can't start or stop the array or run parity checks.", + "Needs ${KeyAction.ControlArray.permission}", + ) + + /** + * The note for the notifications sheet, or null when the key may do both. Archiving needs + * `NOTIFICATIONS:UPDATE_ANY`, deleting `NOTIFICATIONS:DELETE_ANY`; only a [Access.Denied] + * counts, so unknown access shows no note and keeps the buttons. + */ + fun notifications(update: Access, delete: Access): ViewOnly? { + val noUpdate = update == Access.Denied + val noDelete = delete == Access.Denied + val upd = KeyAction.UpdateNotifications.permission + val del = KeyAction.DeleteNotifications.permission + return when { + noUpdate && noDelete -> ViewOnly( + "View only. This API key can't archive or delete notifications.", + "Needs $upd and $del", + ) + noDelete -> ViewOnly("This API key can't delete notifications.", "Needs $del") + noUpdate -> ViewOnly("This API key can't archive notifications.", "Needs $upd") + else -> null + } + } + } +} + +/** + * One note per surface where a key's missing permission hides the controls: it sits where they + * were and says why. Both lines are one merged node, so a screen reader reads them together; + * the "Which permissions?" link sits outside that node, so the note itself is not a button. + */ +@Composable +fun ViewOnlyNote(note: ViewOnly, modifier: Modifier = Modifier) { + val t = UnraidTheme.colors + val uriHandler = LocalUriHandler.current + Column(modifier = modifier.fillMaxWidth()) { + Row( + modifier = Modifier + .fillMaxWidth() + .background(t.muted.copy(alpha = UnraidAlpha.softFill), RoundedCornerShape(12.dp)) + .border(1.dp, t.border, RoundedCornerShape(12.dp)) + .padding(horizontal = 14.dp, vertical = 12.dp) + .semantics(mergeDescendants = true) {}, + verticalAlignment = Alignment.Top, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + UC.Lock(18.dp, t.muted) + Column(modifier = Modifier.weight(1f)) { + Text(note.title, color = t.text, style = MaterialTheme.typography.bodyMedium) + Text(note.needs, color = t.muted, style = MaterialTheme.typography.labelSmall) + } + } + UnraidButton( + onClick = { runCatching { uriHandler.openUri(PERMISSIONS_HELP_URL) } }, + label = "Which permissions?", + variant = BtnVariant.Text, + tone = Tone.Accent, + ) + } +} diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/SnapshotStates.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/SnapshotStates.kt index 45349448..b13de890 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/SnapshotStates.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/SnapshotStates.kt @@ -60,7 +60,8 @@ data class ErrorTexts(val title: String, val body: String) /** * The texts for [reason]. Pure, so a test can pin every wording. [message] is the * server's own text and the body only for [ErrorReason.Unreachable] and - * [ErrorReason.ServerError]; the other reasons explain what to do instead. + * [ErrorReason.ServerError] (for [ErrorReason.Redirected] it is the app's own sentence naming the + * target); the other reasons explain what to do instead. * [subject] is null where a screen has none (generic wording). */ fun errorTexts(reason: ErrorReason, subject: ErrorSubject?, message: String): ErrorTexts = when (reason) { @@ -90,6 +91,8 @@ fun errorTexts(reason: ErrorReason, subject: ErrorSubject?, message: String): Er // Only Docker and VMs can be switched off; anything else is the server's own error. else -> ErrorTexts("The server couldn't load ${subject?.noun ?: "this"}", message) } + // [message] names the target ("The server redirects to https://...") and is already the advice. + ErrorReason.Redirected -> ErrorTexts("The address needs to change", message) ErrorReason.ServerError -> ErrorTexts("The server couldn't load ${subject?.noun ?: "this"}", message) } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/array/ArrayTab.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/array/ArrayTab.kt index dd422c2c..c6fc0e4d 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/array/ArrayTab.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/array/ArrayTab.kt @@ -25,6 +25,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import io.github.nofuturekid.nova.data.local.LayoutMode +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.ArrayInfo import io.github.nofuturekid.nova.data.model.ArrayState import io.github.nofuturekid.nova.data.model.Disk @@ -40,6 +41,8 @@ import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidButton import io.github.nofuturekid.nova.ui.components.UnraidCard import io.github.nofuturekid.nova.ui.components.UnraidProgress +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.components.onTone import io.github.nofuturekid.nova.ui.screens.ErrorState import io.github.nofuturekid.nova.ui.screens.ErrorSubject @@ -64,6 +67,8 @@ fun ArrayTab( onCancelParity: () -> Unit, globalDiskWarnC: Int? = null, globalDiskCritC: Int? = null, + /** May the key start and stop the array and run parity checks? Only [Access.Denied] hides the buttons (#315). */ + control: Access = Access.Unknown, ) { when (state) { DomainState.Loading -> LoadingState() @@ -75,6 +80,7 @@ fun ArrayTab( state.value, view, onStartArray, onStopArray, onStartParity, onPauseParity, onResumeParity, onCancelParity, globalDiskWarnC, globalDiskCritC, + canControl = control != Access.Denied, ) } } @@ -116,6 +122,7 @@ private fun ArrayContent( onCancelParity: () -> Unit, globalDiskWarnC: Int? = null, globalDiskCritC: Int? = null, + canControl: Boolean = true, ) { val t = UnraidTheme.colors val arrayOn = arr.state != ArrayState.Stopped && arr.state != ArrayState.Offline @@ -135,6 +142,8 @@ private fun ArrayContent( verticalArrangement = Arrangement.spacedBy(d.gap), ) { if (!hasArray) item { NoArrayCard() } + // Without an array there is nothing to control, so the note only belongs to a real array. + if (hasArray && !canControl) item { ViewOnlyNote(ViewOnly.Array) } if (hasArray) item { UnraidCard(padding = UnraidTheme.tokens.padHero) { Column { @@ -162,7 +171,7 @@ private fun ArrayContent( style = MaterialTheme.typography.bodySmall, ) } - if (arrayOn) { + if (canControl && arrayOn) { UnraidButton( onClick = onStop, label = "Stop", @@ -170,7 +179,7 @@ private fun ArrayContent( tone = Tone.Danger, leadingIcon = { UC.Stop(14.dp, t.danger) }, ) - } else { + } else if (canControl) { UnraidButton( onClick = onStart, label = "Start", @@ -212,8 +221,8 @@ private fun ArrayContent( style = MaterialTheme.typography.labelSmall, ) } - Spacer(Modifier.height(10.dp)) - Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (canControl) Spacer(Modifier.height(10.dp)) + if (canControl) Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { if (pc.paused) { UnraidButton( onClick = onResumeParity, @@ -245,7 +254,7 @@ private fun ArrayContent( ) } } - } else if (arrayOn && !parity) { + } else if (canControl && arrayOn && !parity) { Spacer(Modifier.height(12.dp)) UnraidButton( onClick = onStartParity, diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/container/ContainerDetailSheet.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/container/ContainerDetailSheet.kt index 50809f2a..be17b2e7 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/container/ContainerDetailSheet.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/container/ContainerDetailSheet.kt @@ -47,6 +47,7 @@ import androidx.compose.ui.unit.sp import androidx.compose.ui.platform.LocalContext import android.content.Intent import androidx.core.net.toUri +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.Container import io.github.nofuturekid.nova.data.model.ContainerLiveStats import io.github.nofuturekid.nova.data.model.ContainerStatus @@ -59,6 +60,8 @@ import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidButton import io.github.nofuturekid.nova.ui.components.UnraidCard import io.github.nofuturekid.nova.ui.components.UnraidIconButton +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.components.onTone import io.github.nofuturekid.nova.ui.theme.JetBrainsMono import io.github.nofuturekid.nova.ui.theme.UnraidAlpha @@ -89,6 +92,8 @@ fun ContainerDetailSheet( onRestart: (Container) -> Unit, onStop: (Container) -> Unit, onUpdate: (Container) -> Unit, + /** May the key start, stop, restart and update containers? Only [Access.Denied] hides the buttons (#315). */ + control: Access = Access.Unknown, ) { val t = UnraidTheme.colors val scope = rememberCoroutineScope() @@ -223,6 +228,9 @@ fun ContainerDetailSheet( style = MaterialTheme.typography.labelLarge, ) } + } else if (control == Access.Denied) { + // Logs and the other tabs below are reads and stay; only the actions go. + ViewOnlyNote(ViewOnly.Containers) } else { if (container.updateStatus.hasUpdate()) { UnraidButton( diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/docker/DockerTab.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/docker/DockerTab.kt index b878a8c9..659347eb 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/docker/DockerTab.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/docker/DockerTab.kt @@ -43,6 +43,7 @@ import androidx.compose.ui.unit.sp import io.github.nofuturekid.nova.data.local.LayoutMode import io.github.nofuturekid.nova.data.model.Container import io.github.nofuturekid.nova.data.model.ContainerLiveStats +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.ContainerStatus import io.github.nofuturekid.nova.data.model.hasUpdate import io.github.nofuturekid.nova.data.repository.DomainState @@ -53,6 +54,8 @@ import io.github.nofuturekid.nova.ui.components.Tone import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidCard import io.github.nofuturekid.nova.ui.components.UnraidIconButton +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.screens.ErrorState import io.github.nofuturekid.nova.ui.screens.ErrorSubject import io.github.nofuturekid.nova.ui.screens.LoadingState @@ -75,6 +78,8 @@ fun DockerTab( onRestart: (Container) -> Unit, onStop: (Container) -> Unit, onUpdateAll: () -> Unit, + /** May the key start, stop, restart and update containers? Only [Access.Denied] hides the controls (#315). */ + control: Access = Access.Unknown, ) { when (state) { DomainState.Loading -> LoadingState() @@ -94,6 +99,7 @@ fun DockerTab( onRestart = onRestart, onStop = onStop, onUpdateAll = onUpdateAll, + control = control, ) } } @@ -135,7 +141,9 @@ private fun DockerContent( onRestart: (Container) -> Unit, onStop: (Container) -> Unit, onUpdateAll: () -> Unit, + control: Access = Access.Unknown, ) { + val canControl = control != Access.Denied val filtered = filterContainers(containers, query) val rows = MainViewModel.joinContainerStats(filtered, stats) val noMatch = filtered.isEmpty() && containers.isNotEmpty() @@ -149,11 +157,12 @@ private fun DockerContent( ), verticalArrangement = Arrangement.spacedBy(d.gap), ) { - if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll) } + if (!canControl) item { ViewOnlyNote(ViewOnly.Containers) } + if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll, canControl) } item { SearchBox(query, onQueryChange) } if (noMatch) item { NoMatches(query, containers.size) } items(rows, key = { it.first.id }) { (c, live) -> - ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop) + ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop, canControl) } } LayoutMode.Grid -> LazyVerticalGrid( @@ -165,8 +174,9 @@ private fun DockerContent( horizontalArrangement = Arrangement.spacedBy(d.gap), verticalArrangement = Arrangement.spacedBy(d.gap), ) { + if (!canControl) item(span = { GridItemSpan(maxLineSpan) }) { ViewOnlyNote(ViewOnly.Containers) } if (updateCount > 0) item(span = { GridItemSpan(maxLineSpan) }) { - UpdateAllBanner(updateCount, onUpdateAll) + UpdateAllBanner(updateCount, onUpdateAll, canControl) } item(span = { GridItemSpan(maxLineSpan) }) { SearchBox(query, onQueryChange) } if (noMatch) item(span = { GridItemSpan(maxLineSpan) }) { NoMatches(query, containers.size) } @@ -185,25 +195,26 @@ private fun DockerContent( ), verticalArrangement = Arrangement.spacedBy(d.gap), ) { - if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll) } + if (!canControl) item { ViewOnlyNote(ViewOnly.Containers) } + if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll, canControl) } item { SearchBox(query, onQueryChange) } if (noMatch) item { NoMatches(query, containers.size) } if (running.isNotEmpty()) { item { SectionLabel("Running · ${running.size}") } items(running, key = { "r-${it.first.id}" }) { (c, live) -> - ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop) + ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop, canControl) } } if (paused.isNotEmpty()) { item { SectionLabel("Paused · ${paused.size}") } items(paused, key = { "p-${it.first.id}" }) { (c, live) -> - ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop) + ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop, canControl) } } if (exited.isNotEmpty()) { item { SectionLabel("Stopped · ${exited.size}") } items(exited, key = { "x-${it.first.id}" }) { (c, live) -> - ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop) + ContainerRow(c, serverBaseUrl, live, onOpenContainer, onStart, onRestart, onStop, canControl) } } } @@ -218,7 +229,8 @@ private fun DockerContent( ), verticalArrangement = Arrangement.spacedBy(d.gap), ) { - if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll) } + if (!canControl) item { ViewOnlyNote(ViewOnly.Containers) } + if (updateCount > 0) item { UpdateAllBanner(updateCount, onUpdateAll, canControl) } item { SearchBox(query, onQueryChange) } if (noMatch) item { NoMatches(query, containers.size) } groups.forEach { group -> @@ -226,7 +238,7 @@ private fun DockerContent( SectionLabel("${group.title} · ${group.containers.size}") } items(group.containers, key = { "c-${it.id}" }) { c -> - ContainerRow(c, serverBaseUrl, liveById[c.id], onOpenContainer, onStart, onRestart, onStop) + ContainerRow(c, serverBaseUrl, liveById[c.id], onOpenContainer, onStart, onRestart, onStop, canControl) } } } @@ -235,7 +247,7 @@ private fun DockerContent( } @Composable -private fun UpdateAllBanner(count: Int, onTap: () -> Unit) { +private fun UpdateAllBanner(count: Int, onTap: () -> Unit, canUpdate: Boolean = true) { val t = UnraidTheme.colors Row( modifier = Modifier @@ -243,7 +255,7 @@ private fun UpdateAllBanner(count: Int, onTap: () -> Unit) { .clip(RoundedCornerShape(12.dp)) .background(t.info.copy(alpha = UnraidAlpha.softFill)) .border(1.dp, t.info.copy(alpha = UnraidAlpha.softBorder), RoundedCornerShape(12.dp)) - .clickable(onClick = onTap) + .then(if (canUpdate) Modifier.clickable(onClick = onTap) else Modifier) .padding(horizontal = 14.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), @@ -255,13 +267,15 @@ private fun UpdateAllBanner(count: Int, onTap: () -> Unit) { color = t.info, style = MaterialTheme.typography.labelLarge, ) - Text( - text = "Tap to update all", - color = t.info.copy(alpha = 0.75f), - style = MaterialTheme.typography.labelSmall, - ) + if (canUpdate) { + Text( + text = "Tap to update all", + color = t.info.copy(alpha = 0.75f), + style = MaterialTheme.typography.labelSmall, + ) + } } - UC.ChevR(16.dp, t.info) + if (canUpdate) UC.ChevR(16.dp, t.info) } } @@ -339,6 +353,7 @@ private fun ContainerRow( onStart: (Container) -> Unit, onRestart: (Container) -> Unit, onStop: (Container) -> Unit, + canControl: Boolean = true, ) { val t = UnraidTheme.colors val tone = when (c.status) { @@ -389,7 +404,7 @@ private fun ContainerRow( } } } - Row { + if (canControl) Row { when (c.status) { ContainerStatus.Running -> { UnraidIconButton(icon = { UC.Restart(16.dp, t.text) }, onClick = { onRestart(c) }, size = 34.dp, contentDescription = "Restart ${c.name}") diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt index 2cf2c303..77baed78 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainScreen.kt @@ -54,6 +54,7 @@ import io.github.nofuturekid.nova.BuildConfig import io.github.nofuturekid.nova.data.model.ArrayState import io.github.nofuturekid.nova.data.model.AttentionTarget import io.github.nofuturekid.nova.data.model.Container +import io.github.nofuturekid.nova.data.model.KeyAction import io.github.nofuturekid.nova.data.model.ConnectionMode import io.github.nofuturekid.nova.data.model.NotifType import io.github.nofuturekid.nova.data.model.Server @@ -112,6 +113,12 @@ fun MainScreen( val vmsState by vm.vmsState.collectAsStateWithLifecycle() val notificationsState by vm.notificationsState.collectAsStateWithLifecycle() val displayThresholds by vm.displayThresholds.collectAsStateWithLifecycle() + // What the API key may do. Every surface below gets one Access value and hides its controls + // only for Denied; unknown access keeps them, as before (ADR-0047, #315). + val capabilities by vm.capabilities.collectAsStateWithLifecycle() + val dockerAccess = capabilities.access(KeyAction.ControlDocker) + val vmsAccess = capabilities.access(KeyAction.ControlVms) + val arrayAccess = capabilities.access(KeyAction.ControlArray) val scope = rememberCoroutineScope() // Pause polling when app is backgrounded (ADR-0017). Bound to the @@ -298,6 +305,7 @@ fun MainScreen( }, globalDiskWarnC = displayThresholds?.diskWarnC, globalDiskCritC = displayThresholds?.diskCritC, + control = arrayAccess, ) MainTab.Docker -> DockerTab( state = dockerState, @@ -307,7 +315,7 @@ fun MainScreen( onAddServer = onAddServer, stats = dockerLiveStats, onOpenContainer = { setOpenContainer(it) }, - onStart = { c -> vm.startContainer(c.id) }, + onStart = { c -> vm.startContainer(c) }, onRestart = { c -> confirm = ConfirmRequest( title = "Restart ${c.name}?", @@ -342,6 +350,7 @@ fun MainScreen( onConfirm = { vm.updateAllContainers(); confirm = null }, ) }, + control = dockerAccess, ) MainTab.Vms -> VmsTab( state = vmsState, @@ -351,6 +360,7 @@ fun MainScreen( onResume = { v -> vm.resumeVm(v.id) }, onPause = { v -> vm.pauseVm(v.id) }, onOpenVm = { openVm = it }, + control = vmsAccess, ) } } @@ -382,7 +392,7 @@ fun MainScreen( onFetchLogs = { id -> vm.containerLogs(id) }, onRefresh = { vm.refresh() }, onDismiss = { setOpenContainer(null) }, - onStart = { vm.startContainer(it.id); setOpenContainer(null) }, + onStart = { vm.startContainer(it); setOpenContainer(null) }, onRestart = { c -> confirm = ConfirmRequest( title = "Restart ${c.name}?", @@ -413,6 +423,7 @@ fun MainScreen( onConfirm = { vm.updateContainer(c.id); confirm = null }, ) }, + control = dockerAccess, ) } @@ -463,6 +474,7 @@ fun MainScreen( onConfirm = { vm.resetVm(v.id); confirm = null; openVm = null }, ) }, + control = vmsAccess, ) } @@ -491,6 +503,8 @@ fun MainScreen( onConfirm = { vm.deleteNotification(n.id, n.type ?: NotifType.Unread); confirm = null }, ) }, + update = capabilities.access(KeyAction.UpdateNotifications), + delete = capabilities.access(KeyAction.DeleteNotifications), ) } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainViewModel.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainViewModel.kt index 50912023..e75b2f03 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainViewModel.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/main/MainViewModel.kt @@ -40,6 +40,7 @@ import io.github.nofuturekid.nova.data.model.DisplayThresholds import io.github.nofuturekid.nova.data.model.NotifType import io.github.nofuturekid.nova.data.model.Container import io.github.nofuturekid.nova.data.model.ContainerLiveStats +import io.github.nofuturekid.nova.data.model.ContainerStatus import io.github.nofuturekid.nova.data.model.LiveMetrics import io.github.nofuturekid.nova.data.model.NetworkThroughput import io.github.nofuturekid.nova.data.model.Notifications @@ -399,7 +400,10 @@ class MainViewModel @Inject constructor( fun startArray() = launchAction { unraid.startArray() } fun stopArray() = launchAction { unraid.stopArray() } - fun startContainer(id: String) = launchAction { unraid.startContainer(id) } + /** Start for a stopped container, resume (`unpause`) for a paused one (#345). */ + fun startContainer(c: Container) = launchAction { + unraid.startContainer(c.id, paused = c.status == ContainerStatus.Paused) + } fun stopContainer(id: String) = launchAction { unraid.stopContainer(id) } fun restartContainer(id: String) = launchAction { // Unknown API version stays on stop + start: only a known 4.36.0+ server gets `docker.restart`. diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/notifications/NotificationsSheet.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/notifications/NotificationsSheet.kt index 1b5303e0..af31b25a 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/notifications/NotificationsSheet.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/notifications/NotificationsSheet.kt @@ -33,6 +33,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.NotifImportance import io.github.nofuturekid.nova.data.model.NotifType import io.github.nofuturekid.nova.data.model.Notifications @@ -43,6 +44,8 @@ import io.github.nofuturekid.nova.ui.components.Tone import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidButton import io.github.nofuturekid.nova.ui.components.UnraidIconButton +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.theme.UnraidAlpha import io.github.nofuturekid.nova.ui.theme.UnraidTheme import io.github.nofuturekid.nova.ui.util.notificationSummary @@ -73,8 +76,14 @@ fun NotificationsSheet( onArchiveAll: () -> Unit, onDeleteAllArchivedRequest: () -> Unit, onDeleteRequest: (UnraidNotification) -> Unit, + /** May the key archive and unarchive? Only [Access.Denied] hides those buttons (#315). */ + update: Access = Access.Unknown, + /** May the key delete? Only [Access.Denied] hides the delete buttons (#315). */ + delete: Access = Access.Unknown, ) { val t = UnraidTheme.colors + val canUpdate = update != Access.Denied + val canDelete = delete != Access.Denied val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val data = (state as? DomainState.Content)?.value var tabIndex by remember { mutableIntStateOf(0) } @@ -144,6 +153,10 @@ fun NotificationsSheet( ) } Spacer(Modifier.height(12.dp)) + ViewOnly.notifications(update, delete)?.let { + ViewOnlyNote(it) + Spacer(Modifier.height(12.dp)) + } when { state is DomainState.Loading -> CenterMsg("Loading notifications…", loading = true) @@ -152,7 +165,7 @@ fun NotificationsSheet( state is DomainState.NoServer -> CenterMsg("No server selected.") else -> { val list = if (tabIndex == 0) unread else archived - if (tabIndex == 0 && unread.isNotEmpty()) { + if (canUpdate && tabIndex == 0 && unread.isNotEmpty()) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, @@ -167,7 +180,7 @@ fun NotificationsSheet( } Spacer(Modifier.height(6.dp)) } - if (tabIndex == 1 && archived.isNotEmpty()) { + if (canDelete && tabIndex == 1 && archived.isNotEmpty()) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, @@ -199,6 +212,8 @@ fun NotificationsSheet( onArchive = { onArchive(n.id) }, onUnread = { onUnread(n.id) }, onDelete = { onDeleteRequest(n) }, + canUpdate = canUpdate, + canDelete = canDelete, ) } } @@ -235,6 +250,8 @@ private fun NotificationRow( onArchive: () -> Unit, onUnread: () -> Unit, onDelete: () -> Unit, + canUpdate: Boolean = true, + canDelete: Boolean = true, ) { val t = UnraidTheme.colors val accent = when (n.importance) { @@ -279,25 +296,25 @@ private fun NotificationRow( } } } - Spacer(Modifier.height(8.dp)) - Row( + if (canUpdate || canDelete) Spacer(Modifier.height(8.dp)) + if (canUpdate || canDelete) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, ) { - if (archivedTab) { + if (canUpdate && archivedTab) { UnraidIconButton( icon = { UC.Restart(20.dp, t.text) }, onClick = onUnread, contentDescription = "Unarchive (restore to unread)", ) - } else { + } else if (canUpdate) { UnraidIconButton( icon = { UC.Check(20.dp, t.text) }, onClick = onArchive, contentDescription = "Archive (mark read)", ) } - UnraidIconButton( + if (canDelete) UnraidIconButton( icon = { UC.Trash(20.dp, t.danger) }, onClick = onDelete, contentDescription = "Delete notification", diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFigures.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFigures.kt index 9e032644..316e350f 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFigures.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFigures.kt @@ -1,6 +1,10 @@ package io.github.nofuturekid.nova.ui.screens.overview import io.github.nofuturekid.nova.data.model.ArrayInfo +import io.github.nofuturekid.nova.data.model.Container +import io.github.nofuturekid.nova.data.model.ContainerStatus +import io.github.nofuturekid.nova.data.model.Vm +import io.github.nofuturekid.nova.data.model.VmState /** What a card shows for a value that is not known (offline, not loaded yet). Same dash as the Network and Temperature cards. */ internal const val PLACEHOLDER = "—" @@ -43,6 +47,30 @@ internal fun arrayFigures(array: ArrayInfo?): ArrayFigures { ) } +/** + * Headline and sub line of the Containers or Virtual machines card. Unknown ([containers] or + * [vms] null: not loaded yet, turned off, not allowed, offline) shows the placeholder, never + * "0 running · all healthy" (#356); a real empty list stays 0. + */ +internal data class CountFigures(val value: String, val sub: String) + +internal fun containerFigures(containers: List?): CountFigures { + if (containers == null) return CountFigures(PLACEHOLDER, PLACEHOLDER) + val stopped = containers.count { it.status == ContainerStatus.Exited } + val paused = containers.count { it.status == ContainerStatus.Paused } + return CountFigures( + value = "${containers.count { it.status == ContainerStatus.Running }}", + sub = if (stopped == 0 && paused == 0) "all healthy" else listOfNotNull( + if (stopped > 0) "$stopped stopped" else null, + if (paused > 0) "$paused paused" else null, + ).joinToString(" · "), + ) +} + +internal fun vmFigures(vms: List?): CountFigures = + if (vms == null) CountFigures(PLACEHOLDER, PLACEHOLDER) + else CountFigures("${vms.count { it.state == VmState.Running }}", "${vms.size} configured") + /** CPU headline: the load, or the placeholder while it is unknown. */ internal fun cpuValue(cpuPercent: Double?): String = cpuPercent?.let { "%.1f%%".format(it) } ?: PLACEHOLDER diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt index 8e29be15..db8347aa 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewTab.kt @@ -32,7 +32,6 @@ import io.github.nofuturekid.nova.data.model.AttentionSnapshot import io.github.nofuturekid.nova.data.model.AttentionTarget import io.github.nofuturekid.nova.data.model.attentionItems import io.github.nofuturekid.nova.data.model.Container -import io.github.nofuturekid.nova.data.model.ContainerStatus import io.github.nofuturekid.nova.data.model.DisplayThresholds import io.github.nofuturekid.nova.data.model.LiveMetrics import io.github.nofuturekid.nova.data.model.NetworkThroughput @@ -42,7 +41,6 @@ import io.github.nofuturekid.nova.data.model.ServerInfo import io.github.nofuturekid.nova.data.model.Temperature import io.github.nofuturekid.nova.data.model.TemperatureUnit import io.github.nofuturekid.nova.data.model.Vm -import io.github.nofuturekid.nova.data.model.VmState import io.github.nofuturekid.nova.data.repository.DomainState import io.github.nofuturekid.nova.ui.components.Pill import io.github.nofuturekid.nova.ui.components.Sparkline @@ -102,20 +100,16 @@ fun OverviewTab( // Nothing yet → either Loading or surface the first Error. if (info == null && metrics == null && array == null && containers == null && vms == null) { - val err = listOfNotNull( - infoState as? DomainState.Error, - metricsState as? DomainState.Error, - arrayState as? DomainState.Error, - dockerState as? DomainState.Error, - vmsState as? DomainState.Error, - ).firstOrNull() - if (err != null) ErrorState(err.message, detail = err.detail) else LoadingState() + val err = overviewFailure(infoState, metricsState, arrayState, dockerState, vmsState) + // The reason picks the same title and next step as the tabs do (#247, #217). + if (err != null) ErrorState(err.message, detail = err.detail, reason = err.reason) else LoadingState() return } - // Same rule as the top bar's Offline pill: an Error on any of these streams - // means the server is not reachable, so there is nothing trustworthy to flag. - val offline = listOf(infoState, arrayState, dockerState, vmsState).any { it is DomainState.Error } + // Same rule as the top bar's Offline pill: only an Error that says the server cannot be used + // means there is nothing trustworthy to flag. Docker or VMs being switched off, or a key that + // may not read one domain, leaves the server reachable and the card in place (#217, #356). + val offline = isOffline(infoState, arrayState, dockerState, vmsState) val attention = remember(array, notifications, displayThresholds, offline) { if (offline) emptyList() else attentionItems(AttentionSnapshot(array, notifications, displayThresholds)) @@ -127,6 +121,20 @@ fun OverviewTab( ) } +/** + * The error the Overview shows when no domain has loaded: a connection problem (server + * unreachable, key rejected) wins over any other reason, because it is the cause of the rest; + * otherwise the first error in the order given. Null when nothing failed. + */ +internal fun overviewFailure(vararg states: DomainState<*>): DomainState.Error? { + val errors = states.filterIsInstance() + return errors.firstOrNull { it.reason.isConnectionProblem } ?: errors.firstOrNull() +} + +/** True when any state is an Error that says the server itself cannot be used ([ErrorReason.isConnectionProblem]). */ +internal fun isOffline(vararg states: DomainState<*>): Boolean = + states.any { it is DomainState.Error && it.reason.isConnectionProblem } + @Composable private fun OverviewContent( info: ServerInfo?, @@ -181,11 +189,8 @@ private fun OverviewContent( val arrayFig = arrayFigures(array) val arrState = array?.state ?: ArrayState.Offline - val running = containers?.count { it.status == ContainerStatus.Running } ?: 0 - val stopped = containers?.count { it.status == ContainerStatus.Exited } ?: 0 - val paused = containers?.count { it.status == ContainerStatus.Paused } ?: 0 - val vmRunning = vms?.count { it.state == VmState.Running } ?: 0 - val vmCount = vms?.size ?: 0 + val dockerFig = containerFigures(containers) + val vmFig = vmFigures(vms) val arrTone = when (arrState) { ArrayState.Started -> Tone.Accent @@ -381,18 +386,12 @@ private fun OverviewContent( } Spacer(Modifier.height(8.dp)) Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(6.dp)) { - Text("$running", color = t.text, style = MaterialTheme.typography.headlineMedium) + Text(dockerFig.value, color = t.text, style = MaterialTheme.typography.headlineMedium) Text("running", color = t.muted, style = MaterialTheme.typography.bodySmall) } Spacer(Modifier.height(6.dp)) Text( - text = when { - stopped == 0 && paused == 0 -> "all healthy" - else -> listOfNotNull( - if (stopped > 0) "$stopped stopped" else null, - if (paused > 0) "$paused paused" else null, - ).joinToString(" · ") - }, + text = dockerFig.sub, color = t.muted, style = MaterialTheme.typography.bodySmall, ) @@ -407,11 +406,11 @@ private fun OverviewContent( } Spacer(Modifier.height(8.dp)) Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(6.dp)) { - Text("$vmRunning", color = t.text, style = MaterialTheme.typography.headlineMedium) + Text(vmFig.value, color = t.text, style = MaterialTheme.typography.headlineMedium) Text("running", color = t.muted, style = MaterialTheme.typography.bodySmall) } Spacer(Modifier.height(6.dp)) - Text("$vmCount configured", color = t.muted, style = MaterialTheme.typography.bodySmall) + Text(vmFig.sub, color = t.muted, style = MaterialTheme.typography.bodySmall) } } } diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/server/AddEditServerSheet.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/server/AddEditServerSheet.kt index 131bf09e..2e28a054 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/server/AddEditServerSheet.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/server/AddEditServerSheet.kt @@ -26,6 +26,7 @@ import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel @@ -46,6 +47,7 @@ import io.github.nofuturekid.nova.data.repository.UnraidRepository import io.github.nofuturekid.nova.ui.components.BtnVariant import io.github.nofuturekid.nova.ui.components.ConfirmDialog import io.github.nofuturekid.nova.ui.components.ConfirmRequest +import io.github.nofuturekid.nova.ui.components.PERMISSIONS_HELP_URL import io.github.nofuturekid.nova.ui.components.Tone import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidButton @@ -70,8 +72,11 @@ data class AddEditUiState( val showKey: Boolean = false, val localTest: TestState = TestState.Idle, val localTestMsg: String? = null, + // The first line of a successful test ("Connected · Unraid 7.4.0 · API 4.37.11"); the second is the message. + val localTestTitle: String? = null, val remoteTest: TestState = TestState.Idle, val remoteTestMsg: String? = null, + val remoteTestTitle: String? = null, // Fingerprint captured at Test, pinned on save (null until confirmed). val pendingLocalCertSha256: String? = null, // When non-null, the sheet shows the cert-trust confirm dialog. @@ -150,7 +155,9 @@ class AddEditServerViewModel @Inject constructor( viewModelScope.launch { val allowSelfSigned = s.localSsl && s.trustSelfSignedLocal when (val out = unraid.testConnection(url, s.apiKey, allowSelfSigned, s.pendingLocalCertSha256)) { - TestOutcome.Ok -> _state.value = _state.value.copy(localTest = TestState.Ok, localTestMsg = null) + is TestOutcome.Ok -> _state.value = _state.value.copy( + localTest = TestState.Ok, localTestTitle = out.title, localTestMsg = out.detail, + ) is TestOutcome.Failed -> _state.value = _state.value.copy(localTest = TestState.Fail, localTestMsg = out.message) is TestOutcome.CertUntrusted -> _state.value = _state.value.copy( localTest = TestState.Idle, certDialogSha256 = out.sha256, certDialogPrevious = null, @@ -175,7 +182,9 @@ class AddEditServerViewModel @Inject constructor( // Remote always uses full CA validation (allowSelfSigned = false). A // self-signed remote cert therefore comes back as Failed, never a prompt. when (val out = unraid.testConnection(url, s.apiKey, allowSelfSigned = false)) { - TestOutcome.Ok -> _state.value = _state.value.copy(remoteTest = TestState.Ok, remoteTestMsg = null) + is TestOutcome.Ok -> _state.value = _state.value.copy( + remoteTest = TestState.Ok, remoteTestTitle = out.title, remoteTestMsg = out.detail, + ) is TestOutcome.Failed -> _state.value = _state.value.copy(remoteTest = TestState.Fail, remoteTestMsg = out.message) is TestOutcome.CertUntrusted -> _state.value = _state.value.copy(remoteTest = TestState.Fail, remoteTestMsg = "Certificate not trusted (remote requires a valid certificate)") is TestOutcome.CertChanged -> _state.value = _state.value.copy(remoteTest = TestState.Fail, remoteTestMsg = "Certificate changed") @@ -431,6 +440,14 @@ fun AddEditServerSheet( contentDescription = if (state.showKey) "Hide API key" else "Show API key", ) }, + helper = "A key with the VIEWER role is enough to see everything. Controls need more permissions.", + ) + val uriHandler = LocalUriHandler.current + UnraidButton( + onClick = { runCatching { uriHandler.openUri(PERMISSIONS_HELP_URL) } }, + label = "Which permissions?", + variant = BtnVariant.Text, + tone = Tone.Accent, ) if (state.localHost.isNotBlank()) { @@ -439,6 +456,7 @@ fun AddEditServerSheet( state = state.localTest, onTest = vm::testLocal, message = state.localTestMsg, + okTitle = state.localTestTitle, ) Spacer(Modifier.height(8.dp)) } @@ -448,6 +466,7 @@ fun AddEditServerSheet( state = state.remoteTest, onTest = vm::testRemote, message = state.remoteTestMsg, + okTitle = state.remoteTestTitle, ) } @@ -561,7 +580,14 @@ fun AddEditServerSheet( } @Composable -private fun TestConnectionPanel(title: String, state: TestState, onTest: () -> Unit, message: String?) { +private fun TestConnectionPanel( + title: String, + state: TestState, + onTest: () -> Unit, + message: String?, + /** First line after a successful test: the server's version. */ + okTitle: String? = null, +) { val t = UnraidTheme.colors val bg = when (state) { TestState.Ok -> t.accent.copy(alpha = UnraidAlpha.softFill) @@ -587,7 +613,7 @@ private fun TestConnectionPanel(title: String, state: TestState, onTest: () -> U text = when (state) { TestState.Idle -> title TestState.Testing -> "Connecting…" - TestState.Ok -> "Connected" + TestState.Ok -> okTitle ?: "Connected" TestState.Fail -> "Failed to connect" }, color = t.text, @@ -598,7 +624,7 @@ private fun TestConnectionPanel(title: String, state: TestState, onTest: () -> U text = when (state) { TestState.Idle -> "Verify URL + API key before saving" TestState.Testing -> "Talking to GraphQL endpoint…" - TestState.Ok -> "Server responded · ready to save" + TestState.Ok -> message ?: "Server responded · ready to save" TestState.Fail -> message ?: "Check URL and API key" }, color = t.muted, diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmDetailSheet.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmDetailSheet.kt index 17f85ca4..09642e47 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmDetailSheet.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmDetailSheet.kt @@ -23,6 +23,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.Vm import io.github.nofuturekid.nova.data.model.VmState import io.github.nofuturekid.nova.ui.components.BtnVariant @@ -31,6 +32,8 @@ import io.github.nofuturekid.nova.ui.components.Tone import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidButton import io.github.nofuturekid.nova.ui.components.UnraidIconButton +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.components.onTone import io.github.nofuturekid.nova.ui.theme.UnraidAlpha import io.github.nofuturekid.nova.ui.theme.UnraidTheme @@ -56,6 +59,8 @@ fun VmDetailSheet( onForceStop: (Vm) -> Unit = {}, onReboot: (Vm) -> Unit, onReset: (Vm) -> Unit, + /** May the key start, stop and otherwise control VMs? Only [Access.Denied] hides the buttons (#315). */ + control: Access = Access.Unknown, ) { val t = UnraidTheme.colors val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) @@ -102,7 +107,9 @@ fun VmDetailSheet( Spacer(Modifier.height(18.dp)) } - Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (control == Access.Denied) { + ViewOnlyNote(ViewOnly.Vms) + } else Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { when (vm.state) { VmState.Running -> { UnraidButton( @@ -155,7 +162,7 @@ fun VmDetailSheet( } } } - if (vm.state == VmState.Running) { + if (control != Access.Denied && vm.state == VmState.Running) { Spacer(Modifier.height(6.dp)) Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { UnraidButton( @@ -177,7 +184,7 @@ fun VmDetailSheet( ) } } - if (vm.state != VmState.Stopped) { + if (control != Access.Denied && vm.state != VmState.Stopped) { Spacer(Modifier.height(6.dp)) UnraidButton( onClick = { onForceStop(vm) }, diff --git a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmsTab.kt b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmsTab.kt index e87117f5..58f91427 100644 --- a/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmsTab.kt +++ b/app/src/main/kotlin/io/github/nofuturekid/nova/ui/screens/vms/VmsTab.kt @@ -29,6 +29,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import io.github.nofuturekid.nova.data.local.LayoutMode +import io.github.nofuturekid.nova.data.model.Access import io.github.nofuturekid.nova.data.model.Vm import io.github.nofuturekid.nova.data.model.VmState import io.github.nofuturekid.nova.data.repository.DomainState @@ -38,6 +39,8 @@ import io.github.nofuturekid.nova.ui.components.SectionLabel import io.github.nofuturekid.nova.ui.components.Tone import io.github.nofuturekid.nova.ui.components.UC import io.github.nofuturekid.nova.ui.components.UnraidCard +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.components.ViewOnlyNote import io.github.nofuturekid.nova.ui.components.onTone import io.github.nofuturekid.nova.ui.screens.ErrorState import io.github.nofuturekid.nova.ui.screens.ErrorSubject @@ -55,7 +58,10 @@ fun VmsTab( onResume: (Vm) -> Unit, onPause: (Vm) -> Unit, onOpenVm: (Vm) -> Unit, + /** May the key start, stop and pause VMs? Only [Access.Denied] hides the buttons (#315). */ + control: Access = Access.Unknown, ) { + val canControl = control != Access.Denied when (state) { DomainState.Loading -> LoadingState() DomainState.NoServer -> NoServerState(onAdd = onAddServer) @@ -77,8 +83,9 @@ fun VmsTab( contentPadding = pad, verticalArrangement = Arrangement.spacedBy(d.gap), ) { + if (!canControl) item { ViewOnlyNote(ViewOnly.Vms) } items(vms, key = { it.id }) { vm -> - VmCard(vm, onOpenVm, onStart, onResume, onPause) + VmCard(vm, onOpenVm, onStart, onResume, onPause, canControl) } } LayoutMode.Grid -> LazyVerticalGrid( @@ -88,6 +95,9 @@ fun VmsTab( horizontalArrangement = Arrangement.spacedBy(d.gap), verticalArrangement = Arrangement.spacedBy(d.gap), ) { + if (!canControl) item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) { + ViewOnlyNote(ViewOnly.Vms) + } gridItems(vms, key = { it.id }) { vm -> VmTile(vm, onOpenVm) } @@ -101,22 +111,23 @@ fun VmsTab( contentPadding = pad, verticalArrangement = Arrangement.spacedBy(d.gap), ) { + if (!canControl) item { ViewOnlyNote(ViewOnly.Vms) } if (running.isNotEmpty()) { item { SectionLabel("Running · ${running.size}") } items(running, key = { "r-${it.id}" }) { vm -> - VmCard(vm, onOpenVm, onStart, onResume, onPause) + VmCard(vm, onOpenVm, onStart, onResume, onPause, canControl) } } if (paused.isNotEmpty()) { item { SectionLabel("Paused · ${paused.size}") } items(paused, key = { "p-${it.id}" }) { vm -> - VmCard(vm, onOpenVm, onStart, onResume, onPause) + VmCard(vm, onOpenVm, onStart, onResume, onPause, canControl) } } if (stopped.isNotEmpty()) { item { SectionLabel("Stopped · ${stopped.size}") } items(stopped, key = { "s-${it.id}" }) { vm -> - VmCard(vm, onOpenVm, onStart, onResume, onPause) + VmCard(vm, onOpenVm, onStart, onResume, onPause, canControl) } } } @@ -205,6 +216,7 @@ private fun VmCard( onStart: (Vm) -> Unit, onResume: (Vm) -> Unit, onPause: (Vm) -> Unit, + canControl: Boolean = true, ) { val t = UnraidTheme.colors val tone = when (vm.state) { @@ -246,7 +258,7 @@ private fun VmCard( } } } - when (vm.state) { + if (canControl) when (vm.state) { VmState.Running -> UnraidIconButton( icon = { UC.Pause(16.dp, t.warn) }, onClick = { onPause(vm) }, diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/BackgroundClientRedirectTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/BackgroundClientRedirectTest.kt index 15d3771f..b9e6fbd7 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/BackgroundClientRedirectTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/BackgroundClientRedirectTest.kt @@ -19,8 +19,9 @@ import java.util.concurrent.CopyOnWriteArrayList * WHY: OkHttp follows redirects by default and strips only `Authorization` on the way, so a 3xx * answer would send the `x-api-key` header, and on 307/308 the POST body too, to whatever * `Location` says: another host, or http. In the background nobody is looking, so a verified - * https peer, or a proxy in front of it, must not be able to move the key anywhere. The - * foreground client is deliberately left as it is; a guard test pins that down. + * https peer, or a proxy in front of it, must not be able to move the key anywhere. The foreground + * clients follow no redirect either since ADR-0051 ([KeyedClientRedirectTest]); the background + * client states it itself, so these tests pin it independently of the base client. */ class BackgroundClientRedirectTest { private val servers = mutableListOf() @@ -93,15 +94,15 @@ class BackgroundClientRedirectTest { assertEquals("nothing reached the http server", emptyList(), plain.seenKeys.toList()) } - @Test fun the_foreground_client_still_follows_redirects() { - // WHY: the foreground behaviour of the app is deliberately unchanged; this guard fails if - // the redirect and cleartext settings ever leak from the background variant into build(). + @Test fun the_foreground_client_does_not_follow_redirects_either_but_keeps_cleartext() { + // WHY: ADR-0051 stopped the foreground redirects; what must stay is the background-only cleartext + // block: a user with an http-only server (SSL off) still connects in the foreground. val elsewhere = peer(200) val redirecting = peer(307, location = "${elsewhere.url}/graphql") exception(ApolloClientFactory().build(redirecting.url, "secret")) - assertEquals(listOf("secret"), redirecting.seenKeys.toList()) - assertEquals("the foreground follows the redirect, as before", listOf("secret"), elsewhere.seenKeys.toList()) + assertEquals("http is still allowed in the foreground", listOf("secret"), redirecting.seenKeys.toList()) + assertEquals("no redirect is followed", emptyList(), elsewhere.seenKeys.toList()) } } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/KeyedClientRedirectTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/KeyedClientRedirectTest.kt new file mode 100644 index 00000000..e92db7e6 --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/api/KeyedClientRedirectTest.kt @@ -0,0 +1,199 @@ +package io.github.nofuturekid.nova.data.api + +import com.apollographql.apollo.ApolloClient +import com.apollographql.apollo.exception.ApolloHttpException +import com.sun.net.httpserver.HttpServer +import io.github.nofuturekid.nova.data.repository.ErrorReason +import io.github.nofuturekid.nova.data.repository.toQueryError +import io.github.nofuturekid.nova.graphql.DockerContainerStatsSubscription +import io.github.nofuturekid.nova.graphql.GetArrayQuery +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeoutOrNull +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.IOException +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import java.security.MessageDigest +import java.util.Base64 +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicInteger +import kotlin.concurrent.thread + +/** + * WHY (ADR-0051): every client that carries the API key must keep it on the address the user + * entered. OkHttp follows redirects by default and strips only `Authorization`, so a 3xx answer + * (from a server, or a proxy or hijacked DNS in front of it) used to move the `x-api-key` header to + * whatever `Location` named: another host, or plain http. The WebSocket client is the same case in + * a worse form: after a followed handshake the key goes out in `connection_init` to the new host. + * Unraid itself answers http requests with `302` when SSL is Yes or Strict, so the redirect must + * also arrive as a reason the user can act on, not as a silent failure. + */ +class KeyedClientRedirectTest { + private val servers = mutableListOf() + private val wsPeers = mutableListOf() + + @After fun stop() { + servers.forEach { it.stop(0) } + wsPeers.forEach { it.close() } + } + + /** Records the x-api-key header of every request it gets; answers with [status] and [location]. */ + private class Peer(val server: HttpServer, val seenKeys: CopyOnWriteArrayList) { + val url get() = "http://127.0.0.1:${server.address.port}" + } + + private fun peer(status: Int, location: String? = null): Peer { + val seen = CopyOnWriteArrayList() + val http = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0) + http.createContext("/graphql") { exchange -> + seen += exchange.requestHeaders.getFirst("x-api-key") ?: "(none)" + exchange.requestBody.readBytes() + location?.let { exchange.responseHeaders.add("Location", it) } + val body = if (status == 200) """{"data":null}""".toByteArray() else ByteArray(0) + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(status, if (body.isEmpty()) -1 else body.size.toLong()) + exchange.responseBody.use { it.write(body) } + } + http.start() + servers += http + return Peer(http, seen) + } + + /** + * A minimal WebSocket server: accepts the upgrade and records the text frames the client sends + * (the `graphql-ws` `connection_init` carries the API key). It answers nothing else. + */ + private class WsPeer : AutoCloseable { + private val socket = ServerSocket(0, 10, InetAddress.getByName("127.0.0.1")) + val port get() = socket.localPort + val connections = AtomicInteger() + val frames = CopyOnWriteArrayList() + + init { + thread(isDaemon = true) { + try { + while (true) { + val client = socket.accept() + connections.incrementAndGet() + thread(isDaemon = true) { serve(client) } + } + } catch (_: IOException) { /* closed */ } + } + } + + private fun serve(client: Socket) = try { + client.use { + it.soTimeout = 5_000 + val input = it.getInputStream().buffered() + val head = StringBuilder() + while (!head.endsWith("\r\n\r\n")) { + val b = input.read() + if (b < 0) return@use + head.append(b.toChar()) + } + val key = Regex("(?im)^Sec-WebSocket-Key: (.+)$").find(head)?.groupValues?.get(1)?.trim() ?: return@use + val protocol = Regex("(?im)^Sec-WebSocket-Protocol: (.+)$").find(head)?.groupValues?.get(1)?.trim() + val accept = Base64.getEncoder().encodeToString( + MessageDigest.getInstance("SHA-1").digest((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").toByteArray()), + ) + val reply = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + + "Sec-WebSocket-Accept: $accept\r\n" + + (protocol?.let { p -> "Sec-WebSocket-Protocol: ${p.substringBefore(',').trim()}\r\n" } ?: "") + "\r\n" + it.getOutputStream().apply { write(reply.toByteArray()); flush() } + while (true) { + val b0 = input.read() + if (b0 < 0) break + var len = input.read() and 0x7f + if (len == 126) len = (input.read() shl 8) or input.read() + val mask = ByteArray(4).also { m -> input.readNBytes(m, 0, 4) } + val payload = ByteArray(len).also { p -> input.readNBytes(p, 0, len) } + for (i in payload.indices) payload[i] = (payload[i].toInt() xor mask[i % 4].toInt()).toByte() + if (b0 and 0x0f == 1) frames += String(payload) + } + } + } catch (_: IOException) { /* peer went away or timed out */ } + + override fun close() = socket.close() + } + + private val variants: Map ApolloClient> = mapOf( + "build" to { factory, url -> factory.build(url, "secret") }, + "buildLongRunning" to { factory, url -> factory.buildLongRunning(url, "secret") }, + ) + + private fun failure(client: ApolloClient) = runBlocking { client.query(GetArrayQuery()).execute().exception } + + @Test fun the_key_never_reaches_a_second_host_through_a_redirect() { + // 302 is what Unraid's nginx sends; 303/307/308 are the other statuses OkHttp would follow. + for ((name, build) in variants) for (status in listOf(301, 302, 303, 307, 308)) { + val elsewhere = peer(200) + val redirecting = peer(status, location = "${elsewhere.url}/graphql") + + val failure = failure(build(ApolloClientFactory(), redirecting.url)) + + assertEquals("$name $status: the address the user entered was asked", listOf("secret"), redirecting.seenKeys.toList()) + assertEquals("$name $status: nothing reached the redirect target", emptyList(), elsewhere.seenKeys.toList()) + assertTrue("$name $status: a 3xx is a failure, got $failure", failure is ApolloHttpException && failure.statusCode == status) + } + } + + // WHY: a redirect that is not followed is the answer the tab gets; it must reach the user as its own + // reason that names the target. It is no outage: the pill must not say Offline (isConnectionProblem). + @Test fun a_redirect_reaches_the_user_as_its_own_reason_with_the_target() { + val elsewhere = peer(200) + val redirecting = peer(302, location = "${elsewhere.url}/graphql") + + val error = failure(ApolloClientFactory().build(redirecting.url, "secret"))!!.toQueryError("Network error") + + assertEquals(ErrorReason.Redirected, error.reason) + assertTrue(error.message, error.message.contains("The server redirects to ${elsewhere.url}.")) + assertFalse(error.reason.isConnectionProblem) + } + + // WHY: nothing may change for the many servers that do not redirect. + @Test fun a_server_that_does_not_redirect_is_used_as_before() { + for ((name, build) in variants) { + val plain = peer(200) + + val failure = failure(build(ApolloClientFactory(), plain.url)) + + assertEquals(name, listOf("secret"), plain.seenKeys.toList()) + assertFalse("$name: an answer is no failure of the transport, got $failure", failure is ApolloHttpException) + } + } + + // WHY: the downgrade from https to http cannot be staged without a TLS peer; the two switches that + // forbid it (followRedirects covers every redirect, followSslRedirects the scheme change) are pinned. + @Test fun the_clients_are_configured_to_follow_no_redirect_at_all() { + val factory = ApolloClientFactory() + for ((name, client) in listOf("short" to factory.baseHttpClient, "long" to factory.longRunningHttpClient, "background" to factory.backgroundHttpClient)) { + assertFalse("$name followRedirects", client.followRedirects) + assertFalse("$name followSslRedirects", client.followSslRedirects) + } + } + + // WHY: the WebSocket sends the key in `connection_init` AFTER the handshake. A followed handshake + // redirect would complete on the second host and hand it the key; not following ends it at the 302. + @Test fun the_websocket_handshake_does_not_follow_a_redirect() { + val elsewhere = WsPeer().also { wsPeers += it } + val redirecting = peer(302, location = "http://127.0.0.1:${elsewhere.port}/graphql") + + val client = ApolloClientFactory().buildWs(redirecting.url, "secret") + runBlocking { + withTimeoutOrNull(4_000) { + try { client.subscription(DockerContainerStatsSubscription()).toFlow().first() } catch (_: Exception) { null } + } + } + + assertTrue("the address the user entered was asked", redirecting.seenKeys.isNotEmpty()) + assertEquals("no connection to the redirect target", 0, elsewhere.connections.get()) + assertEquals("the key was not sent there", emptyList(), elsewhere.frames.toList()) + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/demo/DemoStateTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/demo/DemoStateTest.kt index 6524ff42..0c432ba9 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/demo/DemoStateTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/demo/DemoStateTest.kt @@ -41,6 +41,25 @@ class DemoStateTest { assertEquals(ContainerStatus.Running, start.stopContainer("plex").restartContainer("plex").container("plex").status) } + // WHY (#345): Docker answers `start` on a paused container with "try unpause instead". The demo must + // not hide the bug the real server shows: only unpause resumes a paused container. + @Test fun aPausedContainerResumesWithUnpauseNotStart() { + val paused = start.pauseContainer("plex") + assertEquals(ContainerStatus.Paused, paused.startContainer("plex").container("plex").status) + assertEquals(ContainerStatus.Running, paused.unpauseContainer("plex").container("plex").status) + } + + // WHY: unpause answers only a paused container; it must not start a stopped one by the back door. + @Test fun unpauseLeavesAStoppedOrRunningContainerAlone() { + assertEquals(ContainerStatus.Exited, start.unpauseContainer("jellyfin").container("jellyfin").status) + assertEquals(ContainerStatus.Running, start.unpauseContainer("plex").container("plex").status) + } + + // WHY: restart is stop + start (or one step) on the server and works on a paused container too. + @Test fun restartEndsRunningAlsoForAPausedContainer() { + assertEquals(ContainerStatus.Running, start.pauseContainer("plex").restartContainer("plex").container("plex").status) + } + @Test fun pauseOnlyPausesARunningContainer() { assertEquals(ContainerStatus.Paused, start.pauseContainer("plex").container("plex").status) assertEquals(ContainerStatus.Exited, start.pauseContainer("jellyfin").container("jellyfin").status) diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionRefusalTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionRefusalTest.kt new file mode 100644 index 00000000..2334254c --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionRefusalTest.kt @@ -0,0 +1,121 @@ +package io.github.nofuturekid.nova.data.repository + +import com.apollographql.apollo.ApolloClient +import com.apollographql.apollo.api.Error +import com.apollographql.apollo.api.http.HttpRequest +import com.apollographql.apollo.api.http.HttpResponse +import com.apollographql.apollo.network.http.HttpEngine +import io.github.nofuturekid.nova.data.model.KeyAction +import io.github.nofuturekid.nova.data.repository.UnraidRepository.Companion.runAction +import io.github.nofuturekid.nova.graphql.StartContainerMutation +import io.github.nofuturekid.nova.graphql.StopVmMutation +import io.github.nofuturekid.nova.ui.screens.main.MainViewModel +import kotlinx.coroutines.test.runTest +import okio.Buffer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The fallback path of #315: while the key's access is unknown the buttons are shown, and a refused + * action must say WHY instead of "Forbidden resource". The FORBIDDEN body is the answer a real + * Unraid 7.4.0 server (API 4.37.11) gave a VIEWER key for `docker.start` on 2026-11-13 (the id did + * not exist and the guard ran before the resolver, so nothing changed); the VM and UNAUTHENTICATED + * bodies have the same shape with the path adapted. + */ +class ActionRefusalTest { + + private class Engine(private val reply: () -> HttpResponse) : HttpEngine { + override suspend fun execute(request: HttpRequest): HttpResponse = reply() + override fun close() {} + } + + private fun reply(body: String): () -> HttpResponse = { + HttpResponse.Builder(200) + .addHeader("Content-Type", "application/graphql-response+json") + .body(Buffer().writeUtf8(body)) + .build() + } + + private val forbiddenDocker = reply( + """{"errors":[{"message":"Forbidden resource","locations":[{"line":1,"column":21}],"path":["docker","start"],"extensions":{"code":"FORBIDDEN","originalError":{"message":"Forbidden resource","error":"Forbidden","statusCode":403}}}],"data":null}""", + ) + private val forbiddenVm = reply( + """{"errors":[{"message":"Forbidden resource","locations":[{"line":1,"column":15}],"path":["vm","stop"],"extensions":{"code":"FORBIDDEN","originalError":{"message":"Forbidden resource","error":"Forbidden","statusCode":403}}}],"data":null}""", + ) + private val unauthenticated = reply( + """{"errors":[{"message":"API key validation failed","locations":[{"line":1,"column":21}],"path":["docker","start"],"extensions":{"code":"UNAUTHENTICATED","originalError":{"message":"API key validation failed","error":"Unauthorized","statusCode":401}}}],"data":null}""", + ) + + private fun client(engine: HttpEngine) = + ApolloClient.Builder().serverUrl("http://unraid.test/graphql").httpEngine(engine).build() + + private suspend fun failureOf(block: suspend () -> Unit): ActionFailedException? = + try { block(); null } catch (e: ActionFailedException) { e } + + // WHY: #315. A user who presses Restart with a read-only key learns which permission to grant, + // not the server's internal "Forbidden resource". + @Test fun forbiddenActionNamesPermission() = runTest { + val e = failureOf { client(Engine(forbiddenDocker)).runAction(StartContainerMutation("c1")) } + assertNotNull(e) + assertEquals("your API key isn't allowed to do this (it needs DOCKER:UPDATE_ANY)", e!!.message) + assertEquals("the server's own wording stays available for diagnosis", "Forbidden resource", e.detail) + } + + @Test fun forbiddenVmActionNamesTheVmPermission() = runTest { + val e = failureOf { client(Engine(forbiddenVm)).runAction(StopVmMutation("v1")) } + assertEquals("your API key isn't allowed to do this (it needs VMS:UPDATE_ANY)", e!!.message) + } + + // WHY: the snackbar prefix is added by the view model; the sentence must read as one sentence. + @Test fun snackbarReadsAsOneSentence() = runTest { + val messages = mutableListOf() + MainViewModel.runResilientAction(emit = { messages += it }) { + client(Engine(forbiddenDocker)).runAction(StartContainerMutation("c1")) + } + assertEquals( + listOf("Action failed: your API key isn't allowed to do this (it needs DOCKER:UPDATE_ANY)"), + messages, + ) + } + + @Test fun rejectedKeyIsSaidSo() = runTest { + val e = failureOf { client(Engine(unauthenticated)).runAction(StartContainerMutation("c1")) } + assertEquals("the server didn't accept the API key", e!!.message) + } + + // WHY: a refusal for an operation NOVA has no table entry for must still be explained, without + // inventing a permission name. + @Test fun unknownOperationGetsTheGenericRefusal() { + val errors = listOf(Error.Builder("Forbidden resource").extensions(mapOf("code" to "FORBIDDEN")).build()) + assertEquals("your API key isn't allowed to do this", actionRefusalMessage(errors, "SomethingNew")) + assertEquals("your API key isn't allowed to do this", actionRefusalMessage(errors, null)) + } + + // WHY: only a refusal for the key is reworded. Any other server error keeps its own text, or the + // user loses the one clue that explains it. + @Test fun otherErrorsAreNotReworded() { + val errors = listOf(Error.Builder("Failed to start").extensions(mapOf("code" to "INTERNAL_SERVER_ERROR")).build()) + assertNull(actionRefusalMessage(errors, "StartContainer")) + assertNull(actionRefusalMessage(emptyList(), "StartContainer")) + assertNull(actionRefusalMessage(null, "StartContainer")) + } + + // WHY: the permission named in the message must be the one the buttons are hidden by. Every + // mutation NOVA sends names exactly its KeyAction's permission, so the two cannot drift apart. + @Test fun everyOperationNamesItsOwnPermission() { + val errors = listOf(Error.Builder("Forbidden resource").extensions(mapOf("code" to "FORBIDDEN")).build()) + KeyAction.entries.forEach { action -> + action.operations.forEach { op -> + val text = actionRefusalMessage(errors, op)!! + assertTrue("$op: $text", text.endsWith("(it needs ${action.permission})")) + KeyAction.entries.filter { it != action }.forEach { + assertFalse("$op must not name ${it.permission}", text.contains(it.permission)) + } + } + } + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionResponseTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionResponseTest.kt index 4886c78f..50cd24ea 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionResponseTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ActionResponseTest.kt @@ -121,6 +121,30 @@ class ActionResponseTest { assertTrue(uses.single().contains("mutation(m).execute().orThrow()")) } + private val unpaused = json("""{"data":{"docker":{"unpause":{"id":"c1","state":"RUNNING"}}}}""") + + // WHY (#345): Docker refuses `start` for a paused container ("try unpause instead"), so Resume + // must send unpause and never start. + @Test fun resumingAPausedContainer_sendsUnpause_neverStart() = runTest { + val engine = ScriptedEngine(listOf(unpaused, started)) + UnraidRepository.startContainer(client(engine), "c1", paused = true) + assertEquals(listOf("UnpauseContainer"), engine.operationNames()) + } + + // WHY: the fix must not turn every Start into unpause: a stopped container still gets start. + @Test fun startingAStoppedContainer_sendsStart_neverUnpause() = runTest { + val engine = ScriptedEngine(listOf(started, unpaused)) + UnraidRepository.startContainer(client(engine), "c1", paused = false) + assertEquals(listOf("StartContainer"), engine.operationNames()) + } + + // WHY: a refused resume (no permission) must reach the user with the server's text, like any action. + @Test fun refusedResume_failsTheActionWithServerText() = runTest { + val e = failureOf { UnraidRepository.startContainer(client(ScriptedEngine(listOf(forbidden))), "c1", paused = true) } + assertNotNull("a refused unpause must fail the action", e) + assertTrue(e!!.message, e.message!!.contains("API key lacks DOCKER:UPDATE_ANY")) + } + @Test fun restart_onSuccess_sendsStopThenStart() = runTest { val engine = ScriptedEngine(listOf(stopped, started)) UnraidRepository.restartContainer(client(engine), "c1", atomic = false) diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt index b95ff7d0..437d8a98 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ErrorReasonTest.kt @@ -5,6 +5,7 @@ import com.apollographql.apollo.api.http.HttpRequest import com.apollographql.apollo.api.http.HttpResponse import com.apollographql.apollo.exception.ApolloException import com.apollographql.apollo.network.http.HttpEngine +import io.github.nofuturekid.nova.graphql.GetDockerContainersQuery import io.github.nofuturekid.nova.graphql.GetVmsQuery import kotlinx.coroutines.test.runTest import okio.Buffer @@ -56,6 +57,9 @@ class ErrorReasonTest { """{"errors":[{"message":"boom","extensions":{"code":"INTERNAL_SERVER_ERROR"}}],"data":{"docker":null}}""", ) private val unreachable: () -> HttpResponse = { throw IOException("connection refused") } + private fun redirect(status: Int, location: String?): () -> HttpResponse = { + HttpResponse.Builder(status).apply { if (location != null) addHeader("Location", location) }.build() + } /** Runs the VMs query like the poll does and classifies what comes back. */ private suspend fun reasonOf(server: () -> HttpResponse): ErrorReason { @@ -64,6 +68,14 @@ class ErrorReasonTest { return classifyErrorReason(resp.exception, resp.errors) } + /** The same for the Docker query, which the Docker-off answer is really given to. */ + private suspend fun reasonOfDocker(server: () -> HttpResponse): ErrorReason { + val client = ApolloClient.Builder().serverUrl("http://unraid.test/graphql").httpEngine(Engine(server)).build() + val resp = client.query(GetDockerContainersQuery()).execute() + assertNull("the Docker-off body must parse, not fail in transport", resp.exception) + return classifyErrorReason(resp.exception, resp.errors) + } + // WHY: #247. A server whose API is too old answers HTTP 400 with a validation error; the tab must // show the "API too old" hint, not raw validation text. @Test fun validationError_isApiTooOld() = runTest { @@ -85,6 +97,15 @@ class ErrorReasonTest { assertEquals(ErrorReason.ServiceOff, reasonOf(dockerOff)) } + // WHY: #356. The Overview keeps its card only if the real Docker query turns this answer into + // ServiceOff; a transport exception here would fall back to Unreachable and read as offline. + @Test fun dockerSocketUnavailable_onTheDockerQuery_isServiceOff() = runTest { + val body = reply( + """{"errors":[{"message":"Docker socket unavailable.","path":["docker","containers"],"extensions":{"code":"INTERNAL_SERVER_ERROR"}}],"data":{"docker":null}}""", + ) + assertEquals(ErrorReason.ServiceOff, reasonOfDocker(body)) + } + @Test fun vmsNotAvailable_isServiceOff() = runTest { assertEquals(ErrorReason.ServiceOff, reasonOf(vmsOff)) } @@ -99,6 +120,23 @@ class ErrorReasonTest { assertEquals(ErrorReason.Unreachable, reasonOf(unreachable)) } + // WHY: the clients no longer follow a redirect (ADR-0051), so a 3xx is the answer the tab gets. It must + // not read as an outage ("Can't reach the server" and an Offline pill): the server answered, and the fix + // is the address in the server's settings. Unraid answers http requests with 302 when SSL is Yes or Strict. + @Test fun redirect_isRedirected_notUnreachable() = runTest { + listOf(301, 302, 303, 307, 308).forEach { status -> + assertEquals("$status", ErrorReason.Redirected, reasonOf(redirect(status, "https://tower.example.net/graphql"))) + } + assertEquals("no Location header", ErrorReason.Redirected, reasonOf(redirect(302, null))) + } + + // WHY: 304 and 4xx/5xx are no redirects; only a status the client would have followed gets the reason. + @Test fun otherHttpStatuses_areNotRedirected() = runTest { + listOf(304, 404, 500).forEach { status -> + assertEquals("$status", ErrorReason.Unreachable, reasonOf(redirect(status, "https://tower.example.net/"))) + } + } + // WHY: rule order. A response that carries both a key refusal and a service message is about the key. @Test fun firstMatchingRuleWins() { val both = listOf( diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt index 15acdde4..ed8bea36 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/ResponseClassifierTest.kt @@ -1,5 +1,6 @@ package io.github.nofuturekid.nova.data.repository +import com.apollographql.apollo.api.http.HttpHeader import com.apollographql.apollo.exception.ApolloHttpException import com.apollographql.apollo.exception.ApolloNetworkException import io.github.nofuturekid.nova.data.api.CertIssue @@ -7,6 +8,9 @@ import io.github.nofuturekid.nova.data.api.CertificateChangedException import io.github.nofuturekid.nova.data.api.CertificateUntrustedException import org.junit.Assert.assertEquals import org.junit.Assert.assertNull +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue import org.junit.Test import java.io.IOException @@ -158,4 +162,78 @@ class ResponseClassifierTest { assertEquals("Error while reading JSON response (EOFException: End of input at path $.data)", err.message) assertNull(err.detail) } + + private fun redirect(status: Int, location: String?, name: String = "Location") = ApolloHttpException( + status, listOfNotNull(location?.let { HttpHeader(name, it) }), null, "HTTP error $status", null, + ) + + // WHY: a redirect is what Unraid sends to an http request when SSL is Yes or Strict (nginx `return 302`). + // The user must be told where it points, as the address to enter; the message names the target and + // the advice, and stays out of the "Offline" class of failures. + @Test fun redirect_namesTheTargetAndTheAdvice() { + val err = redirect(302, "https://192-168-1-100.abc123.myunraid.net:8443/graphql?x=1").toQueryError("Network error") + assertEquals(ErrorReason.Redirected, err.reason) + assertEquals( + "The server redirects to https://192-168-1-100.abc123.myunraid.net:8443. Edit the server and enter that address.", + err.message, + ) + assertEquals("the raw text stays behind Show details", "HTTP error 302", err.detail) + assertFalse("a redirect must not turn the pill to Offline", err.reason.isConnectionProblem) + } + + // WHY: only the origin is shown. A path says nothing the user can act on, a query can carry tokens, and a + // Location with user:password@ must never be echoed onto the screen. + @Test fun redirect_showsOnlySchemeHostAndNonDefaultPort() { + assertEquals( + "The server redirects to https://tower.example.net. Edit the server and enter that address.", + redirect(302, "https://tower.example.net:443/graphql").redirectMessage(), + ) + assertEquals( + "The server redirects to http://[::1]:8080. Edit the server and enter that address.", + redirect(307, "http://[::1]:8080/a?token=secret#frag").redirectMessage(), + ) + val withCredentials = redirect(308, "https://admin:hunter2@tower.example.net/graphql").redirectMessage()!! + assertTrue(withCredentials, !withCredentials.contains("hunter2") && !withCredentials.contains("admin")) + assertTrue(withCredentials, withCredentials.contains("https://tower.example.net.")) + } + + // WHY: a redirect without a usable target still must be a redirect (not "HTTP error 302"), and the text + // must not invent a host. The header name is case-insensitive in HTTP. + @Test fun redirect_withoutUsableTarget_saysSoWithoutInventingOne() { + val unknown = "The server redirects to another address, but doesn't say which. Check the address in this server's settings." + assertEquals(unknown, redirect(302, null).redirectMessage()) + assertEquals("relative", unknown, redirect(302, "/login").redirectMessage()) + assertEquals("not http", unknown, redirect(302, "javascript:alert(1)").redirectMessage()) + assertEquals( + "The server redirects to https://tower.example.net. Edit the server and enter that address.", + redirect(302, "https://tower.example.net/", name = "location").redirectMessage(), + ) + } + + // WHY: only the statuses OkHttp used to follow are redirects; a 304 or an error is not. + @Test fun otherStatuses_areNotRedirects() { + listOf(200, 304, 400, 401, 404, 500).forEach { + assertNull("$it", redirect(it, "https://tower.example.net/").redirectMessage()) + } + assertNull(ApolloNetworkException("down").redirectMessage()) + assertEquals(ErrorReason.Unreachable, redirect(404, null).toQueryError("Network error").reason) + } + + // WHY: the Add server sheet's Test shows the classifier's message, so Test and the tabs say the same. + @Test fun redirect_isTheTestConnectionMessage() { + val c = classifyResponse(redirect(302, "https://tower.example.net/"), hasErrors = false, errorMessage = null, dataIsNull = true) + assertEquals( + RespClass.Failed("The server redirects to https://tower.example.net. Edit the server and enter that address."), + c, + ) + } + + // WHY: an action (start a container) that meets a redirect did not run; the snackbar says why instead of + // "the server answered HTTP 302". + @Test fun redirect_failsAnAction_withTheTarget() { + val e = assertThrows(ActionFailedException::class.java) { + checkActionResponse(redirect(307, "https://tower.example.net/graphql"), hasErrors = false, errorMessage = null) + } + assertEquals("the server redirects to https://tower.example.net. Edit the server and enter that address.", e.message) + } } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt new file mode 100644 index 00000000..dd195bc7 --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/TestConnectionOutcomeTest.kt @@ -0,0 +1,133 @@ +package io.github.nofuturekid.nova.data.repository + +import com.apollographql.apollo.ApolloClient +import com.apollographql.apollo.api.http.HttpRequest +import com.apollographql.apollo.api.http.HttpResponse +import com.apollographql.apollo.network.http.HttpEngine +import io.github.nofuturekid.nova.data.api.CertificateUntrustedException +import kotlinx.coroutines.test.runTest +import okio.Buffer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.IOException + +/** + * What the Add server sheet's Test button reports (#315). The probe is the capability detection + * (version and `me`), not `Ping`: the server answers a bare `__typename` for ANY key, so the old + * Test said "Connected" for a wrong key. Bodies are the verbatim answers of an Unraid 7.4.0 server + * (API 4.37.11) recorded on 2026-11-13, except the explicit-permission one, which is constructed. + * They run on a scripted HTTP engine through the real Apollo response path. + */ +class TestConnectionOutcomeTest { + + private class Engine( + private val version: () -> HttpResponse, + private val access: () -> HttpResponse, + ) : HttpEngine { + override suspend fun execute(request: HttpRequest): HttpResponse { + val body = Buffer().also { request.body?.writeTo(it) }.readUtf8() + return if ("GetApiVersion" in body) version() else access() + } + override fun close() {} + } + + private fun reply(body: String, status: Int = 200, type: String = "application/json"): () -> HttpResponse = { + HttpResponse.Builder(status).addHeader("Content-Type", type).body(Buffer().writeUtf8(body)).build() + } + + private val versionOk = reply("""{"data":{"info":{"versions":{"core":{"unraid":"7.4.0","api":"4.37.11+8e587fe2"}}}}}""") + private val viewerMe = reply("""{"data":{"me":{"roles":["VIEWER"],"permissions":[]}}}""") + private val adminMe = reply("""{"data":{"me":{"roles":["ADMIN"],"permissions":[]}}}""") + private val viewerWithDockerAndVms = reply( + """{"data":{"me":{"roles":["VIEWER"],"permissions":[{"resource":"DOCKER","actions":["UPDATE_ANY"]},{"resource":"VMS","actions":["UPDATE_ANY"]}]}}}""", + ) + private val unauthenticated = reply( + """{"errors":[{"message":"API key validation failed","locations":[{"line":1,"column":3}],"path":["info"],"extensions":{"code":"UNAUTHENTICATED","originalError":{"message":"API key validation failed","error":"Unauthorized","statusCode":401}}}],"data":null}""", + ) + private val forbidden = reply( + """{"errors":[{"message":"Forbidden resource","locations":[{"line":1,"column":3}],"path":["me"],"extensions":{"code":"FORBIDDEN","originalError":{"message":"Forbidden resource","error":"Forbidden","statusCode":403}}}],"data":null}""", + ) + private val validation400 = reply( + """{"errors":[{"message":"Cannot query field \"core\" on type \"InfoVersions\".","locations":[{"line":1,"column":12}],"extensions":{"code":"GRAPHQL_VALIDATION_FAILED"}}]}""", + status = 400, + type = "application/graphql-response+json", + ) + private val serverError = reply( + """{"errors":[{"message":"boom","extensions":{"code":"INTERNAL_SERVER_ERROR"}}],"data":null}""", + ) + + private suspend fun test(version: () -> HttpResponse, access: () -> HttpResponse): TestOutcome = + testOutcomeOf(probeCapabilities(client(Engine(version, access)))) + + private fun client(engine: HttpEngine) = + ApolloClient.Builder().serverUrl("http://unraid.test/graphql").httpEngine(engine).build() + + // WHY: the whole defect. A wrong key used to pass the Test, so the user saved a server that then + // showed nothing; the server's UNAUTHENTICATED must fail it. + @Test fun testConnectionRejectsWrongKey() = runTest { + val out = test(unauthenticated, unauthenticated) + assertEquals(TestOutcome.Failed("The server didn't accept this API key"), out) + } + + // WHY: #315. A read-only key is a valid key, and the user is told up front that NOVA will hide + // the controls, instead of finding that out from missing buttons. + @Test fun testConnectionReportsViewOnly() = runTest { + val out = test(versionOk, viewerMe) as TestOutcome.Ok + assertEquals("Connected · Unraid 7.4.0 · API 4.37.11", out.title) + assertEquals("View only key: NOVA will hide controls", out.detail) + assertFalse(out.apiTooOld) + } + + @Test fun testConnectionReportsFullControl() = runTest { + val out = test(versionOk, adminMe) as TestOutcome.Ok + assertEquals("Full control", out.detail) + } + + // WHY: a least-privilege key (#316) must be described by what it can do, not as "view only". + @Test fun testConnectionNamesWhatAPartialKeyCanControl() = runTest { + val out = test(versionOk, viewerWithDockerAndVms) as TestOutcome.Ok + assertEquals("Can control: Docker, VMs", out.detail) + } + + // WHY: a refused `me` is fail-open everywhere; the Test must not claim "view only" for a key whose + // rights nobody could read. It says nothing about control, and the connection still counts. + @Test fun testConnectionSaysNothingAboutControlWhenAccessIsUnknown() = runTest { + val out = test(versionOk, forbidden) as TestOutcome.Ok + assertEquals(TestControl.Unknown, out.control) + assertEquals("Server responded · ready to save", out.detail) + assertEquals("Connected · Unraid 7.4.0 · API 4.37.11", out.title) + } + + // WHY: #247. The server answers, so the connection is fine; what is wrong is the API version, and + // the user is told what to update before they wonder why screens fail. + @Test fun testConnectionWarnsWhenTheApiIsTooOld() = runTest { + val out = test(validation400, viewerMe) as TestOutcome.Ok + assertTrue(out.apiTooOld) + assertEquals("Connected", out.title) + assertEquals( + "Connected, but this server's Unraid API is too old. NOVA needs 4.30.0 or newer (Unraid 7.2.5 or newer).", + out.detail, + ) + } + + // WHY: an unreachable server must fail the Test with the cause, never read as a working connection. + @Test fun testConnectionFailsWhenTheServerIsUnreachable() = runTest { + val unreachable: () -> HttpResponse = { throw IOException("connection refused") } + val out = test(unreachable, unreachable) + assertTrue(out.toString(), out is TestOutcome.Failed) + } + + // WHY: the self-signed-certificate dialog depends on the Test surfacing the fingerprint. Moving the + // Test off Ping must not swallow the certificate exception into a generic failure. + @Test fun testConnectionStillSurfacesAnUntrustedCertificate() = runTest { + val untrusted: () -> HttpResponse = { throw CertificateUntrustedException("AB:CD") } + assertEquals(TestOutcome.CertUntrusted("AB:CD"), test(untrusted, untrusted)) + } + + // WHY: an error NOVA does not classify is shown with the server's own text, not as a success. + @Test fun testConnectionShowsTheServersOwnErrorText() = runTest { + assertEquals(TestOutcome.Failed("boom"), test(serverError, serverError)) + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt index b690d340..f8d3fcb2 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/data/repository/UnraidGatewayTest.kt @@ -122,14 +122,17 @@ class UnraidGatewayTest { fun vm(id: String) = demo.current.vms.first { it.id == id } gateway.stopContainer("plex"); assertEquals(ContainerStatus.Exited, container("plex").status) - gateway.startContainer("plex"); assertEquals(ContainerStatus.Running, container("plex").status) + gateway.startContainer("plex", paused = false); assertEquals(ContainerStatus.Running, container("plex").status) // The demo restarts the container in its model whichever way the real server would be asked. gateway.stopContainer("plex"); gateway.restartContainer("plex", atomic = true) assertEquals(ContainerStatus.Running, container("plex").status) gateway.stopContainer("plex"); gateway.restartContainer("plex", atomic = false) assertEquals(ContainerStatus.Running, container("plex").status) gateway.pauseContainer("plex"); assertEquals(ContainerStatus.Paused, container("plex").status) - gateway.startContainer("jellyfin"); assertEquals(ContainerStatus.Running, container("jellyfin").status) + // Resume is `unpause`, and Docker refuses `start` for a paused container: the demo's model does the same (#345). + gateway.startContainer("plex", paused = false); assertEquals(ContainerStatus.Paused, container("plex").status) + gateway.startContainer("plex", paused = true); assertEquals(ContainerStatus.Running, container("plex").status) + gateway.startContainer("jellyfin", paused = false); assertEquals(ContainerStatus.Running, container("jellyfin").status) gateway.updateContainer("grafana") assertEquals(ContainerUpdateStatus.UpToDate, container("grafana").updateStatus) assertEquals(ContainerUpdateStatus.UpdateAvailable, container("nextcloud").updateStatus) diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/TabFailureRenderingTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/TabFailureRenderingTest.kt index ee6460f5..0f5339d0 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/TabFailureRenderingTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/TabFailureRenderingTest.kt @@ -82,6 +82,7 @@ class TabFailureRenderingTest { ErrorReason.Forbidden to "This API key can't read containers", ErrorReason.ApiTooOld to "This server's Unraid API is too old", ErrorReason.ServiceOff to "Docker is turned off", + ErrorReason.Redirected to "The address needs to change", ErrorReason.ServerError to "The server couldn't load containers", ) assertTrue("one case per reason", titles.keys == ErrorReason.entries.toSet()) diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/ViewOnlyControlsTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/ViewOnlyControlsTest.kt new file mode 100644 index 00000000..ef49e08e --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/ViewOnlyControlsTest.kt @@ -0,0 +1,364 @@ +package io.github.nofuturekid.nova.ui.screens + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.junit4.ComposeContentTestRule +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onAllNodesWithContentDescription +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.github.nofuturekid.nova.data.demo.DemoFixtures +import io.github.nofuturekid.nova.data.demo.DemoUnraid +import io.github.nofuturekid.nova.data.local.LayoutMode +import io.github.nofuturekid.nova.data.model.Access +import io.github.nofuturekid.nova.data.model.ArrayInfo +import io.github.nofuturekid.nova.data.model.ArrayState +import io.github.nofuturekid.nova.data.model.Container +import io.github.nofuturekid.nova.data.model.ContainerStatus +import io.github.nofuturekid.nova.data.model.ContainerUpdateStatus +import io.github.nofuturekid.nova.data.model.KeyAction +import io.github.nofuturekid.nova.data.model.ParityCheck +import io.github.nofuturekid.nova.data.model.Vm +import io.github.nofuturekid.nova.data.model.VmState +import io.github.nofuturekid.nova.data.repository.DomainState +import io.github.nofuturekid.nova.ui.components.ViewOnly +import io.github.nofuturekid.nova.ui.screens.array.ArrayTab +import io.github.nofuturekid.nova.ui.screens.container.ContainerDetailSheet +import io.github.nofuturekid.nova.ui.screens.docker.DockerTab +import io.github.nofuturekid.nova.ui.screens.notifications.NotificationsSheet +import io.github.nofuturekid.nova.ui.screens.vms.VmDetailSheet +import io.github.nofuturekid.nova.ui.screens.vms.VmsTab +import io.github.nofuturekid.nova.ui.theme.ThemeMode +import io.github.nofuturekid.nova.ui.theme.UnraidTheme +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.TestScope +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * #315: a key that may not control something is not offered the controls, and one note says why. + * Each surface is tested in pairs: with [Access.Denied] the buttons are gone and the note is + * there; with [Access.Unknown] (detection failed, not finished, or a role NOVA does not know) and + * with [Access.Allowed] the very same screen shows its buttons. Without the second half a screen + * that hides everything would pass. Same Robolectric setup as the other tab tests. + */ +@RunWith(AndroidJUnit4::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35], qualifiers = "w432dp-h768dp-night-400dpi") +class ViewOnlyControlsTest { + + @get:Rule + val rule = createComposeRule() + + private fun show(content: @Composable () -> Unit) = + rule.setContent { UnraidTheme(themeMode = ThemeMode.Dark) { content() } } + + private fun ComposeContentTestRule.hasText(text: String) = + onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty() + + private fun ComposeContentTestRule.hasDescription(text: String) = + onAllNodesWithContentDescription(text).fetchSemanticsNodes().isNotEmpty() + + private fun container(name: String, status: ContainerStatus, update: ContainerUpdateStatus = ContainerUpdateStatus.UpToDate) = + Container( + id = name, name = name, image = "img/$name", status = status, autoStart = false, + iconColorHex = null, iconUrl = null, cpu = 0.0, memMb = 0, ports = emptyList(), volumes = emptyList(), + updateStatus = update, webUiUrl = null, networkIp = null, + ) + + private val running = container("plex", ContainerStatus.Running, ContainerUpdateStatus.UpdateAvailable) + private val stopped = container("sonarr", ContainerStatus.Exited) + private val paused = container("radarr", ContainerStatus.Paused) + + private val dockerNote = ViewOnly.Containers.title + private val vmsNote = ViewOnly.Vms.title + private val arrayNote = ViewOnly.Array.title + + // ── Docker tab ─────────────────────────────────────────────────── + + private fun dockerTab(control: () -> Access, layout: () -> LayoutMode = { LayoutMode.List }) = show { + DockerTab( + state = DomainState.Content(listOf(running, stopped, paused)), view = layout(), query = "", + onQueryChange = {}, onAddServer = {}, onOpenContainer = {}, onStart = {}, onRestart = {}, + onStop = {}, onUpdateAll = {}, control = control(), + ) + } + + // WHY: #315 acceptance. A read-only key is offered no Start, Stop, Restart or Resume, in any + // layout the user may have chosen, and the tab says why once. + @Test fun dockerTab_deniedHidesEveryContainerButton_andShowsOneNote() { + var layout by mutableStateOf(LayoutMode.List) + dockerTab({ Access.Denied }, { layout }) + listOf(LayoutMode.List, LayoutMode.Grouped, LayoutMode.Compose).forEach { l -> + layout = l + rule.waitForIdle() + listOf("Restart plex", "Stop plex", "Start sonarr", "Resume radarr").forEach { + assertFalse("$it in $l", rule.hasDescription(it)) + } + assertEquals("one note in $l", 1, rule.onAllNodesWithText(dockerNote).fetchSemanticsNodes().size) + assertTrue(rule.hasText("Needs DOCKER:UPDATE_ANY")) + } + } + + // WHY: the banner keeps telling the user that updates exist (a read), but no longer offers to run them. + @Test fun dockerTab_denied_keepsTheUpdateNotice_withoutTheAction() { + dockerTab({ Access.Denied }) + assertTrue(rule.hasText("1 container has an update")) + assertFalse(rule.hasText("Tap to update all")) + } + + // WHY: fail open. Unknown access (detection failed or still running) must look exactly as before the feature. + @Test fun dockerTab_unknownAndAllowedKeepTheButtons() { + var access by mutableStateOf(Access.Unknown) + dockerTab({ access }) + listOf(Access.Unknown, Access.Allowed).forEach { a -> + access = a + rule.waitForIdle() + listOf("Restart plex", "Stop plex", "Start sonarr", "Resume radarr").forEach { + assertTrue("$it with $a", rule.hasDescription(it)) + } + assertTrue(rule.hasText("Tap to update all")) + assertFalse(rule.hasText(dockerNote)) + } + } + + // ── Container sheet ────────────────────────────────────────────── + + private fun containerSheet(c: Container, control: Access) = show { + ContainerDetailSheet( + container = c, serverBaseUrl = "", liveStats = null, isUpdating = false, + onFetchLogs = { null }, onRefresh = {}, onDismiss = {}, + onStart = {}, onRestart = {}, onStop = {}, onUpdate = {}, control = control, + ) + } + + @Test fun containerSheet_denied_hasNoActions_butShowsTheNote() { + containerSheet(running, Access.Denied) + listOf("Update container", "Restart", "Stop", "Start").forEach { assertFalse(it, rule.hasText(it)) } + assertTrue(rule.hasText(dockerNote)) + // The container itself is still shown: only the actions are gone. + assertTrue(rule.hasText("plex")) + } + + @Test fun containerSheet_unknown_keepsTheActions() { + containerSheet(running, Access.Unknown) + listOf("Update container", "Restart", "Stop").forEach { assertTrue(it, rule.hasText(it)) } + assertFalse(rule.hasText(dockerNote)) + } + + // ── VMs ────────────────────────────────────────────────────────── + + private val vmRunning = Vm("v1", "Windows 11", VmState.Running, 4, 8, null) + private val vmPaused = Vm("v2", "Debian", VmState.Paused, 2, 4, null) + private val vmStopped = Vm("v3", "macOS", VmState.Stopped, 2, 4, null) + + private fun vmsTab(control: Access) = show { + VmsTab( + state = DomainState.Content(listOf(vmRunning, vmPaused, vmStopped)), view = LayoutMode.List, + onAddServer = {}, onStart = {}, onResume = {}, onPause = {}, onOpenVm = {}, control = control, + ) + } + + @Test fun vmsTab_deniedHidesPauseResumeStart_andShowsOneNote() { + vmsTab(Access.Denied) + listOf("Pause Windows 11", "Resume Debian", "Start macOS").forEach { assertFalse(it, rule.hasDescription(it)) } + assertEquals(1, rule.onAllNodesWithText(vmsNote).fetchSemanticsNodes().size) + assertTrue(rule.hasText("Needs VMS:UPDATE_ANY")) + // The VMs themselves stay listed. + assertTrue(rule.hasText("Windows 11")) + } + + @Test fun vmsTab_unknownKeepsTheButtons() { + vmsTab(Access.Unknown) + listOf("Pause Windows 11", "Resume Debian", "Start macOS").forEach { assertTrue(it, rule.hasDescription(it)) } + assertFalse(rule.hasText(vmsNote)) + } + + private fun vmSheet(vm: Vm, control: Access) = show { + VmDetailSheet( + vm = vm, onDismiss = {}, onStart = {}, onResume = {}, onPause = {}, onStop = {}, + onForceStop = {}, onReboot = {}, onReset = {}, control = control, + ) + } + + // WHY: the VM sheet has the most buttons (Reboot, Reset and Force stop are the dangerous ones); + // a read-only key must see none of them. + @Test fun vmSheet_denied_hidesEveryAction() { + vmSheet(vmRunning, Access.Denied) + listOf("Pause", "Stop", "Reboot", "Reset", "Force stop").forEach { assertFalse(it, rule.hasText(it)) } + assertTrue(rule.hasText(vmsNote)) + assertTrue(rule.hasText("Windows 11")) + } + + @Test fun vmSheet_unknown_keepsEveryAction() { + vmSheet(vmRunning, Access.Unknown) + listOf("Pause", "Stop", "Reboot", "Reset", "Force stop").forEach { assertTrue(it, rule.hasText(it)) } + assertFalse(rule.hasText(vmsNote)) + } + + @Test fun vmSheet_deniedWhileStopped_hidesStart() { + vmSheet(vmStopped, Access.Denied) + assertFalse(rule.hasText("Start")) + assertTrue(rule.hasText(vmsNote)) + } + + // ── Array ──────────────────────────────────────────────────────── + + private fun arrayInfo(state: ArrayState, parity: ParityCheck? = null) = + DemoFixtures.array.copy(state = state, parity = parity) + + private fun arrayTab(info: ArrayInfo, control: Access) = show { + ArrayTab( + state = DomainState.Content(info), view = LayoutMode.List, onAddServer = {}, + onStartArray = {}, onStopArray = {}, onStartParity = {}, onPauseParity = {}, + onResumeParity = {}, onCancelParity = {}, control = control, + ) + } + + // WHY: array start/stop and parity checks are the most consequential controls; a view-only key sees none. + @Test fun arrayTab_denied_hidesStopAndParityCheck() { + arrayTab(arrayInfo(ArrayState.Started), Access.Denied) + listOf("Stop", "Start", "Check parity").forEach { assertFalse(it, rule.hasText(it)) } + assertTrue(rule.hasText(arrayNote)) + assertTrue(rule.hasText("Needs ARRAY:UPDATE_ANY")) + // The disks stay listed. + assertTrue(rule.hasText("disk1")) + } + + @Test fun arrayTab_denied_hidesStartWhenStopped() { + arrayTab(arrayInfo(ArrayState.Stopped), Access.Denied) + assertFalse(rule.hasText("Start")) + assertTrue(rule.hasText(arrayNote)) + } + + @Test fun arrayTab_denied_hidesPauseAndCancelOfARunningCheck_butKeepsItsProgress() { + arrayTab(arrayInfo(ArrayState.Parity, ParityCheck(0.4f, 120.0, paused = false)), Access.Denied) + listOf("Pause", "Cancel", "Resume").forEach { assertFalse(it, rule.hasText(it)) } + assertTrue(rule.hasText("Parity operation in progress")) + assertTrue(rule.hasText("40%")) + } + + @Test fun arrayTab_unknown_keepsEveryControl() { + arrayTab(arrayInfo(ArrayState.Started), Access.Unknown) + listOf("Stop", "Check parity").forEach { assertTrue(it, rule.hasText(it)) } + assertFalse(rule.hasText(arrayNote)) + } + + @Test fun arrayTab_unknown_keepsPauseAndCancel() { + arrayTab(arrayInfo(ArrayState.Parity, ParityCheck(0.4f, 120.0, paused = false)), Access.Unknown) + listOf("Pause", "Cancel").forEach { assertTrue(it, rule.hasText(it)) } + } + + // ── Notifications ──────────────────────────────────────────────── + + private fun notificationsSheet(update: Access, delete: Access) = show { + NotificationsSheet( + state = DomainState.Content(DemoFixtures.notifications), + onDismiss = {}, onArchive = {}, onUnread = {}, onArchiveAll = {}, + onDeleteAllArchivedRequest = {}, onDeleteRequest = {}, update = update, delete = delete, + ) + } + + // WHY: the two permissions are separate on the server (UPDATE_ANY archives, DELETE_ANY deletes), + // so a key that may archive but not delete keeps exactly the archive buttons. + @Test fun notifications_updateAllowedDeleteDenied_hidesOnlyDelete() { + notificationsSheet(Access.Allowed, Access.Denied) + assertTrue(rule.hasText("Archive all")) + assertTrue(rule.hasDescription("Archive (mark read)")) + assertFalse(rule.hasDescription("Delete notification")) + assertTrue(rule.hasText("This API key can't delete notifications.")) + assertTrue(rule.hasText("Needs NOTIFICATIONS:DELETE_ANY")) + // On the archived tab "Delete all archived" is a delete too. + rule.onNodeWithText("Archived (1)").performClick() + rule.waitForIdle() + assertFalse(rule.hasText("Delete all archived")) + assertTrue(rule.hasDescription("Unarchive (restore to unread)")) + } + + @Test fun notifications_bothDenied_hidesEveryActionAndShowsOneNote() { + notificationsSheet(Access.Denied, Access.Denied) + assertFalse(rule.hasText("Archive all")) + assertFalse(rule.hasDescription("Archive (mark read)")) + assertFalse(rule.hasDescription("Delete notification")) + assertEquals(1, rule.onAllNodesWithText("View only. This API key can't archive or delete notifications.").fetchSemanticsNodes().size) + assertTrue(rule.hasText("Needs NOTIFICATIONS:UPDATE_ANY and NOTIFICATIONS:DELETE_ANY")) + // The notifications themselves are still readable. + assertTrue(rule.hasText("Warning [TOWER] - Disk 3 temperature")) + } + + @Test fun notifications_updateDeniedDeleteAllowed_hidesOnlyArchive() { + notificationsSheet(Access.Denied, Access.Allowed) + assertFalse(rule.hasText("Archive all")) + assertFalse(rule.hasDescription("Archive (mark read)")) + assertTrue(rule.hasDescription("Delete notification")) + assertTrue(rule.hasText("This API key can't archive notifications.")) + } + + @Test fun notifications_unknownKeepsEveryButton() { + notificationsSheet(Access.Unknown, Access.Unknown) + assertTrue(rule.hasText("Archive all")) + assertTrue(rule.hasDescription("Archive (mark read)")) + assertTrue(rule.hasDescription("Delete notification")) + assertFalse(rule.hasText("View only. This API key can't archive or delete notifications.")) + } + + // ── The demo ───────────────────────────────────────────────────── + + // WHY: the demo has no key and no server to refuse anything; it must look like an admin server. + // The access values come from what the demo reports to the capability model, exactly as MainScreen + // derives them, and no screen may show a note or lose a button. + @Test fun demo_hidesNoControl() { + val caps = DemoUnraid(TestScope(), MutableStateFlow(true)) { 0L }.capabilities().toCapabilities(null) + KeyAction.entries.forEach { assertEquals(it.name, Access.Allowed, caps.access(it)) } + assertNull(ViewOnly.notifications(caps.access(KeyAction.UpdateNotifications), caps.access(KeyAction.DeleteNotifications))) + + show { + DockerTab( + state = DomainState.Content(DemoFixtures.containers), view = LayoutMode.List, query = "", + onQueryChange = {}, onAddServer = {}, onOpenContainer = {}, onStart = {}, onRestart = {}, + onStop = {}, onUpdateAll = {}, control = caps.access(KeyAction.ControlDocker), + ) + } + assertTrue(rule.hasDescription("Restart plex")) + assertTrue(rule.hasDescription("Start jellyfin")) + assertFalse(rule.hasText(dockerNote)) + } + + @Test fun demo_vmsKeepTheirControls() { + val caps = DemoUnraid(TestScope(), MutableStateFlow(true)) { 0L }.capabilities().toCapabilities(null) + show { + VmsTab( + state = DomainState.Content(DemoFixtures.vms), view = LayoutMode.List, onAddServer = {}, + onStart = {}, onResume = {}, onPause = {}, onOpenVm = {}, + control = caps.access(KeyAction.ControlVms), + ) + } + assertTrue(rule.hasDescription("Pause Windows 11")) + assertFalse(rule.hasText(vmsNote)) + } + + // ── The note's wording ─────────────────────────────────────────── + + // WHY: the permission named in the note is the one the button is hidden by; they must not drift. + @Test fun noteTexts_nameThePermissionOfTheirKeyAction() { + assertEquals("Needs ${KeyAction.ControlDocker.permission}", ViewOnly.Containers.needs) + assertEquals("Needs ${KeyAction.ControlVms.permission}", ViewOnly.Vms.needs) + assertEquals("Needs ${KeyAction.ControlArray.permission}", ViewOnly.Array.needs) + assertEquals("Needs DOCKER:UPDATE_ANY", ViewOnly.Containers.needs) + assertNotNull(ViewOnly.notifications(Access.Denied, Access.Unknown)) + assertNull(ViewOnly.notifications(Access.Unknown, Access.Unknown)) + assertNull(ViewOnly.notifications(Access.Allowed, Access.Allowed)) + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/ConnectionLabelTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/ConnectionLabelTest.kt index d6b1cc4a..e4840470 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/ConnectionLabelTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/main/ConnectionLabelTest.kt @@ -41,8 +41,11 @@ class ConnectionLabelTest { } // WHY: the same holds when nothing else has loaded yet, and for every reason that is not about the connection. + // A redirect is one of them: the server answered, so "Offline" would send the user to the network. @Test fun failuresThatAreNotTheConnection_leaveThePillAlone() { - listOf(ErrorReason.Forbidden, ErrorReason.ApiTooOld, ErrorReason.ServiceOff, ErrorReason.ServerError).forEach { + listOf( + ErrorReason.Forbidden, ErrorReason.ApiTooOld, ErrorReason.ServiceOff, ErrorReason.Redirected, ErrorReason.ServerError, + ).forEach { assertEquals("$it", "Local", connectionLabel(DomainState.Error("x", reason = it), ConnectionMode.Local)) } } diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/NeedsAttentionWithServicesOffTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/NeedsAttentionWithServicesOffTest.kt new file mode 100644 index 00000000..d9385847 --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/NeedsAttentionWithServicesOffTest.kt @@ -0,0 +1,96 @@ +package io.github.nofuturekid.nova.ui.screens.overview + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.github.nofuturekid.nova.data.model.ArrayInfo +import io.github.nofuturekid.nova.data.model.ArrayState +import io.github.nofuturekid.nova.data.model.Container +import io.github.nofuturekid.nova.data.model.LiveMetrics +import io.github.nofuturekid.nova.data.model.Server +import io.github.nofuturekid.nova.data.model.ServerInfo +import io.github.nofuturekid.nova.data.model.Vm +import io.github.nofuturekid.nova.data.repository.DomainState +import io.github.nofuturekid.nova.data.repository.ErrorReason +import io.github.nofuturekid.nova.ui.theme.ThemeMode +import io.github.nofuturekid.nova.ui.theme.UnraidTheme +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * #356 (reported on 0.1.48): with Docker or the VM manager switched off on the server, or a key + * that may not read them, the Overview never showed the "Needs attention" card, even when the + * array is degraded. The server is reachable in every one of these cases. Cases B and C fail + * on the released tag, because there any Error on a domain hid the card. + */ +@RunWith(AndroidJUnit4::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35], qualifiers = "w432dp-h768dp-night-400dpi") +class NeedsAttentionWithServicesOffTest { + + @get:Rule val rule = createComposeRule() + + private val server = Server("s", "Tower", "tower.example.net", "http://192.0.2.10", "https://tower.example.net") + private val info = ServerInfo("Tower", "1d", "7.2.0", "6.12", "CPU", 4, 8, 4.0, 16.0) + private val degraded = ArrayInfo(ArrayState.Error, totalTb = 8.0, usedTb = 2.0, parity = null, disks = emptyList()) + private val noContainers: DomainState> = DomainState.Content(emptyList()) + private val noVms: DomainState> = DomainState.Content(emptyList()) + + private fun off(reason: ErrorReason, message: String) = DomainState.Error(message, detail = null, reason = reason) + private val vmsOff = off(ErrorReason.ServiceOff, "Failed to retrieve VM domains: VMs are not available") + private val dockerOff = off(ErrorReason.ServiceOff, "Docker socket unavailable.") + + private fun show(docker: DomainState>, vms: DomainState>) { + rule.setContent { + UnraidTheme(themeMode = ThemeMode.Dark) { + OverviewTab( + infoState = DomainState.Content(info), + metricsState = DomainState.Content(LiveMetrics(10.0, 20.0, 5.0, 2.0)), + arrayState = DomainState.Content(degraded), + dockerState = docker, + vmsState = vms, + server = server, + onAddServer = {}, + ) + } + } + } + + private fun assertCardShown() { + rule.onNodeWithText("Needs attention").assertIsDisplayed() + rule.onNodeWithText("Array is degraded").assertIsDisplayed() + } + + // A: control, so B and C cannot pass for a card that never depends on the services. + @Test fun a_degraded_array_shows_the_card_when_every_service_answers() { + show(noContainers, noVms) + assertCardShown() + } + + // B + @Test fun the_card_is_shown_although_VMs_are_off() { + show(noContainers, vmsOff) + assertCardShown() + } + + // C + @Test fun the_card_is_shown_although_Docker_is_off() { + show(dockerOff, noVms) + assertCardShown() + } + + // The "permission the key lacks" half of #356, rendered once for each domain. + @Test fun the_card_is_shown_although_the_key_may_not_read_Docker() { + show(off(ErrorReason.Forbidden, "Forbidden resource"), noVms) + assertCardShown() + } + + @Test fun the_card_is_shown_although_the_key_may_not_read_VMs() { + show(noContainers, off(ErrorReason.Forbidden, "Forbidden resource")) + assertCardShown() + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt new file mode 100644 index 00000000..bb11b8c8 --- /dev/null +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFailureTest.kt @@ -0,0 +1,187 @@ +package io.github.nofuturekid.nova.ui.screens.overview + +import androidx.compose.runtime.Composable +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.ComposeContentTestRule +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.github.nofuturekid.nova.data.demo.DemoFixtures +import io.github.nofuturekid.nova.data.model.ArrayState +import io.github.nofuturekid.nova.data.repository.DomainState +import io.github.nofuturekid.nova.data.repository.ErrorReason +import io.github.nofuturekid.nova.ui.theme.ThemeMode +import io.github.nofuturekid.nova.ui.theme.UnraidTheme +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * The Overview names why it failed, and a switched-off Docker or VM service does not make the + * server look offline (#217, #247). Before, every cause of a total failure read "Can't reach the + * server", and ANY Error on a domain hid the "Needs attention" card although the server answered. + */ +@RunWith(AndroidJUnit4::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35], qualifiers = "w432dp-h768dp-night-400dpi") +class OverviewFailureTest { + + @get:Rule + val rule = createComposeRule() + + private fun error(reason: ErrorReason, message: String = "server text") = + DomainState.Error(message, detail = null, reason = reason) + + private fun show(content: @Composable () -> Unit) = + rule.setContent { UnraidTheme(themeMode = ThemeMode.Dark) { content() } } + + private fun overview( + info: DomainState, + array: DomainState, + docker: DomainState>, + vms: DomainState>, + metrics: DomainState = DomainState.Loading, + ) = show { + OverviewTab( + infoState = info, metricsState = metrics, arrayState = array, dockerState = docker, vmsState = vms, + server = null, onAddServer = {}, + ) + } + + private fun ComposeContentTestRule.exists(text: String) = + onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty() + + // WHY: a rejected key sent the user to check the network. The Overview now gives the tab's own title and next step. + @Test fun everyDomainFailed_showsTheReason_notAlwaysCantReach() { + overview( + info = error(ErrorReason.KeyRejected), array = error(ErrorReason.KeyRejected), + docker = error(ErrorReason.KeyRejected), vms = error(ErrorReason.KeyRejected), + metrics = error(ErrorReason.KeyRejected), + ) + rule.onNodeWithText("The server didn't accept the API key").assertIsDisplayed() + assertFalse(rule.exists("Can't reach the server")) + } + + // WHY: the guard above must be able to fail: an unreachable server still reads "Can't reach the server". + @Test fun everyDomainFailed_unreachableStillSaysSo() { + overview( + info = error(ErrorReason.Unreachable, "Check that the server is online"), array = error(ErrorReason.Unreachable), + docker = error(ErrorReason.Unreachable), vms = error(ErrorReason.Unreachable), + metrics = error(ErrorReason.Unreachable), + ) + rule.onNodeWithText("Can't reach the server").assertIsDisplayed() + } + + // WHY: #357. A redirect is not a connection problem: the server answered. The Overview says what the + // tabs say (the address needs to change, and where to) and does not claim the server is unreachable. + @Test fun everyDomainFailed_redirected_namesTheTarget_notCantReach() { + val message = "The server redirects to https://tower.example" + overview( + info = error(ErrorReason.Redirected, message), array = error(ErrorReason.Redirected, message), + docker = error(ErrorReason.Redirected, message), vms = error(ErrorReason.Redirected, message), + metrics = error(ErrorReason.Redirected, message), + ) + rule.onNodeWithText("The address needs to change").assertIsDisplayed() + rule.onNodeWithText(message).assertIsDisplayed() + assertFalse(rule.exists("Can't reach the server")) + } + + // WHY: #217. Docker and VMs switched off, the server answers and the array has a problem: the + // user must still see "Needs attention". A stopped array is the problem here. + @Test fun dockerAndVmsOff_keepsTheNeedsAttentionCard() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array.copy(state = ArrayState.Stopped)), + docker = error(ErrorReason.ServiceOff), vms = error(ErrorReason.ServiceOff), + ) + assertTrue(rule.exists("Needs attention")) + assertTrue(rule.exists("Array is not started")) + } + + // WHY: the other half, so the test above cannot pass for a card that is always shown: a server + // that is really unreachable has nothing trustworthy to flag. + @Test fun unreachableDomain_hidesTheNeedsAttentionCard() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array.copy(state = ArrayState.Stopped)), + docker = error(ErrorReason.Unreachable), vms = DomainState.Loading, + ) + assertFalse(rule.exists("Needs attention")) + } + + // WHY: a rejected key is a connection problem too (the pill says "Key rejected"): nothing to flag either. + @Test fun rejectedKey_hidesTheNeedsAttentionCard() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array.copy(state = ArrayState.Stopped)), + docker = error(ErrorReason.KeyRejected), vms = DomainState.Loading, + ) + assertFalse(rule.exists("Needs attention")) + } + + // WHY: the offline rule is the pure heart of the above; pin it for every reason. + @Test fun offlineIsDecidedByTheReason() { + ErrorReason.entries.forEach { reason -> + assertEquals( + reason.toString(), + reason == ErrorReason.Unreachable || reason == ErrorReason.KeyRejected, + isOffline(DomainState.Content(1), error(reason)), + ) + } + assertFalse("no error, not offline", isOffline(DomainState.Content(1), DomainState.Loading)) + } + + // WHY: when the server is unreachable the other domains fail BECAUSE of it; show that cause, not + // whichever domain happens to come first. + @Test fun failureShown_prefersAConnectionProblem() { + val picked = overviewFailure(error(ErrorReason.ServiceOff), error(ErrorReason.KeyRejected), error(ErrorReason.ServerError)) + assertEquals(ErrorReason.KeyRejected, picked!!.reason) + assertEquals( + ErrorReason.ServiceOff, + overviewFailure(DomainState.Loading, error(ErrorReason.ServiceOff), error(ErrorReason.ServerError))!!.reason, + ) + assertNull(overviewFailure(DomainState.Loading, DomainState.Content(1))) + } + + // WHY: #356. With Docker off and the VMs not loaded yet, the cards must not claim "0 running · all + // healthy" / "0 configured": the app does not know, and says so with the dash. + @Test fun unknownDockerAndVms_showDashes_notZero() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array), + docker = error(ErrorReason.ServiceOff), vms = DomainState.Loading, + ) + assertFalse(rule.exists("all healthy")) + assertFalse(rule.exists("0 configured")) + assertTrue(rule.onAllNodesWithText(PLACEHOLDER).fetchSemanticsNodes().size >= 4) + } + + // WHY: the same for a key that may not read the domains: unknown, not zero. + @Test fun forbiddenDockerAndVms_showDashes_notZero() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array), + docker = error(ErrorReason.Forbidden), vms = error(ErrorReason.Forbidden), + ) + assertFalse(rule.exists("all healthy")) + assertFalse(rule.exists("0 configured")) + } + + // WHY: the guard above must be able to fail: a server that really answers with nothing keeps "0". + @Test fun emptyDockerAndVms_stillReadZero() { + overview( + info = DomainState.Content(DemoFixtures.info), + array = DomainState.Content(DemoFixtures.array), + docker = DomainState.Content(emptyList()), vms = DomainState.Content(emptyList()), + ) + assertTrue(rule.exists("all healthy")) + assertTrue(rule.exists("0 configured")) + } +} diff --git a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFiguresTest.kt b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFiguresTest.kt index 9076340e..687342a7 100644 --- a/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFiguresTest.kt +++ b/app/src/test/kotlin/io/github/nofuturekid/nova/ui/screens/overview/OverviewFiguresTest.kt @@ -1,7 +1,10 @@ package io.github.nofuturekid.nova.ui.screens.overview import io.github.nofuturekid.nova.data.model.ArrayInfo +import io.github.nofuturekid.nova.data.demo.DemoFixtures import io.github.nofuturekid.nova.data.model.ArrayState +import io.github.nofuturekid.nova.data.model.ContainerStatus +import io.github.nofuturekid.nova.data.model.VmState import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals @@ -140,4 +143,30 @@ class OverviewFiguresTest { assertEquals(0f, next.last()) assertEquals(SERIES_LENGTH, next.size) } + + // ── Containers and Virtual machines cards ─────────────────────── + + // WHY: #356. Unknown is not an empty server: "0 running · all healthy" would tell the user + // everything is fine while the app has no idea. + @Test fun unknown_containers_and_vms_show_the_placeholder() { + assertEquals(CountFigures(PLACEHOLDER, PLACEHOLDER), containerFigures(null)) + assertEquals(CountFigures(PLACEHOLDER, PLACEHOLDER), vmFigures(null)) + } + + // WHY: the other half, so the placeholder cannot pass for "always dash": a real empty list stays a real 0. + @Test fun empty_lists_stay_zero() { + assertEquals(CountFigures("0", "all healthy"), containerFigures(emptyList())) + assertEquals(CountFigures("0", "0 configured"), vmFigures(emptyList())) + } + + // WHY: the counts themselves must survive the move out of the card. + @Test fun counts_follow_the_status() { + fun c(status: ContainerStatus) = DemoFixtures.containers.first().copy(status = status) + assertEquals( + CountFigures("2", "1 stopped · 1 paused"), + containerFigures(listOf(c(ContainerStatus.Running), c(ContainerStatus.Running), c(ContainerStatus.Exited), c(ContainerStatus.Paused))), + ) + fun v(state: VmState) = DemoFixtures.vms.first().copy(state = state) + assertEquals(CountFigures("1", "3 configured"), vmFigures(listOf(v(VmState.Running), v(VmState.Stopped), v(VmState.Paused)))) + } } diff --git a/docs/adr/0051-no-redirects-for-keyed-requests.md b/docs/adr/0051-no-redirects-for-keyed-requests.md new file mode 100644 index 00000000..58564bfa --- /dev/null +++ b/docs/adr/0051-no-redirects-for-keyed-requests.md @@ -0,0 +1,47 @@ +# ADR-0051: Never follow a redirect with the API key + +- **Status**: Accepted (2026-11-13) +- **Date**: 2026-11-13 +- **Tags**: security, data, ui + +## Context + +Every request NOVA sends to an Unraid server carries the API key: the `x-api-key` header of the HTTP clients (`ApolloClientFactory.build` and `buildLongRunning`, added by an application interceptor) and the `connection_init` payload of the WebSocket client (`buildWs`), which is sent after the handshake. The background client (`buildBackground`, ADR-0048) already follows no redirect. The three foreground clients kept OkHttp's defaults (`followRedirects` and `followSslRedirects` both true). OkHttp strips only `Authorization` when it follows a redirect to another host, so a 3xx answer re-sent the key to whatever `Location` named: another host, or plain http after the user entered https. For the WebSocket the handshake itself was followed, so the second host completed it and then received the key. `KeyedClientRedirectTest` shows this on the unchanged clients: the key reaches a second server and the WebSocket peer gets a connection (four of its five tests fail without the change). + +What real Unraid servers send (read from `unraid/webgui`, `etc/rc.d/rc.nginx` at commit `99e39027fb` of 2026-11-13; the same lines are in the fixture of `unraid/api`): + +- SSL setting **No**: no redirect. +- SSL **Yes**: a server block on the http port answers every request with `return 302 https://$host:$PORTSSL$request_uri;` (`redirect host`). Same host name, https, port always spelled out. +- SSL **Strict** (`USE_SSL=auto`, with a myunraid.net certificate): `return 302 https://$(fqdn $ADDR)$PORTSSL_URL$request_uri;` (`redirect fqdn`), the host name being `lan-ip.hash.myunraid.net`. A different host name from the one the user typed, even for `http://192.168.1.100` or `http://tower.local`. A Tailscale name gets the same kind of `302` to its own https name. +- All of these are `302`, at server level, so they answer `POST /graphql` too. The `location /graphql` block itself has no redirect; the API answers on a unix socket behind nginx. +- OkHttp turns a followed `301`/`302`/`303` POST into a GET without a body (`RetryAndFollowUpInterceptor`; read from its documented behaviour, not run here), so following Unraid's own redirect could never have produced a working query: the user got a failure on the redirected GET, with no explanation. + +So the realistic case is a user who typed an http address or a bare IP; the redirect is the server telling them the address to use. + +## Decision + +**No client that carries the API key follows a redirect. A redirect becomes a failure reason of its own that names the target.** + +1. **Rule.** The key is never sent to a host other than the one the user entered, and never over http when the user entered https. The simplest way to guarantee both is that no redirect is followed at all: `followRedirects(false)` and `followSslRedirects(false)` on the base and the long-running client; the WebSocket client is derived from the base client and inherits them, which ends the handshake at the 3xx. The background client keeps its own explicit settings. +2. **Not "follow same-host http-to-https upgrades".** That was the alternative. It would not help: the first request already sent the key over http, to the host the user entered, before the redirect; Unraid's redirect is a 302 that OkHttp would turn into a body-less GET; and following needs a custom interceptor that re-sends the POST and compares hosts, which is more code to get wrong in the code path that guards the key. Telling the user the address to enter costs one sentence and fixes the next request too. +3. **Reason.** `ErrorReason.Redirected` (not a connection problem, so the top-bar pill does not say Offline: the server answered). `ApolloException.redirectMessage()` in `ResponseClassifier.kt` recognises the statuses OkHttp followed (300, 301, 302, 303, 307, 308) and builds `The server redirects to . Edit the server and enter that address.` from the `Location` header. Only the origin is shown: the path is of no use to the user, a query can carry tokens, and `user:password@` is dropped. A missing, relative or non-http `Location` gets the same advice without a target. Tabs show it as "The address needs to change" with that sentence; `DomainState.Error.detail` keeps the raw text. +4. **One text everywhere.** `classifyResponse` returns the sentence for a redirect, so the Add server sheet's **Test** (`testConnection`) shows it without a change of its own, and `checkActionResponse` gives it (lower-cased) to the snackbar of a failed action. `classifyErrorReason` and `toQueryError` give tabs the reason. The WebSocket streams keep their generic error text; the polling tabs and **Test** carry the reason. +5. **Unchanged.** A server that does not redirect, http-only servers (SSL No) and the background check behave as before; certificate handling is not touched. + +## Consequences + +- **Positive.** The key cannot be moved by a redirect, whoever sends it (a misconfigured proxy, a changed DNS answer, a captive portal). A user who typed the wrong scheme is told the address instead of seeing an unexplained failure. +- **Negative / trade-offs.** A setup that relied on NOVA following a redirect (a reverse proxy that redirects `/graphql` to another path or host) now fails with the new message and has to be entered at its final address. Unraid's own redirects never worked for POST queries, so no working setup of that kind is known. An http-to-https redirect cannot be followed even when it is harmless; the user enters the https address once. +- **Not covered.** The https-to-http direction cannot be staged in a unit test without a TLS peer; a test pins the two OkHttp switches instead. Certificate handling and the first request over plain http (the user's own choice) are unchanged. +- **Trigger to revisit.** If a real, common Unraid or proxy setup answers the GraphQL POST with a redirect that must be followed (for example a `308` from a documented proxy), follow only a same-host, same-or-upgrading-scheme `307`/`308` in an interceptor that drops the key for any other target. + +## Alternatives considered + +- **Follow only same-host http-to-https upgrades.** Rejected in decision 2. +- **Keep following and strip `x-api-key` on a host or scheme change** (an OkHttp network interceptor). It keeps OkHttp's redirect logic and drops the key, but the follow-up request then fails as unauthenticated with a misleading "key rejected", and the first hop still leaked. +- **Do nothing for the WebSocket.** Rejected: the handshake redirect is the worse leak because the key follows in the payload. + +## References + +- Issue hellwand/nova#354; ADR-0048 (the background client that started this), ADR-0041 (host and SSL entry), ADR-0042 (WebSocket transport), ADR-0047. +- Upstream: `unraid/webgui` `etc/rc.d/rc.nginx` (`redirect()` at the top, the `USE_SSL` branches in `build_servers`, `location /graphql` in `build_locations`). diff --git a/docs/adr/README.md b/docs/adr/README.md index 150491f7..a65f1de5 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -85,3 +85,4 @@ ADRs live under `docs/` so the CI docs-only bypass applies — pure-ADR PRs comp | [0048](./0048-opt-in-background-alert-checks.md) | Opt-in background alert checks (amends ADR-0017) | Accepted | | [0049](./0049-google-play-third-distribution-channel.md) | Google Play as a third distribution channel | Accepted | | [0050](./0050-demo-mode.md) | A demo mode with fictional data | Proposed | +| [0051](./0051-no-redirects-for-keyed-requests.md) | Never follow a redirect with the API key | Accepted |