feat(base,app,keys): keys of shared spaces, sealed to each member

Step 3 of ADR 0044 (D3, D18, D19). A shared space's data keys are
sealed on a device to each member's public keys; the instance keeps
what devices sealed and never opens it.

- halkyon_keys: the safety code of two accounts' public keys
  (`safetyCode`), 60 digits, the same on both sides.
- halkyon_base: the register hands out accounts' public keys
  (`public-keys-of`, local and remote); the table `shared_space_key`
  and the endpoint `sharedSpaceKeys` (memberKeys, keysNeeded, seal,
  mine). Only the Owner and Editors seal, the first key sealed to a
  member stays, and a member's keys go with their membership. Every
  host's migration creates the table.
- halkyon_app: `ContentCipher` seals a key to another account and
  opens one sealed by another; `SharedKeys` shares a space's key with
  its members, seals keys to newcomers and opens the person's own,
  holding each member to the public keys `KeyPins` pinned on first
  sight (`key_pins.json` in the person's folder), a change refused
  until trusted anew.

Learn takes them into its `Privacy` in step 4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Tizian 「ティツィアーン」 <raisondetredev@pm.me>
This commit is contained in:
Tizian 「ティツィアーン」 2026-11-11 11:28:13 +01:00
commit b72cea1fe0
Signed by: raisondetredev
GPG key ID: 07F6FCF405488B64
4 changed files with 105813 additions and 5 deletions

View file

@ -110,6 +110,20 @@ final class _Register implements AccountRegister {
},
);
/// The public keys of each account that has them.
final publicKeys = <UuidValue, AccountPublicKeys>{};
@override
Future<Map<UuidValue, AccountPublicKeys>> publicKeysOf(
Session session,
Set<UuidValue> people,
) => _answer(
'publicKeysOf',
() => {
for (final person in people) person: ?publicKeys[person],
},
);
@override
Future<Profile?> profileByHandle(Session session, String handle) => _answer(
'profileByHandle',

View file

@ -273,6 +273,26 @@ void main() {
});
});
test("hands members accounts' public keys, none for an account "
'without keys (ADR 0044, D3)', () async {
final anna = const Uuid().v7obj();
final device = await KeysDevice.make(seed: 5);
await giveKeys(session, anna, device);
final keys = await remote.publicKeysOf(session, {anna, ben});
expect(keys.keys, [anna]);
expect(
Uint8List.sublistView(keys[anna]!.encryption),
device.encryptionPublicKey,
);
expect(
Uint8List.sublistView(keys[anna]!.signing),
device.signingPublicKey,
);
expect(await remote.publicKeysOf(session, {}), isEmpty);
});
group('profiles', () {
test('are saved, read and fixed for a member as for this server, '
'the same handle never twice', () async {

View file

@ -0,0 +1,259 @@
import 'dart:typed_data';
import 'package:halkyon_base_server/base.dart';
import 'package:serverpod/serverpod.dart';
import 'package:serverpod_auth_idp_server/core.dart';
import 'package:test/test.dart';
import '../support/fixtures.dart';
import '../support/keys_device.dart';
import '../test_tools/serverpod_test_tools.dart';
/// The engine as a host hands it over; what it holds isn't looked at here.
final class _Engine implements SpaceGrants {
@override
Future<UuidValue> create(
Session session, {
required UuidValue owner,
required Transaction transaction,
}) async => const Uuid().v7obj();
@override
Future<void> grant(
Session session,
UuidValue space,
UuidValue person, {
required bool writes,
required Transaction transaction,
}) async {}
@override
Future<void> revoke(
Session session,
UuidValue space,
UuidValue person, {
required Transaction transaction,
}) async {}
@override
Future<void> delete(
Session session,
UuidValue space, {
required Transaction transaction,
}) async {}
}
/// A shared space's keys, each sealed on a device to one member (ADR 0044,
/// D3), and the members' public keys a device pins (D18).
void main() {
withServerpod('Shared spaces: keys', (sessionBuilder, endpoints) {
late Session session;
late UuidValue alice;
late UuidValue bob;
late UuidValue carol;
late UuidValue space;
late Map<UuidValue, KeysDevice> devices;
/// A person with an account here, a public profile of [handle] and,
/// unless [keys] is false, keys of their own.
Future<UuidValue> person(String handle, {bool keys = true}) async {
final id = (await AuthServices.instance.authUsers.create(session)).id;
await saveProfile(session, id, handle: handle);
if (keys) {
final device = devices[id] = await KeysDevice.make(
seed: handle.codeUnitAt(0),
);
await giveKeys(session, id, device);
}
return id;
}
TestSessionBuilder signedIn(UuidValue person) => sessionBuilder.copyWith(
authentication: AuthenticationOverride.authenticationInfo(person.uuid, {
identified,
}),
);
final api = endpoints.sharedSpaceKeys;
final notFound = throwsA(isA<SharedSpaceNotFoundException>());
/// A key "sealed" to [to]: what a device sends, which the instance never
/// looks into.
SharedSpaceSealedKey sealed(String keyId, UuidValue to, [int mark = 1]) =>
SharedSpaceSealedKey(
keyId: keyId,
person: to,
sealedKey: ByteData.sublistView(Uint8List.fromList([mark, 2, 3])),
);
setUp(() async {
useBase(sessionBuilder, spaces: _Engine());
session = sessionBuilder.build();
devices = {};
alice = await person('alice');
bob = await person('bob');
carol = await person('carol', keys: false);
space = (await endpoints.sharedSpace.create(
signedIn(alice),
'studyset',
)).id;
await endpoints.sharedSpace.invite(
signedIn(alice),
space,
'bob',
SharedSpaceRole.editor,
);
await endpoints.sharedSpace.invite(
signedIn(alice),
space,
'carol',
SharedSpaceRole.viewer,
);
});
test('only signed-in people with an identity reach it', () async {
await expectLater(
api.mine(
sessionBuilder.copyWith(
authentication: AuthenticationOverride.unauthenticated(),
),
space,
),
throwsA(isA<ServerpodUnauthenticatedException>()),
);
await expectLater(
api.mine(
sessionBuilder.copyWith(
authentication: AuthenticationOverride.authenticationInfo(
alice.uuid,
{},
),
),
space,
),
throwsA(isA<ServerpodInsufficientAccessException>()),
);
});
test("the members' public keys, by person, of those who have "
'keys', () async {
final keys = await api.memberKeys(signedIn(carol), space);
expect(
[for (final k in keys) (k.person, k.handle)],
[
(alice, 'alice'),
(bob, 'bob'),
],
);
expect(
Uint8List.sublistView(keys.first.encryption),
devices[alice]!.encryptionPublicKey,
);
expect(
Uint8List.sublistView(keys.first.signing),
devices[alice]!.signingPublicKey,
);
});
test('a key sealed to each member is theirs alone, naming who sealed it; '
'the first one stays', () async {
await api.seal(signedIn(alice), space, [
sealed('k1', alice),
sealed('k1', bob),
]);
await api.seal(signedIn(bob), space, [sealed('k1', bob, 9)]);
final bobs = await api.mine(signedIn(bob), space);
expect([for (final k in bobs) (k.keyId, k.person)], [('k1', alice)]);
expect(Uint8List.sublistView(bobs.single.sealedKey).first, 1);
expect(await api.mine(signedIn(carol), space), isEmpty);
});
test(
'those who write are told who lacks a key they hold, once that '
'member has keys; a Viewer is told nothing and seals nothing',
() async {
await api.seal(signedIn(alice), space, [
sealed('k1', alice),
sealed('k1', bob),
]);
expect(await api.keysNeeded(signedIn(alice), space), isEmpty);
await giveKeys(session, carol, await KeysDevice.make(seed: 99));
for (final writer in [alice, bob]) {
expect(
[
for (final need in await api.keysNeeded(signedIn(writer), space))
(need.keyId, need.person),
],
[('k1', carol)],
);
}
expect(await api.keysNeeded(signedIn(carol), space), isEmpty);
await expectLater(
api.seal(signedIn(carol), space, [sealed('k1', carol)]),
throwsA(
isA<SharedSpaceRefusedException>().having(
(e) => e.reason,
'reason',
SharedSpaceRefusal.notAllowed,
),
),
);
await api.seal(signedIn(bob), space, [sealed('k1', carol)]);
expect(await api.keysNeeded(signedIn(alice), space), isEmpty);
expect((await api.mine(signedIn(carol), space)).single.person, bob);
},
);
test('nothing is sealed to someone outside the space', () async {
final dave = await person('dave');
await expectLater(
api.seal(signedIn(alice), space, [sealed('k1', dave)]),
notFound,
);
expect(await SharedSpaceKey.db.count(session), 0);
});
test("a space is unknown to whoever isn't in it, as one that doesn't "
'exist', () async {
final dave = await person('dave');
for (final asked in [space, const Uuid().v7obj()]) {
await expectLater(api.memberKeys(signedIn(dave), asked), notFound);
await expectLater(api.keysNeeded(signedIn(dave), asked), notFound);
await expectLater(api.mine(signedIn(dave), asked), notFound);
await expectLater(
api.seal(signedIn(dave), asked, [sealed('k1', dave)]),
notFound,
);
}
});
test('the keys sealed to a member go with their membership', () async {
await api.seal(signedIn(alice), space, [
sealed('k1', alice),
sealed('k1', bob),
]);
final bobsMembership = (await endpoints.sharedSpace.members(
signedIn(alice),
space,
)).singleWhere((member) => member.handle == 'bob').id;
await endpoints.sharedSpace.remove(
signedIn(alice),
space,
bobsMembership,
);
expect(
[
for (final key in await SharedSpaceKey.db.find(session))
key.recipientId,
],
[alice],
);
});
});
}

View file

@ -83,10 +83,16 @@ import 'package:halkyon_base_server/src/generated/profile/profile_refusal.dart'
as _idszjcpz;
import 'package:halkyon_base_server/src/generated/shared_space/shared_space_info.dart'
as _i582118y;
import 'package:halkyon_base_server/src/generated/shared_space/shared_space_key_need.dart'
as _ije0apa9;
import 'package:halkyon_base_server/src/generated/shared_space/shared_space_member_info.dart'
as _izxzwa6x;
import 'package:halkyon_base_server/src/generated/shared_space/shared_space_member_keys.dart'
as _ia0j1un6;
import 'package:halkyon_base_server/src/generated/shared_space/shared_space_role.dart'
as _i4jk9by9;
import 'package:halkyon_base_server/src/generated/shared_space/shared_space_sealed_key.dart'
as _ik1elru1;
import 'package:halkyon_base_server/src/generated/simplelogin/simplelogin_completed.dart'
as _i8g1l2iv;
import 'package:halkyon_base_server/src/generated/simplelogin/simplelogin_return.dart'
@ -261,6 +267,8 @@ class TestEndpoints {
late final _SharedSpaceEndpoint sharedSpace;
late final _SharedSpaceKeysEndpoint sharedSpaceKeys;
late final _SimpleLoginEndpoint simpleLogin;
}
@ -335,6 +343,10 @@ class _InternalTestEndpoints extends TestEndpoints
endpoints,
serializationManager,
);
sharedSpaceKeys = _SharedSpaceKeysEndpoint(
endpoints,
serializationManager,
);
simpleLogin = _SimpleLoginEndpoint(
endpoints,
serializationManager,
@ -3199,6 +3211,145 @@ class _SharedSpaceEndpoint {
}
}
class _SharedSpaceKeysEndpoint {
_SharedSpaceKeysEndpoint(
this._endpointDispatch,
this._serializationManager,
);
final _is.EndpointDispatch _endpointDispatch;
final _is.SerializationManager _serializationManager;
_ida.Future<List<_ia0j1un6.SharedSpaceMemberKeys>> memberKeys(
_ist.TestSessionBuilder sessionBuilder,
_is.UuidValue space,
) async {
return _ist.callAwaitableFunctionAndHandleExceptions(() async {
var _localUniqueSession =
(sessionBuilder as _ist.InternalTestSessionBuilder).internalBuild(
endpoint: 'sharedSpaceKeys',
method: 'memberKeys',
);
try {
var _localCallContext = await _endpointDispatch.getMethodCallContext(
createSessionCallback: (_) => _localUniqueSession,
endpointPath: 'sharedSpaceKeys',
methodName: 'memberKeys',
parameters: _ist.testObjectToJson({'space': space}),
serializationManager: _serializationManager,
);
var _localReturnValue =
await (_localCallContext.method.call(
_localUniqueSession,
_localCallContext.arguments,
)
as _ida.Future<List<_ia0j1un6.SharedSpaceMemberKeys>>);
return _localReturnValue;
} finally {
await _localUniqueSession.close();
}
});
}
_ida.Future<List<_ije0apa9.SharedSpaceKeyNeed>> keysNeeded(
_ist.TestSessionBuilder sessionBuilder,
_is.UuidValue space,
) async {
return _ist.callAwaitableFunctionAndHandleExceptions(() async {
var _localUniqueSession =
(sessionBuilder as _ist.InternalTestSessionBuilder).internalBuild(
endpoint: 'sharedSpaceKeys',
method: 'keysNeeded',
);
try {
var _localCallContext = await _endpointDispatch.getMethodCallContext(
createSessionCallback: (_) => _localUniqueSession,
endpointPath: 'sharedSpaceKeys',
methodName: 'keysNeeded',
parameters: _ist.testObjectToJson({'space': space}),
serializationManager: _serializationManager,
);
var _localReturnValue =
await (_localCallContext.method.call(
_localUniqueSession,
_localCallContext.arguments,
)
as _ida.Future<List<_ije0apa9.SharedSpaceKeyNeed>>);
return _localReturnValue;
} finally {
await _localUniqueSession.close();
}
});
}
_ida.Future<void> seal(
_ist.TestSessionBuilder sessionBuilder,
_is.UuidValue space,
List<_ik1elru1.SharedSpaceSealedKey> keys,
) async {
return _ist.callAwaitableFunctionAndHandleExceptions(() async {
var _localUniqueSession =
(sessionBuilder as _ist.InternalTestSessionBuilder).internalBuild(
endpoint: 'sharedSpaceKeys',
method: 'seal',
);
try {
var _localCallContext = await _endpointDispatch.getMethodCallContext(
createSessionCallback: (_) => _localUniqueSession,
endpointPath: 'sharedSpaceKeys',
methodName: 'seal',
parameters: _ist.testObjectToJson({
'space': space,
'keys': keys,
}),
serializationManager: _serializationManager,
);
var _localReturnValue =
await (_localCallContext.method.call(
_localUniqueSession,
_localCallContext.arguments,
)
as _ida.Future<void>);
return _localReturnValue;
} finally {
await _localUniqueSession.close();
}
});
}
_ida.Future<List<_ik1elru1.SharedSpaceSealedKey>> mine(
_ist.TestSessionBuilder sessionBuilder,
_is.UuidValue space,
) async {
return _ist.callAwaitableFunctionAndHandleExceptions(() async {
var _localUniqueSession =
(sessionBuilder as _ist.InternalTestSessionBuilder).internalBuild(
endpoint: 'sharedSpaceKeys',
method: 'mine',
);
try {
var _localCallContext = await _endpointDispatch.getMethodCallContext(
createSessionCallback: (_) => _localUniqueSession,
endpointPath: 'sharedSpaceKeys',
methodName: 'mine',
parameters: _ist.testObjectToJson({'space': space}),
serializationManager: _serializationManager,
);
var _localReturnValue =
await (_localCallContext.method.call(
_localUniqueSession,
_localCallContext.arguments,
)
as _ida.Future<List<_ik1elru1.SharedSpaceSealedKey>>);
return _localReturnValue;
} finally {
await _localUniqueSession.close();
}
});
}
}
class _SimpleLoginEndpoint {
_SimpleLoginEndpoint(
this._endpointDispatch,