1use std::sync::Arc;
16
17use anyhow::{ensure, Context, Result};
18use hyprstream_pds::{
19 AllocatedAccountName, DidOpSignature, GenesisRepoHead, GenesisRotationKeys, HostedAccountMint,
20 HostedRepoGenesis, SealedHostedAccount, UnsignedGenesisDidOp, DID_DOCUMENT_PATH,
21 DID_OPERATION_LOG_PATH,
22};
23use hyprstream_rpc::service_entry::BrowserQuicReach;
24
25use crate::validate_tenant_component;
26
27#[derive(Clone, Debug, Eq, PartialEq)]
32pub struct HostedAccountRegistrationRequest {
33 handle: String,
34}
35
36impl HostedAccountRegistrationRequest {
37 fn new(handle: impl Into<String>) -> Self {
38 Self {
39 handle: handle.into(),
40 }
41 }
42
43 pub fn from_client_fields(
45 handle: impl Into<String>,
46 client_asserted_tenant: Option<&str>,
47 ) -> Result<Self> {
48 ensure!(
49 client_asserted_tenant.is_none(),
50 "client-asserted tenant is forbidden for hosted-account registration"
51 );
52 Ok(Self::new(handle))
53 }
54
55 #[must_use]
56 pub fn handle(&self) -> &str {
57 &self.handle
58 }
59}
60
61#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct HostedAccountRegistrationResult {
67 pub handle: String,
68 pub did: String,
69 pub pds_endpoint: String,
70 pub quic_url: String,
71 pub cert_hash: String,
72}
73
74#[derive(Clone)]
79pub struct AuthorityHostedAccountBinding {
80 tenant: String,
81 name: AllocatedAccountName,
82 rotations: GenesisRotationKeys,
83}
84
85impl AuthorityHostedAccountBinding {
86 pub fn new(
88 tenant: impl Into<String>,
89 name: AllocatedAccountName,
90 rotations: GenesisRotationKeys,
91 ) -> Result<Self> {
92 let tenant = tenant.into();
93 validate_tenant_component(&tenant)?;
94 Ok(Self {
95 tenant,
96 name,
97 rotations,
98 })
99 }
100
101 #[must_use]
102 pub fn tenant(&self) -> &str {
103 &self.tenant
104 }
105
106 #[must_use]
107 pub fn name(&self) -> &AllocatedAccountName {
108 &self.name
109 }
110}
111
112pub trait HostedAccountAuthority: Send + Sync {
114 fn allocate(&self, requested_handle: &str) -> Result<AuthorityHostedAccountBinding>;
115
116 fn allocate_for_transaction(
121 &self,
122 requested_handle: &str,
123 _transaction_id: &str,
124 ) -> Result<AuthorityHostedAccountBinding> {
125 self.allocate(requested_handle)
126 }
127}
128
129pub trait HostedAccountGenesisSigner {
131 fn sign(&self, unsigned: &UnsignedGenesisDidOp) -> Result<DidOpSignature>;
132}
133
134#[derive(Clone, Debug, PartialEq)]
136pub struct LiveHostedPdsDiscovery {
137 pub pds_endpoint: String,
138 pub browser_quic_reach: BrowserQuicReach,
139}
140
141pub trait HostedPdsDiscovery: Send + Sync {
148 fn current(&self) -> Result<LiveHostedPdsDiscovery>;
149}
150
151pub struct HostedPdsAccountPublication<'a> {
157 tenant: &'a str,
158 account: &'a SealedHostedAccount,
159 repo: &'a HostedRepoGenesis,
160 transaction_id: Option<&'a str>,
161}
162
163impl HostedPdsAccountPublication<'_> {
164 #[must_use]
165 pub fn tenant(&self) -> &str {
166 self.tenant
167 }
168
169 #[must_use]
170 pub fn label(&self) -> &str {
171 self.account.record().name().label()
172 }
173
174 #[must_use]
175 pub fn account(&self) -> &SealedHostedAccount {
176 self.account
177 }
178
179 #[must_use]
180 pub fn repo(&self) -> &HostedRepoGenesis {
181 self.repo
182 }
183
184 #[must_use]
187 pub fn transaction_id(&self) -> Option<&str> {
188 self.transaction_id
189 }
190
191 #[must_use]
193 pub fn did_document(&self) -> (&'static str, &[u8]) {
194 (DID_DOCUMENT_PATH, self.account.did_document().as_bytes())
195 }
196
197 #[must_use]
200 pub fn did_operation_log_genesis(&self) -> (&'static str, &[u8]) {
201 (DID_OPERATION_LOG_PATH, self.account.genesis_bytes())
202 }
203}
204
205pub trait HostedPdsAccountPublisher: Send + Sync {
207 fn publish(&self, publication: HostedPdsAccountPublication<'_>) -> Result<()>;
208}
209
210pub struct HostedPdsAccountMinter {
212 authority: Arc<dyn HostedAccountAuthority>,
213 discovery: Arc<dyn HostedPdsDiscovery>,
214 publisher: Arc<dyn HostedPdsAccountPublisher>,
215}
216
217impl HostedPdsAccountMinter {
218 #[must_use]
219 pub fn new(
220 authority: Arc<dyn HostedAccountAuthority>,
221 discovery: Arc<dyn HostedPdsDiscovery>,
222 publisher: Arc<dyn HostedPdsAccountPublisher>,
223 ) -> Self {
224 Self {
225 authority,
226 discovery,
227 publisher,
228 }
229 }
230
231 pub fn mint(
233 &self,
234 request: &HostedAccountRegistrationRequest,
235 signer: &dyn HostedAccountGenesisSigner,
236 ) -> Result<HostedAccountRegistrationResult> {
237 self.mint_inner(request, signer, None)
238 }
239
240 pub fn mint_for_transaction(
243 &self,
244 request: &HostedAccountRegistrationRequest,
245 signer: &dyn HostedAccountGenesisSigner,
246 transaction_id: &str,
247 ) -> Result<HostedAccountRegistrationResult> {
248 ensure!(
249 !transaction_id.is_empty(),
250 "hosted-account mint transaction id must not be empty"
251 );
252 self.mint_inner(request, signer, Some(transaction_id))
253 }
254
255 fn mint_inner(
256 &self,
257 request: &HostedAccountRegistrationRequest,
258 signer: &dyn HostedAccountGenesisSigner,
259 transaction_id: Option<&str>,
260 ) -> Result<HostedAccountRegistrationResult> {
261 ensure!(
262 !request.handle.is_empty(),
263 "hosted account handle must not be empty"
264 );
265
266 let live = self
269 .discovery
270 .current()
271 .context("live hosted-PDS discovery is unavailable")?;
272 ensure!(
273 !live.browser_quic_reach.quic_url.is_empty()
274 && !live.browser_quic_reach.cert_hash.is_empty(),
275 "live hosted-PDS QUIC discovery is incomplete"
276 );
277
278 let binding = match transaction_id {
279 Some(transaction_id) => self
280 .authority
281 .allocate_for_transaction(&request.handle, transaction_id),
282 None => self.authority.allocate(&request.handle),
283 }
284 .context("hosted-account authority allocation failed")?;
285 ensure!(
286 binding.name.label() == request.handle,
287 "authority allocation does not match the requested handle"
288 );
289
290 let mint = HostedAccountMint::begin(binding.name.clone(), binding.rotations.clone())
291 .context("hosted-account mint initialization failed")?;
292 let document = mint
293 .seal_did_document(&live.pds_endpoint)
294 .context("hosted DID document sealing failed")?;
295 let (pending, repo) = mint
296 .prepare_pds_genesis(document, hyprstream_pds::tid::Tid::now())
297 .context("hosted PDS repo genesis failed")?;
298 let signature = signer
299 .sign(pending.unsigned_genesis())
300 .context("hosted DID genesis signing failed")?;
301 let account = pending
302 .seal(signature)
303 .context("hosted DID genesis signature is invalid")?;
304
305 ensure!(
306 account.genesis().unsigned().head_at_op()
307 == GenesisRepoHead::Existing(repo.commit_cid()),
308 "hosted DID genesis is not bound to the signed PDS repo"
309 );
310 repo.verify(&account.record().atproto_verifying_key()?)
311 .context("hosted PDS repo verification failed")?;
312
313 self.publisher
314 .publish(HostedPdsAccountPublication {
315 tenant: binding.tenant(),
316 account: &account,
317 repo: &repo,
318 transaction_id,
319 })
320 .context("hosted PDS account publication failed")?;
321
322 Ok(registration_result(account, live.browser_quic_reach))
323 }
324}
325
326fn registration_result(
327 account: SealedHostedAccount,
328 browser_reach: BrowserQuicReach,
329) -> HostedAccountRegistrationResult {
330 let document = account.did_document();
331 HostedAccountRegistrationResult {
332 handle: document.handle().to_owned(),
333 did: document.did().to_owned(),
334 pds_endpoint: document.pds_endpoint().to_owned(),
335 quic_url: browser_reach.quic_url,
336 cert_hash: browser_reach.cert_hash,
337 }
338}
339
340#[cfg(all(test, not(target_arch = "wasm32")))]
341mod tests {
342 #![allow(clippy::expect_used, clippy::unwrap_used)]
343
344 use std::sync::atomic::{AtomicUsize, Ordering};
345 use std::sync::OnceLock;
346
347 use ed25519_dalek::SigningKey;
348 use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes, MlDsaSigningKey};
349 use hyprstream_pds::{
350 sign_genesis, AccountRecord, HostKeyEnrollment, HybridRotationKey, RecoveryKeyEnrollment,
351 UserRotationKey,
352 };
353 use hyprstream_rpc::auth::mac::{MacDecision, SecurityContext};
354 use hyprstream_rpc::Subject;
355 use hyprstream_vfs::{SyntheticMount, SyntheticNode};
356 use rand::rngs::OsRng;
357
358 use super::*;
359 use crate::{
360 AccountRecordReadAuthorizer, AccountRecordStore, PDS_ACCOUNTS_DIRECTORY,
361 PDS_ACCOUNT_RECORD_FILE,
362 };
363
364 struct TestAuthority {
365 calls: AtomicUsize,
366 rotations: GenesisRotationKeys,
367 }
368
369 impl HostedAccountAuthority for TestAuthority {
370 fn allocate(&self, requested_handle: &str) -> Result<AuthorityHostedAccountBinding> {
371 self.calls.fetch_add(1, Ordering::SeqCst);
372 AuthorityHostedAccountBinding::new(
373 "tenant-authority",
374 AllocatedAccountName::new(
375 requested_handle,
376 format!("did:web:{requested_handle}.accounts.example"),
377 )?,
378 self.rotations.clone(),
379 )
380 }
381 }
382
383 struct TestSigner {
384 ed: SigningKey,
385 pq: MlDsaSigningKey,
386 }
387
388 impl HostedAccountGenesisSigner for TestSigner {
389 fn sign(&self, unsigned: &UnsignedGenesisDidOp) -> Result<DidOpSignature> {
390 sign_genesis(unsigned, &self.ed, &self.pq)
391 }
392 }
393
394 #[derive(Clone)]
395 struct StaticDiscovery;
396
397 impl HostedPdsDiscovery for StaticDiscovery {
398 fn current(&self) -> Result<LiveHostedPdsDiscovery> {
399 Ok(LiveHostedPdsDiscovery {
400 pds_endpoint: "https://pds.example".to_owned(),
401 browser_quic_reach: BrowserQuicReach {
402 quic_url: "https://pds.example:4433/wt".to_owned(),
403 cert_hash: "paWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaU=".to_owned(),
404 },
405 })
406 }
407 }
408
409 #[derive(Clone)]
410 struct Published {
411 tenant: String,
412 label: String,
413 account_record: Vec<u8>,
414 did_document_path: String,
415 did_document: Vec<u8>,
416 operation_log_path: String,
417 operation_log_genesis: Vec<u8>,
418 mst_root: hyprstream_pds::Cid,
419 mst_blocks: Vec<(hyprstream_pds::Cid, Vec<u8>)>,
420 commit: Vec<u8>,
421 public_commit: Vec<u8>,
422 }
423
424 #[derive(Default)]
425 struct CapturingPublisher {
426 published: OnceLock<Published>,
427 }
428
429 impl HostedPdsAccountPublisher for CapturingPublisher {
430 fn publish(&self, publication: HostedPdsAccountPublication<'_>) -> Result<()> {
431 let (did_document_path, did_document) = publication.did_document();
432 let (operation_log_path, operation_log_genesis) =
433 publication.did_operation_log_genesis();
434 let published = Published {
435 tenant: publication.tenant().to_owned(),
436 label: publication.label().to_owned(),
437 account_record: publication.account().record_bytes().to_vec(),
438 did_document_path: did_document_path.to_owned(),
439 did_document: did_document.to_vec(),
440 operation_log_path: operation_log_path.to_owned(),
441 operation_log_genesis: operation_log_genesis.to_vec(),
442 mst_root: publication.repo().mst_root(),
443 mst_blocks: publication.repo().mst_blocks().to_vec(),
444 commit: publication.repo().commit_bytes().to_vec(),
445 public_commit: publication.repo().public_commit_bytes().to_vec(),
446 };
447 self.published
448 .set(published)
449 .map_err(|_| anyhow::anyhow!("account was published more than once"))?;
450 Ok(())
451 }
452 }
453
454 fn fixture() -> (
455 Arc<TestAuthority>,
456 Arc<CapturingPublisher>,
457 TestSigner,
458 HostedPdsAccountMinter,
459 ) {
460 let ed = SigningKey::generate(&mut OsRng);
461 let (pq, pq_vk) = ml_dsa_generate_keypair();
462 let rotation =
463 HybridRotationKey::new(ed.verifying_key().to_bytes(), ml_dsa_vk_bytes(&pq_vk)).unwrap();
464 let authority = Arc::new(TestAuthority {
465 calls: AtomicUsize::new(0),
466 rotations: GenesisRotationKeys::new(
467 UserRotationKey::new(rotation),
468 RecoveryKeyEnrollment::Declined,
469 HostKeyEnrollment::Absent,
470 )
471 .unwrap(),
472 });
473 let publisher = Arc::new(CapturingPublisher::default());
474 let minter = HostedPdsAccountMinter::new(
475 authority.clone(),
476 Arc::new(StaticDiscovery),
477 publisher.clone(),
478 );
479 (authority, publisher, TestSigner { ed, pq }, minter)
480 }
481
482 struct PermitReads;
483
484 impl AccountRecordReadAuthorizer for PermitReads {
485 fn check_read(
486 &self,
487 _subject: &Subject,
488 _verified_tenant: Option<&str>,
489 _security_context: Option<&SecurityContext>,
490 _object_id: &str,
491 ) -> MacDecision {
492 MacDecision::Permit
493 }
494 }
495
496 #[test]
497 fn mint_publishes_did_log_and_signed_repo_and_returns_live_discovery() {
498 let (_authority, publisher, signer, minter) = fixture();
499 let result = minter
500 .mint(&HostedAccountRegistrationRequest::new("alice"), &signer)
501 .unwrap();
502 let published = publisher
503 .published
504 .get()
505 .cloned()
506 .expect("mint must publish");
507
508 assert_eq!(published.did_document_path, DID_DOCUMENT_PATH);
509 assert!(!published.did_document.is_empty());
510 assert_eq!(published.operation_log_path, DID_OPERATION_LOG_PATH);
511 assert!(!published.operation_log_genesis.is_empty());
512 let document =
513 hyprstream_pds::SealedHostedDidDocument::from_canonical_json(&published.did_document)
514 .unwrap();
515 let genesis =
516 hyprstream_pds::GenesisDidOp::from_dag_cbor(&published.operation_log_genesis).unwrap();
517 assert!(published
518 .mst_blocks
519 .iter()
520 .any(|(cid, bytes)| *cid == published.mst_root
521 && hyprstream_pds::Cid::from_dag_cbor(bytes) == *cid));
522 let commit = hyprstream_pds::commit::Commit::from_dag_cbor(&published.commit).unwrap();
523 let public_commit =
524 hyprstream_pds::commit::Commit::from_atproto_dag_cbor(&published.public_commit)
525 .unwrap();
526 let record = AccountRecord::from_dag_cbor(&published.account_record).unwrap();
527 commit
528 .verify(&record.atproto_verifying_key().unwrap())
529 .unwrap();
530 public_commit
531 .verify_atproto(&record.atproto_verifying_key().unwrap())
532 .unwrap();
533 assert_eq!(public_commit.did, commit.did);
534 assert_eq!(public_commit.data, commit.data);
535 assert_eq!(public_commit.rev, commit.rev);
536 assert_eq!(public_commit.prev, commit.prev);
537 assert_eq!(document.did(), record.name().did());
538 assert_eq!(document.cid(), record.doc_cid());
539 assert_eq!(genesis.cid().unwrap(), record.genesis_op());
540 assert_eq!(
541 genesis.unsigned().head_at_op(),
542 GenesisRepoHead::Existing(commit.cid())
543 );
544 assert_eq!(commit.data, published.mst_root);
545
546 assert_eq!(result.handle, "at://alice.accounts.example");
547 assert_eq!(result.did, "did:web:alice.accounts.example");
548 assert_eq!(result.pds_endpoint, "https://pds.example");
549 assert_eq!(result.quic_url, "https://pds.example:4433/wt");
550 assert_eq!(
551 result.cert_hash,
552 "paWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaU="
553 );
554 }
555
556 #[tokio::test]
557 async fn minted_did_resolves_to_the_authority_owned_tenant() {
558 let (_authority, publisher, signer, minter) = fixture();
559 let result = minter
560 .mint(&HostedAccountRegistrationRequest::new("alice"), &signer)
561 .unwrap();
562 let published = publisher
563 .published
564 .get()
565 .cloned()
566 .expect("mint must publish");
567 let root = SyntheticNode::dir().with_child(
568 published.tenant.clone(),
569 SyntheticNode::dir().with_child(
570 PDS_ACCOUNTS_DIRECTORY,
571 SyntheticNode::dir().with_child(
572 published.label,
573 SyntheticNode::dir().with_child(
574 PDS_ACCOUNT_RECORD_FILE,
575 SyntheticNode::file(published.account_record),
576 ),
577 ),
578 ),
579 );
580 let store =
581 AccountRecordStore::new(Arc::new(SyntheticMount::new(root)), Arc::new(PermitReads));
582 store
583 .refresh_hosted_did_index(&Subject::new(crate::OAUTH_ACCOUNT_RESOLVER_SUBJECT))
584 .await
585 .unwrap();
586
587 assert_eq!(
588 store
589 .resolve_tenant_for_hosted_did(
590 &Subject::new(crate::OAUTH_ACCOUNT_RESOLVER_SUBJECT),
591 &result.did,
592 )
593 .await
594 .unwrap(),
595 Some("tenant-authority".to_owned())
596 );
597 }
598
599 #[test]
600 fn client_asserted_tenant_is_rejected_before_authority_or_publication() {
601 let (authority, publisher, _signer, _minter) = fixture();
602 let error =
603 HostedAccountRegistrationRequest::from_client_fields("alice", Some("tenant-client"))
604 .unwrap_err();
605
606 assert!(
607 error.to_string().contains("client-asserted tenant"),
608 "{error}"
609 );
610 assert_eq!(authority.calls.load(Ordering::SeqCst), 0);
611 assert!(publisher.published.get().is_none());
612 }
613}