v1.1.0 — Account-Lifecycle in ManaCore
Phase 1 aus dem Native-Auth-Vollausbau-Plan (Option A, siehe mana/docs/MANA_SWIFT.md). 7 neue AuthClient-Methoden für die Account-Reise: register, forgotPassword, resetPassword, resendVerification, changeEmail, changePassword, deleteAccount. AuthError jetzt mit 19 präzisen Cases gespiegelt aus AuthErrorCode in mana-auth/lib/auth-errors.ts, plus AuthError.classify() als public Helper und Equatable-Conformance. AuthClient.lastError ergänzt — strukturierter Fehler für ManaAuthUI das den .emailNotVerified-Gate programmatisch braucht. signIn und refreshAccessToken auf neue Klassifikation umgestellt. Breaking: AuthError.serverError hat zusätzliches code:-Argument. Apps (cards-native, memoro-native) sind bereits angepasst. 38/38 Tests grün (26 neu): AuthErrorClassifyTests deckt jeden ErrorCode + Status-Heuristik + Retry-After ab, AuthClientAccountTests deckt jede neue Methode via URLProtocol-Mock ab. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
74aee8d47f
commit
716509e10e
6 changed files with 1226 additions and 36 deletions
320
Tests/ManaCoreTests/AuthClientAccountTests.swift
Normal file
320
Tests/ManaCoreTests/AuthClientAccountTests.swift
Normal file
|
|
@ -0,0 +1,320 @@
|
|||
import Foundation
|
||||
import Testing
|
||||
@testable import ManaCore
|
||||
|
||||
@Suite("AuthClient+Account", .serialized)
|
||||
@MainActor
|
||||
struct AuthClientAccountTests {
|
||||
// MARK: - Fixtures
|
||||
|
||||
private static func makeClient() -> (AuthClient, URLSession) {
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.protocolClasses = [MockURLProtocol.self]
|
||||
let session = URLSession(configuration: configuration)
|
||||
|
||||
let config = DefaultManaAppConfig(
|
||||
authBaseURL: URL(string: "https://auth.test")!,
|
||||
keychainService: "ev.mana.test.\(UUID().uuidString)",
|
||||
keychainAccessGroup: nil
|
||||
)
|
||||
return (AuthClient(config: config, session: session), session)
|
||||
}
|
||||
|
||||
private func recordedBody(_ request: URLRequest) -> [String: Any] {
|
||||
// URLSession verschiebt den Body in den BodyStream wenn er nicht
|
||||
// klein-genug ist — ephemeral-Session lässt ihn als httpBody.
|
||||
guard let body = request.httpBody ?? request.bodyStreamData(),
|
||||
let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any]
|
||||
else { return [:] }
|
||||
return json
|
||||
}
|
||||
|
||||
// MARK: - register
|
||||
|
||||
@Test("register schickt POST /api/v1/auth/register mit JSON-Body")
|
||||
func registerSendsCorrectRequest() async throws {
|
||||
let (client, _) = Self.makeClient()
|
||||
MockURLProtocol.handler = { request in
|
||||
#expect(request.httpMethod == "POST")
|
||||
#expect(request.url?.path == "/api/v1/auth/register")
|
||||
#expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json")
|
||||
return (200, Data(#"{"user":{"id":"u1","email":"new@x.de"}}"#.utf8))
|
||||
}
|
||||
|
||||
try await client.register(
|
||||
email: "new@x.de",
|
||||
password: "Aa-123456789",
|
||||
name: "Neu",
|
||||
sourceAppUrl: URL(string: "https://cardecky.mana.how/auth/verify")
|
||||
)
|
||||
// Mit requireEmailVerification:true gibt es noch keine Session.
|
||||
if case .signedIn = client.status {
|
||||
Issue.record("Expected not-signed-in after register without tokens")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("register mit Token-Antwort führt direkt zu signedIn")
|
||||
func registerWithTokensSignsIn() async throws {
|
||||
let (client, _) = Self.makeClient()
|
||||
// gültiger HS256-Header.payload (exp 2_000_000_000).sig — JWT.expiry()
|
||||
// läuft danach nicht in den Refresh-Pfad.
|
||||
let access =
|
||||
"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||
let refresh = "refresh-token-value"
|
||||
MockURLProtocol.handler = { _ in
|
||||
(200, Data(#"""
|
||||
{"user":{"id":"u1","email":"new@x.de"},"accessToken":"\#(access)","refreshToken":"\#(refresh)"}
|
||||
"""#.utf8))
|
||||
}
|
||||
|
||||
try await client.register(email: "new@x.de", password: "Aa-123456789")
|
||||
#expect(client.status == .signedIn(email: "new@x.de"))
|
||||
}
|
||||
|
||||
@Test("register mit existierender Email wirft emailAlreadyRegistered")
|
||||
func registerEmailAlreadyRegistered() async {
|
||||
let (client, _) = Self.makeClient()
|
||||
MockURLProtocol.handler = { _ in
|
||||
(409, Data(#"{"error":"EMAIL_ALREADY_REGISTERED","status":409}"#.utf8))
|
||||
}
|
||||
|
||||
await #expect(throws: AuthError.emailAlreadyRegistered) {
|
||||
try await client.register(email: "old@x.de", password: "Aa-123456789")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("register mit leerer Email wirft validation ohne Server-Call")
|
||||
func registerValidatesEmptyEmail() async {
|
||||
let (client, _) = Self.makeClient()
|
||||
MockURLProtocol.handler = { _ in
|
||||
Issue.record("Server darf nicht aufgerufen werden")
|
||||
return (500, Data())
|
||||
}
|
||||
|
||||
await #expect(throws: (any Error).self) {
|
||||
try await client.register(email: " ", password: "Aa-123456789")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - forgotPassword
|
||||
|
||||
@Test("forgotPassword schickt email + redirectTo")
|
||||
func forgotPasswordPayload() async throws {
|
||||
let (client, _) = Self.makeClient()
|
||||
let capturedURL = MockURLProtocol.Capture()
|
||||
MockURLProtocol.handler = { request in
|
||||
capturedURL.store(request)
|
||||
return (200, Data(#"{"success":true}"#.utf8))
|
||||
}
|
||||
|
||||
try await client.forgotPassword(
|
||||
email: "user@x.de",
|
||||
resetUniversalLink: URL(string: "https://cardecky.mana.how/auth/reset")!
|
||||
)
|
||||
let captured = try #require(capturedURL.request)
|
||||
let json = recordedBody(captured)
|
||||
#expect(json["email"] as? String == "user@x.de")
|
||||
#expect(json["redirectTo"] as? String == "https://cardecky.mana.how/auth/reset")
|
||||
#expect(captured.url?.path == "/api/v1/auth/forgot-password")
|
||||
}
|
||||
|
||||
// MARK: - resetPassword
|
||||
|
||||
@Test("resetPassword schickt token + newPassword")
|
||||
func resetPasswordPayload() async throws {
|
||||
let (client, _) = Self.makeClient()
|
||||
let captured = MockURLProtocol.Capture()
|
||||
MockURLProtocol.handler = { request in
|
||||
captured.store(request)
|
||||
return (200, Data(#"{"success":true}"#.utf8))
|
||||
}
|
||||
|
||||
try await client.resetPassword(token: "tok123", newPassword: "Neu-987654321")
|
||||
let request = try #require(captured.request)
|
||||
let json = recordedBody(request)
|
||||
#expect(json["token"] as? String == "tok123")
|
||||
#expect(json["newPassword"] as? String == "Neu-987654321")
|
||||
#expect(request.url?.path == "/api/v1/auth/reset-password")
|
||||
}
|
||||
|
||||
@Test("resetPassword mit abgelaufenem Token wirft tokenExpired")
|
||||
func resetPasswordTokenExpired() async {
|
||||
let (client, _) = Self.makeClient()
|
||||
MockURLProtocol.handler = { _ in
|
||||
(400, Data(#"{"error":"TOKEN_EXPIRED","status":400}"#.utf8))
|
||||
}
|
||||
|
||||
await #expect(throws: AuthError.tokenExpired) {
|
||||
try await client.resetPassword(token: "old", newPassword: "Neu-987654321")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - resendVerification
|
||||
|
||||
@Test("resendVerification schickt email + sourceAppUrl")
|
||||
func resendVerificationPayload() async throws {
|
||||
let (client, _) = Self.makeClient()
|
||||
let captured = MockURLProtocol.Capture()
|
||||
MockURLProtocol.handler = { request in
|
||||
captured.store(request)
|
||||
return (200, Data(#"{"success":true}"#.utf8))
|
||||
}
|
||||
|
||||
try await client.resendVerification(
|
||||
email: "user@x.de",
|
||||
sourceAppUrl: URL(string: "https://cardecky.mana.how/auth/verify")
|
||||
)
|
||||
let request = try #require(captured.request)
|
||||
let json = recordedBody(request)
|
||||
#expect(json["email"] as? String == "user@x.de")
|
||||
#expect(json["sourceAppUrl"] as? String == "https://cardecky.mana.how/auth/verify")
|
||||
}
|
||||
|
||||
@Test("resendVerification mit Rate-Limit liefert retryAfter")
|
||||
func resendVerificationRateLimited() async {
|
||||
let (client, _) = Self.makeClient()
|
||||
MockURLProtocol.handler = { _ in
|
||||
(
|
||||
429,
|
||||
Data(#"{"error":"RATE_LIMITED","retryAfterSec":42,"status":429}"#.utf8),
|
||||
["Retry-After": "42"]
|
||||
)
|
||||
}
|
||||
|
||||
do {
|
||||
try await client.resendVerification(email: "user@x.de")
|
||||
Issue.record("Expected throw")
|
||||
} catch let AuthError.rateLimited(retryAfter) {
|
||||
#expect(retryAfter == 42)
|
||||
} catch {
|
||||
Issue.record("Unexpected error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Authenticated calls (require signed-in state)
|
||||
|
||||
@Test("changeEmail ohne Login wirft notSignedIn")
|
||||
func changeEmailRequiresSession() async {
|
||||
let (client, _) = Self.makeClient()
|
||||
await #expect(throws: AuthError.notSignedIn) {
|
||||
try await client.changeEmail(newEmail: "neu@x.de")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("changePassword schickt Bearer-Header wenn eingeloggt")
|
||||
func changePasswordSendsBearer() async throws {
|
||||
let (client, _) = Self.makeClient()
|
||||
// Mock-Token im Keychain ablegen via persistSession-Helper.
|
||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||
try client.persistSession(email: "u@x.de", accessToken: access, refreshToken: "r")
|
||||
|
||||
let captured = MockURLProtocol.Capture()
|
||||
MockURLProtocol.handler = { request in
|
||||
captured.store(request)
|
||||
return (200, Data(#"{"success":true}"#.utf8))
|
||||
}
|
||||
|
||||
try await client.changePassword(currentPassword: "alt", newPassword: "neu")
|
||||
let request = try #require(captured.request)
|
||||
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer \(access)")
|
||||
#expect(request.url?.path == "/api/v1/auth/change-password")
|
||||
}
|
||||
|
||||
@Test("deleteAccount wiped Session bei Erfolg")
|
||||
func deleteAccountClearsSession() async throws {
|
||||
let (client, _) = Self.makeClient()
|
||||
let access = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1MSIsImV4cCI6MjAwMDAwMDAwMH0.sig"
|
||||
try client.persistSession(email: "u@x.de", accessToken: access, refreshToken: "r")
|
||||
#expect(client.status == .signedIn(email: "u@x.de"))
|
||||
|
||||
MockURLProtocol.handler = { request in
|
||||
#expect(request.httpMethod == "DELETE")
|
||||
return (200, Data(#"{"success":true}"#.utf8))
|
||||
}
|
||||
try await client.deleteAccount(password: "pw")
|
||||
#expect(client.status == .signedOut)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - URLProtocol Mock
|
||||
|
||||
final class MockURLProtocol: URLProtocol, @unchecked Sendable {
|
||||
/// Antwort-Tuple: (status, body) oder (status, body, headers).
|
||||
typealias Response = (status: Int, body: Data, headers: [String: String])
|
||||
typealias Handler = @Sendable (URLRequest) -> Any // (Int, Data) | (Int, Data, [String:String])
|
||||
|
||||
nonisolated(unsafe) static var handler: Handler?
|
||||
|
||||
/// Thread-safer Capture-Container — Tests können den Request darin
|
||||
/// festhalten und nach dem await aus dem Test-Body lesen.
|
||||
final class Capture: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var stored: URLRequest?
|
||||
|
||||
func store(_ r: URLRequest) {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stored = r
|
||||
}
|
||||
|
||||
var request: URLRequest? {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
return stored
|
||||
}
|
||||
}
|
||||
|
||||
override class func canInit(with request: URLRequest) -> Bool { true }
|
||||
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
||||
override func stopLoading() {}
|
||||
|
||||
override func startLoading() {
|
||||
guard let handler = MockURLProtocol.handler else {
|
||||
client?.urlProtocol(
|
||||
self,
|
||||
didFailWithError: URLError(.unknown)
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
let result = handler(request)
|
||||
let status: Int
|
||||
let body: Data
|
||||
let headers: [String: String]
|
||||
if let tuple = result as? (Int, Data, [String: String]) {
|
||||
status = tuple.0; body = tuple.1; headers = tuple.2
|
||||
} else if let tuple = result as? (Int, Data) {
|
||||
status = tuple.0; body = tuple.1; headers = [:]
|
||||
} else {
|
||||
client?.urlProtocol(self, didFailWithError: URLError(.unknown))
|
||||
return
|
||||
}
|
||||
|
||||
let response = HTTPURLResponse(
|
||||
url: request.url!,
|
||||
statusCode: status,
|
||||
httpVersion: "HTTP/1.1",
|
||||
headerFields: headers
|
||||
)!
|
||||
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
||||
client?.urlProtocol(self, didLoad: body)
|
||||
client?.urlProtocolDidFinishLoading(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension URLRequest {
|
||||
/// Liest httpBodyStream in einen Data. URLSession ephemeral-Session
|
||||
/// nutzt manchmal Streams statt httpBody.
|
||||
func bodyStreamData() -> Data? {
|
||||
guard let stream = httpBodyStream else { return nil }
|
||||
stream.open(); defer { stream.close() }
|
||||
var data = Data()
|
||||
let bufferSize = 1024
|
||||
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
|
||||
defer { buffer.deallocate() }
|
||||
while stream.hasBytesAvailable {
|
||||
let read = stream.read(buffer, maxLength: bufferSize)
|
||||
if read <= 0 { break }
|
||||
data.append(buffer, count: read)
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
167
Tests/ManaCoreTests/AuthErrorClassifyTests.swift
Normal file
167
Tests/ManaCoreTests/AuthErrorClassifyTests.swift
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
import Foundation
|
||||
import Testing
|
||||
@testable import ManaCore
|
||||
|
||||
@Suite("AuthError.classify")
|
||||
struct AuthErrorClassifyTests {
|
||||
private func body(_ json: String) -> Data {
|
||||
Data(json.utf8)
|
||||
}
|
||||
|
||||
@Test("Mapped INVALID_CREDENTIALS auf invalidCredentials")
|
||||
func mapsInvalidCredentials() {
|
||||
let err = AuthError.classify(
|
||||
status: 401,
|
||||
data: body(#"{"error":"INVALID_CREDENTIALS","message":"Email oder Passwort falsch","status":401}"#)
|
||||
)
|
||||
#expect(err == .invalidCredentials)
|
||||
}
|
||||
|
||||
@Test("Mapped EMAIL_NOT_VERIFIED auf emailNotVerified")
|
||||
func mapsEmailNotVerified() {
|
||||
let err = AuthError.classify(
|
||||
status: 403,
|
||||
data: body(#"{"error":"EMAIL_NOT_VERIFIED","message":"Bitte bestätige…","status":403}"#)
|
||||
)
|
||||
#expect(err == .emailNotVerified)
|
||||
}
|
||||
|
||||
@Test("Mapped EMAIL_ALREADY_REGISTERED auf emailAlreadyRegistered")
|
||||
func mapsEmailAlreadyRegistered() {
|
||||
let err = AuthError.classify(
|
||||
status: 409,
|
||||
data: body(#"{"error":"EMAIL_ALREADY_REGISTERED","status":409}"#)
|
||||
)
|
||||
#expect(err == .emailAlreadyRegistered)
|
||||
}
|
||||
|
||||
@Test("WEAK_PASSWORD trägt Server-Message")
|
||||
func weakPasswordCarriesMessage() {
|
||||
let err = AuthError.classify(
|
||||
status: 400,
|
||||
data: body(#"{"error":"WEAK_PASSWORD","message":"Mindestens 8 Zeichen","status":400}"#)
|
||||
)
|
||||
if case let .weakPassword(message) = err {
|
||||
#expect(message == "Mindestens 8 Zeichen")
|
||||
} else {
|
||||
Issue.record("Expected .weakPassword, got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("RATE_LIMITED nutzt retryAfterSec aus Body")
|
||||
func rateLimitedFromBody() {
|
||||
let err = AuthError.classify(
|
||||
status: 429,
|
||||
data: body(#"{"error":"RATE_LIMITED","retryAfterSec":30,"status":429}"#)
|
||||
)
|
||||
if case let .rateLimited(retryAfter) = err {
|
||||
#expect(retryAfter == 30)
|
||||
} else {
|
||||
Issue.record("Expected .rateLimited(30), got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("RATE_LIMITED fällt auf Retry-After-Header zurück")
|
||||
func rateLimitedFromHeader() {
|
||||
let err = AuthError.classify(
|
||||
status: 429,
|
||||
data: body(#"{"error":"RATE_LIMITED","status":429}"#),
|
||||
retryAfterHeader: 60
|
||||
)
|
||||
if case let .rateLimited(retryAfter) = err {
|
||||
#expect(retryAfter == 60)
|
||||
} else {
|
||||
Issue.record("Expected .rateLimited(60), got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("ACCOUNT_LOCKED erhält retryAfter")
|
||||
func accountLockedRetryAfter() {
|
||||
let err = AuthError.classify(
|
||||
status: 423,
|
||||
data: body(#"{"error":"ACCOUNT_LOCKED","retryAfterSec":120,"status":423}"#)
|
||||
)
|
||||
if case let .accountLocked(retryAfter) = err {
|
||||
#expect(retryAfter == 120)
|
||||
} else {
|
||||
Issue.record("Expected .accountLocked(120), got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("SIGNUP_LIMIT_REACHED")
|
||||
func signupLimitReached() {
|
||||
let err = AuthError.classify(
|
||||
status: 429,
|
||||
data: body(#"{"error":"SIGNUP_LIMIT_REACHED","status":429}"#)
|
||||
)
|
||||
#expect(err == .signupLimitReached)
|
||||
}
|
||||
|
||||
@Test("TOKEN_EXPIRED und TOKEN_INVALID werden unterschieden")
|
||||
func tokenStates() {
|
||||
#expect(
|
||||
AuthError.classify(status: 400, data: body(#"{"error":"TOKEN_EXPIRED"}"#))
|
||||
== .tokenExpired
|
||||
)
|
||||
#expect(
|
||||
AuthError.classify(status: 400, data: body(#"{"error":"TOKEN_INVALID"}"#))
|
||||
== .tokenInvalid
|
||||
)
|
||||
}
|
||||
|
||||
@Test("VALIDATION trägt Message")
|
||||
func validationCarriesMessage() {
|
||||
let err = AuthError.classify(
|
||||
status: 400,
|
||||
data: body(#"{"error":"VALIDATION","message":"email is required","status":400}"#)
|
||||
)
|
||||
if case let .validation(message) = err {
|
||||
#expect(message == "email is required")
|
||||
} else {
|
||||
Issue.record("Expected .validation, got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Unbekannter Code mit Status 401 fällt auf invalidCredentials")
|
||||
func unknownCodeStatusHeuristic401() {
|
||||
let err = AuthError.classify(
|
||||
status: 401,
|
||||
data: body(#"{}"#)
|
||||
)
|
||||
#expect(err == .invalidCredentials)
|
||||
}
|
||||
|
||||
@Test("Unbekannter Code mit Status 503 fällt auf serviceUnavailable")
|
||||
func unknownCodeStatusHeuristic503() {
|
||||
let err = AuthError.classify(
|
||||
status: 503,
|
||||
data: body(#"{}"#)
|
||||
)
|
||||
#expect(err == .serviceUnavailable)
|
||||
}
|
||||
|
||||
@Test("Komplett kaputter Body führt zu serverError mit Status")
|
||||
func brokenBodyFallback() {
|
||||
let err = AuthError.classify(
|
||||
status: 500,
|
||||
data: body("nicht-json")
|
||||
)
|
||||
if case let .serverError(status, code, _) = err {
|
||||
#expect(status == 500)
|
||||
#expect(code == nil)
|
||||
} else {
|
||||
Issue.record("Expected .serverError(500), got \(err)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("errorDescription liefert deutsche Strings")
|
||||
func germanErrorDescriptions() {
|
||||
#expect(AuthError.invalidCredentials.errorDescription == "Email oder Passwort falsch")
|
||||
#expect(AuthError.emailAlreadyRegistered.errorDescription == "Diese Email ist bereits registriert.")
|
||||
#expect(
|
||||
AuthError.rateLimited(retryAfter: 30).errorDescription
|
||||
== "Zu viele Versuche. Bitte warte 30s."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue