Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Sources/SelectiveRemote/CloudAPIClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ enum SelectiveRemoteCloudError: LocalizedError, Equatable {
ru: "Неверная электронная почта или пароль.",
en: "The email or password is incorrect."
)
case "device_conflict" where status == 409:
UpdateLocalization.text(
ru: "Этот профиль macOS уже связан с другим аккаунтом Cloud. Используйте отдельную учётную запись macOS для каждого аккаунта Cloud.",
en: "This macOS profile is already linked to another Cloud account. Use a separate macOS user account for each Cloud account."
)
case "email_not_verified":
UpdateLocalization.text(
ru: "Сначала подтвердите электронную почту по ссылке из письма.",
Expand Down
11 changes: 8 additions & 3 deletions Sources/SelectiveRemote/CloudAccountViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,14 @@ struct SelectiveRemoteCloudSignInView: View {

if let errorMessage {
Section {
Label(errorMessage, systemImage: "exclamationmark.triangle.fill")
.foregroundStyle(.orange)
.fixedSize(horizontal: false, vertical: true)
Label {
Text(errorMessage)
.foregroundStyle(.primary)
} icon: {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(.orange)
}
.fixedSize(horizontal: false, vertical: true)
}
}
}
Expand Down
54 changes: 54 additions & 0 deletions Tests/SelectiveRemoteTests/CloudMacOSFoundationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,60 @@ struct CloudMacOSFoundationTests {
#expect(store.token(for: endpoint) == nil)
}

@Test("A different account's device conflict preserves the current Cloud session")
func accountSwitchDeviceConflictKeepsExistingSession() async throws {
let endpoint = try SelectiveRemoteCloudEndpoint.normalized("https://device-conflict-\(UUID()).example.invalid")
let deviceID = UUID()
let firstAccountToken = String(repeating: "a", count: 43)
let store = SelectiveRemoteCloudMemoryTokenStore()
store.saveToken(firstAccountToken, for: endpoint)

try await confirmation("Exactly one POST to the login endpoint") { loginRequest in
let client = SelectiveRemoteCloudAPIClient(tokenStore: store, dataLoader: { request in
guard request.httpMethod == "POST", request.url?.path == "/v1/auth/login" else {
Issue.record("A rejected login must not make any other Cloud requests")
return Self.response(request, status: 500, json: nil)
}
loginRequest()
let body = try #require(request.httpBody)
let payload = try #require(JSONSerialization.jsonObject(with: body) as? [String: Any])
let device = try #require(payload["device"] as? [String: Any])
let submittedID = try #require(device["id"] as? String)
#expect(payload["email"] as? String == "second@example.invalid")
#expect(UUID(uuidString: submittedID) == deviceID)
#expect(request.value(forHTTPHeaderField: "Authorization") == nil)
return Self.response(request, status: 409, json: ["error": "device_conflict"])
}, publicationStore: { throw CancellationError() })
let existing = try await client.sessionBinding(endpoint: endpoint)

do {
_ = try await client.loginWithSession(
endpoint: endpoint, email: "second@example.invalid", password: "synthetic-password",
device: .thisMac(id: deviceID, name: "Synthetic Mac")
)
Issue.record("The second account's login should fail with device_conflict")
} catch let error as SelectiveRemoteCloudError {
#expect(error == .serviceError(409, "device_conflict"))
#expect(!error.isAuthenticationLoss)
}

#expect(store.token(for: endpoint) == firstAccountToken)
#expect(SelectiveRemotePublicationLifecycle.epoch(endpoint: endpoint) == existing.epoch)
try await client.checkSession(existing)
}
}

@Test("Native device conflict explains that each Cloud account needs a separate macOS user")
func deviceConflictExplainsHowToSignIn() {
let guidance = UpdateLocalization.text(
ru: "Этот профиль macOS уже связан с другим аккаунтом Cloud. Используйте отдельную учётную запись macOS для каждого аккаунта Cloud.",
en: "This macOS profile is already linked to another Cloud account. Use a separate macOS user account for each Cloud account."
)

#expect(SelectiveRemoteCloudError.serviceError(409, "device_conflict").errorDescription == guidance)
#expect(SelectiveRemoteCloudError.serviceError(503, "device_conflict").errorDescription != guidance)
}

@Test("Logout with an empty store rejects a pending successful login response", .timeLimit(.minutes(1)))
func logoutBeforeLoginResponseCannotRestoreSession() async throws {
let endpoint = URL(string: "https://pending-login-logout.example.invalid")!
Expand Down
83 changes: 81 additions & 2 deletions cloud/tests/account-switch-login-postgres.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { PostgresStore } from "../src/postgres-store.mjs";
import { CloudService } from "../src/service.mjs";
import { hashPassword, validateDevicePublicKey } from "../src/security.mjs";
import { publicOperationError } from "../src/service-error.mjs";
import { encryptVaultPayload, generateVaultKey, wrapVaultKey } from "../public/vault-crypto.js";
import { createAccountDeviceCoordinator } from "../public/vault-local.js";
import { ensureTeamDeviceIdentity } from "../public/team-vault-crypto.js";
import * as vaultSync from "../public/vault-sync.js";
Expand Down Expand Up @@ -99,12 +100,13 @@ async function fixture(t) {
});
server.listen(0, "127.0.0.1"); await once(server, "listening");
t.after(() => new Promise(resolve => server.close(resolve)));
const client = vaultSync.createAuthenticatedVaultClient({ fetchValue: (path, init) => fetch(`http://127.0.0.1:${server.address().port}${path}`, init) });
const fetchValue = (path, init) => fetch(`http://127.0.0.1:${server.address().port}${path}`, init);
const client = vaultSync.createAuthenticatedVaultClient({ fetchValue });
const login = (user, overrides = {}) => loginFlow({
input: { email: user.email, password, ...overrides }, accountDevices, ensureIdentity,
login: (input) => client.login(input),
});
return { pool, client, a, b, legacyID, replacementID, accountDevices, ensureIdentity,
return { pool, fetchValue, client, a, b, legacyID, replacementID, accountDevices, ensureIdentity,
identityRecords, login, attempts, failures, replacements: () => replacements };
}

Expand Down Expand Up @@ -134,6 +136,83 @@ test("actual PostgreSQL and browser client switch approved accounts with one bou
assert.equal(f.replacements(), 1);
});

test("a Mac reusing its installation device gets one conflict and leaves both accounts unchanged", options, async t => {
const f = await fixture(t);
const macDevice = { id: f.legacyID, name: "Synthetic Mac", platform: "macos", appVersion: "0.32", publicKey: f.a.identity.publicKey };
const login = (account, device) => f.fetchValue("/v1/auth/login", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: account.email, password, device }),
});

async function seedVault(account, device, marker) {
const response = await login(account, device);
assert.equal(response.status, 200);
const { token, user, deviceID } = await response.json();
assert.equal(user.id, account.id);
assert.equal(deviceID, device.id);
const vaultKey = await generateVaultKey(webcrypto);
const wrappedKey = await wrapVaultKey(vaultKey, password, webcrypto);
const envelope = await encryptVaultPayload({
vaultKey, wrappedKey, payload: { marker }, baseRevision: 0, cryptoValue: webcrypto,
});
// The test database already has each account's empty Vault from registration.
// Populate its head and history directly as the starting state for the login test.
const seeded = await f.pool.query(`
WITH vault AS (
UPDATE personal_vaults
SET revision = 1, envelope_version = $2, wrapped_key = $3, ciphertext = $4, nonce = $5,
auth_tag = $6, content_hash = $7, updated_by_device_id = $8, updated_at = now()
WHERE user_id = $1 AND revision = 0
RETURNING id, revision, envelope_version, wrapped_key, ciphertext, nonce, auth_tag, content_hash, updated_by_device_id
)
INSERT INTO vault_revisions (vault_id, revision, envelope_version, wrapped_key, ciphertext, nonce,
auth_tag, content_hash, updated_by_device_id)
SELECT id, revision, envelope_version, wrapped_key, ciphertext, nonce, auth_tag, content_hash, updated_by_device_id
FROM vault`, [
account.id, envelope.envelopeVersion, envelope.wrappedKey, envelope.ciphertext,
envelope.nonce, envelope.authTag, envelope.contentHash, deviceID,
]);
assert.equal(seeded.rowCount, 1);
return token;
}

const aToken = await seedVault(f.a, macDevice, "synthetic A");
await seedVault(f.b, { ...macDevice, id: f.b.identity.deviceID, publicKey: f.b.identity.publicKey }, "synthetic B");
const logout = await f.fetchValue("/v1/auth/logout", { method: "POST", headers: { authorization: `Bearer ${aToken}` } });
assert.equal(logout.status, 204);

async function readAccountState() {
const scope = [[f.a.id, f.b.id]];
const [vaults, revisions, devices, sessions] = await Promise.all([
f.pool.query("SELECT * FROM personal_vaults WHERE user_id = ANY($1::uuid[]) ORDER BY id", scope),
f.pool.query(`SELECT r.* FROM vault_revisions r JOIN personal_vaults v ON v.id = r.vault_id
WHERE v.user_id = ANY($1::uuid[]) ORDER BY r.vault_id, r.revision`, scope),
f.pool.query("SELECT * FROM devices WHERE user_id = ANY($1::uuid[]) ORDER BY id", scope),
f.pool.query(`SELECT id, user_id, device_id, created_at, expires_at, last_used_at, revoked_at
FROM sessions WHERE user_id = ANY($1::uuid[]) ORDER BY id`, scope),
]);
return { vaults: vaults.rows, revisions: revisions.rows, devices: devices.rows, sessions: sessions.rows };
}

const before = await readAccountState();
assert.deepEqual(before.vaults.map(row => Number(row.revision)), [1, 1]);
assert.deepEqual(before.revisions.map(row => row.ciphertext), before.vaults.map(row => row.ciphertext));
assert.notEqual(before.vaults[0].ciphertext, before.vaults[1].ciphertext);
assert.equal(before.devices.length, 2);
assert.equal(before.devices.find(row => row.id === macDevice.id)?.user_id, f.a.id);
assert.equal(before.sessions.length, 2);
assert.ok(before.sessions.find(row => row.user_id === f.a.id)?.revoked_at);
assert.equal(before.sessions.find(row => row.user_id === f.b.id)?.revoked_at, null);

const attemptCount = f.attempts.length;
const conflict = await login(f.b, macDevice);
assert.equal(conflict.status, 409);
assert.deepEqual(await conflict.json(), { error: "device_conflict" });
assert.deepEqual(f.attempts.slice(attemptCount), [{ email: f.b.email, deviceID: macDevice.id }]);
assert.deepEqual(await readAccountState(), before);
});

test("an accepted account mapping is never rotated on cross-account conflict", options, async t => {
const f = await fixture(t);
await f.accountDevices.remember(f.b.email, f.legacyID);
Expand Down
Loading