luminate/Tests/LuminateServicesTests/JellyfinClientAuthTests.swift

338 lines
12 KiB
Swift

//
// JellyfinClientAuthTests.swift
//
// Copyright 2026 Brendan Szymanski <hello@bscubed.dev>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
import HTTPTypes
import LuminateAPI
import LuminateCore
import OpenAPIRuntime
import Testing
@testable import LuminateServices
private struct PublicUsersTransport: ClientTransport {
let responseBody: String
func send(
_ request: HTTPRequest,
body: HTTPBody?,
baseURL: URL,
operationID: String
) async throws -> (HTTPResponse, HTTPBody?) {
let response = HTTPResponse(
status: .ok,
headerFields: [.contentType: "application/json"]
)
return (response, HTTPBody(responseBody))
}
}
/// Covers sign-in: argument validation, payload mapping, and token adoption.
@Suite struct JellyfinClientAuthTests {
/// Builds a client wired to a double, pointed at a URL that is never dialled.
///
/// - Parameter api: The stubbed API.
/// - Returns: A client that routes every call to `api`.
private func makeClient(_ api: MockJellyfinAPI) -> JellyfinClient {
JellyfinClient(
configuration: JellyfinClientConfiguration(
serverURL: URL(string: "http://localhost")!,
deviceName: "test-device",
deviceID: "test-device-id"
),
api: api
)
}
/// Builds a client that decodes a raw public-user response without opening a network connection.
///
/// - Parameter responseBody: The JSON body returned by the transport double.
/// - Returns: A client configured with the production OpenAPI transport and date transcoder.
private func makeDecodingClient(responseBody: String) -> JellyfinClient {
JellyfinClient(
configuration: JellyfinClientConfiguration(
serverURL: URL(string: "http://localhost")!,
deviceName: "test-device",
deviceID: "test-device-id"
),
makeTransport: { PublicUsersTransport(responseBody: responseBody) }
)
}
@Test("Public users decode Jellyfin dates with seven fractional digits")
func publicUsersDecodeFractionalDates() async throws {
let lastLoginDate = "2025-05-07T17:36:46.1130892Z"
let responseBody = """
[
{
"Name": "ashley",
"Id": "user-1",
"LastLoginDate": "\(lastLoginDate)",
"LastActivityDate": "2026-07-16T05:04:36.1878329Z"
}
]
"""
let client = makeDecodingClient(responseBody: responseBody)
let users = try await client.publicUsers()
let expectedDate = try ISO8601DateTranscoder.iso8601WithFractionalSeconds.decode(lastLoginDate)
#expect(users.count == 1)
#expect(users[0].id == "user-1")
#expect(users[0].name == "ashley")
#expect(users[0].lastLoginDate == expectedDate)
}
@Test("Public users reject malformed date strings")
func publicUsersRejectMalformedDates() async {
let responseBody = """
[
{
"Name": "ashley",
"Id": "user-1",
"LastLoginDate": "not-a-date"
}
]
"""
let client = makeDecodingClient(responseBody: responseBody)
do {
_ = try await client.publicUsers()
Issue.record("Expected malformed public-user date to fail decoding")
} catch let error as ClientError {
#expect(error.underlyingError is DecodingError)
} catch {
Issue.record("Expected OpenAPI ClientError, got \(error)")
}
}
@Test("Fetching the current user maps the signed-in account")
func currentUserMapsAccount() async throws {
var api = MockJellyfinAPI()
api.getCurrentUserOutput = .ok(
.init(body: .json(Components.Schemas.UserDto(name: "echo", id: "u1")))
)
let client = makeClient(api)
let user = try await client.currentUser()
#expect(user.id == "u1")
#expect(user.name == "echo")
}
@Test("A rejected token surfaces as unauthorized")
func currentUserRejectedTokenIsUnauthorized() async {
var api = MockJellyfinAPI()
api.getCurrentUserOutput = .unauthorized(.init())
let client = makeClient(api)
await #expect(throws: JellyfinClientError.unauthorized) {
_ = try await client.currentUser()
}
}
@Test("A successful sign-in maps the result and adopts the token")
func signInAdoptsToken() async throws {
var api = MockJellyfinAPI()
api.authenticateUserByNameOutput = .ok(
.init(
body: .json(
Components.Schemas.AuthenticationResult(
user: .init(value1: Components.Schemas.UserDto(name: "echo", id: "u1", hasPassword: true)),
accessToken: "tok",
serverId: "srv"
)
)
)
)
let client = makeClient(api)
let result = try await client.authenticate(username: "echo", password: "hunter2")
#expect(result.accessToken == "tok")
#expect(result.serverID == "srv")
#expect(result.user?.name == "echo")
#expect(result.user?.id == "u1")
#expect(await client.accessToken == "tok")
#expect(await client.isAuthenticated)
}
@Test("A success with no token is a failure, not an unauthenticated success")
func missingTokenThrows() async {
var api = MockJellyfinAPI()
api.authenticateUserByNameOutput = .ok(
.init(body: .json(Components.Schemas.AuthenticationResult(accessToken: nil)))
)
let client = makeClient(api)
await #expect(throws: JellyfinClientError.missingPayload(operation: "AuthenticateUserByName")) {
_ = try await client.authenticate(username: "echo", password: "hunter2")
}
#expect(await client.isAuthenticated == false)
}
@Test("An empty username is rejected before any request is sent")
func emptyUsernameRejected() async {
let client = makeClient(MockJellyfinAPI())
await #expect(throws: JellyfinClientError.invalidArgument(name: "username")) {
_ = try await client.authenticate(username: "", password: "hunter2")
}
}
@Test("An empty Quick Connect secret is rejected before any request is sent")
func emptySecretRejected() async {
let client = makeClient(MockJellyfinAPI())
await #expect(throws: JellyfinClientError.invalidArgument(name: "secret")) {
_ = try await client.quickConnectState(secret: "")
}
}
@Test("Quick Connect enabled reports the stubbed flag")
func quickConnectEnabledReportsFlag() async throws {
var api = MockJellyfinAPI()
api.getQuickConnectEnabledOutput = .ok(.init(body: .json(true)))
let client = makeClient(api)
let enabled = try await client.quickConnectEnabled()
#expect(enabled == true)
}
@Test("Initiating Quick Connect maps the pairing state")
func initiateQuickConnectMapsState() async throws {
var api = MockJellyfinAPI()
api.initiateQuickConnectOutput = .ok(
.init(
body: .json(
Components.Schemas.QuickConnectResult(
authenticated: false,
secret: "sec1",
code: "ABC123"
)
)
)
)
let client = makeClient(api)
let state = try await client.initiateQuickConnect()
#expect(state.code == "ABC123")
#expect(state.secret == "sec1")
#expect(state.authenticated == false)
}
@Test("Polling an approved Quick Connect request reports success")
func quickConnectStateReportsApproval() async throws {
var api = MockJellyfinAPI()
api.getQuickConnectStateOutput = .ok(
.init(
body: .json(
Components.Schemas.QuickConnectResult(authenticated: true, secret: "sec1")
)
)
)
let client = makeClient(api)
let state = try await client.quickConnectState(secret: "sec1")
#expect(state.authenticated == true)
}
@Test("Redeeming Quick Connect adopts the issued token")
func authenticateWithQuickConnectAdoptsToken() async throws {
var api = MockJellyfinAPI()
api.authenticateWithQuickConnectOutput = .ok(
.init(
body: .json(
Components.Schemas.AuthenticationResult(
user: .init(value1: Components.Schemas.UserDto(name: "echo", id: "u1", hasPassword: true)),
accessToken: "qc-tok",
serverId: "srv"
)
)
)
)
let client = makeClient(api)
let result = try await client.authenticateWithQuickConnect(secret: "sec1")
#expect(result.accessToken == "qc-tok")
#expect(await client.accessToken == "qc-tok")
#expect(await client.isAuthenticated)
}
@Test("Updating a password records every supplied field")
func updatePasswordRecordsFields() async throws {
var api = MockJellyfinAPI()
api.updateUserPasswordOutput = .noContent
let client = makeClient(api)
try await client.updateUserPassword(
userID: "u1",
currentPassword: "old",
currentPIN: "1234",
newPassword: "new",
resetPassword: false
)
let input = try #require(api.inputs.last("UpdateUserPassword", as: Operations.UpdateUserPassword.Input.self))
#expect(input.query.userId == "u1")
guard case .json(let payload) = input.body else {
Issue.record("Expected a JSON update-password body")
return
}
#expect(payload.value1.currentPassword == "old")
#expect(payload.value1.currentPw == "1234")
#expect(payload.value1.newPw == "new")
#expect(payload.value1.resetPassword == false)
}
@Test("The reduced-arity password overload sends nil PIN, userID, and reset flag")
func reducedArityPasswordOverloadSendsNils() async throws {
var api = MockJellyfinAPI()
api.updateUserPasswordOutput = .noContent
let client = makeClient(api)
try await client.updateUserPassword(currentPassword: "old", newPassword: "new")
let input = try #require(api.inputs.last("UpdateUserPassword", as: Operations.UpdateUserPassword.Input.self))
#expect(input.query.userId == nil)
guard case .json(let payload) = input.body else {
Issue.record("Expected a JSON update-password body")
return
}
#expect(payload.value1.currentPw == nil)
#expect(payload.value1.resetPassword == nil)
}
@Test("Clearing the token signs the client out")
func clearingTokenSignsOut() async {
let client = makeClient(MockJellyfinAPI())
await client.setAccessToken("tok")
#expect(await client.isAuthenticated)
await client.setAccessToken("")
#expect(await client.accessToken == nil)
#expect(await client.isAuthenticated == false)
}
}