gent-daemon 0.2.24

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
use super::*;
use gent_protocol::secret_handoff::{FILENAME, MEDIA_TYPE};

#[tokio::test]
async fn secret_handoff_uses_ordinary_delivery_permissions_and_idempotence() -> Result<()> {
    let mut pair = Pair::new().await;
    let recipient = pair.agents[1].clone();
    let identity = age::x25519::Identity::generate();
    let armor = age::encrypt_and_armor(&identity.to_public(), b"handoff fixture")?;
    let send = AgentOp::SecretSend {
        recipient: recipient.clone(),
        request_id: Uuid::now_v7().to_string(),
        armor: armor.clone(),
    };
    pair.policy(false);
    assert!(pair.agent(0, send.clone()).is_err());
    pair.policy(true);
    pair.pump();

    // An older peer can send arbitrary bytes under the same MIME type. Its
    // receipt must advance the ordered stream before our valid message.
    let file = FilePart {
        name: FILENAME.into(),
        media_type: MEDIA_TYPE.into(),
        data_base64: STANDARD.encode("ordinary file"),
    };
    let generic = |files, text: &str| AgentOp::Send {
        recipient: recipient.clone(),
        request_id: Uuid::now_v7().to_string(),
        files,
        text: text.into(),
        file_ids: vec![],
    };
    let read = |sent: &Value| AgentOp::SecretRead {
        message_id: sent["message_id"].as_str().unwrap().into(),
    };
    let malformed = pair.agent(0, generic(vec![file.clone()], ""))?;
    let good = FilePart {
        data_base64: STANDARD.encode(&armor),
        ..file
    };
    let ordinary = pair.agent(0, generic(vec![], &armor))?;
    let captioned = pair.agent(0, generic(vec![good.clone()], "ordinary caption"))?;
    let multiple = pair.agent(0, generic(vec![good.clone(), good.clone()], ""))?;
    let renamed = pair.agent(
        0,
        generic(
            vec![FilePart {
                name: "other.age".into(),
                ..good.clone()
            }],
            "",
        ),
    )?;
    let untyped = pair.agent(
        0,
        generic(
            vec![FilePart {
                media_type: "text/plain".into(),
                ..good.clone()
            }],
            "",
        ),
    )?;
    let sent = pair.agent(0, send.clone())?;
    assert_eq!(sent["duplicate"], false);
    pair.pump();
    for other in [
        &malformed, &ordinary, &captioned, &multiple, &renamed, &untyped,
    ] {
        assert_eq!(
            pair.agent(1, read(other)).unwrap_err().to_string(),
            UNAVAILABLE
        );
    }
    let retry = pair.agent(0, send.clone())?;
    assert_eq!(retry["duplicate"], true);
    assert_eq!(retry["message_id"], sent["message_id"]);
    let mut changed = send;
    if let AgentOp::SecretSend { armor, .. } = &mut changed {
        *armor = armor.replace('\n', "\r\n");
    }
    assert!(pair.agent(0, changed).is_err());
    assert_eq!(
        pair.agent(0, read(&sent)).unwrap_err().to_string(),
        UNAVAILABLE
    );
    let stranger = config::secret();
    pair.stores[1].execute(Request::Agent {
        credential: stranger.clone(),
        action: AgentOp::Register {
            name: "third chat".into(),
            provider: "test".into(),
        },
    })?;
    assert_eq!(
        pair.stores[1]
            .execute(Request::Agent {
                credential: stranger,
                action: read(&sent)
            })
            .unwrap_err()
            .to_string(),
        UNAVAILABLE
    );
    let expected = json!({"message_id":sent["message_id"], "sender":pair.agents[0], "format":"age-v1","armor":armor});
    assert_eq!(pair.agent(1, read(&sent))?, expected);
    assert_eq!(pair.agent(1, read(&sent))?, expected);
    let inbox = pair.agent(1, AgentOp::Inbox)?;
    let messages: Vec<_> = inbox
        .as_array()
        .unwrap()
        .iter()
        .filter(|m| m["id"] == sent["message_id"])
        .collect();
    assert_eq!(messages.len(), 1);
    assert_eq!(messages[0]["acknowledged"], false);
    assert_eq!(messages[0]["text"], "");
    assert_eq!(messages[0]["files"], json!([good]));
    assert!(messages[0].get("attachments").is_none());
    pair.policy(false);
    pair.pump();
    assert_eq!(
        pair.agent(1, read(&sent)).unwrap_err().to_string(),
        UNAVAILABLE
    );
    pair.policy(true);
    pair.pump();
    assert_eq!(pair.agent(1, read(&sent))?, expected);
    // Age just the received handoff to the recipient's current logical time.
    assert_eq!(
        pair.stores[1].db.execute(
            "UPDATE messages SET payload=json_set(payload,'$.created_at',floor-?2,'$.expires_at',floor)
             FROM request_clock WHERE singleton=1 AND messages.id=?1",
            params![sent["message_id"].as_str().unwrap(), EXCHANGE_TTL_SECONDS],
        )?,
        1
    );
    assert_eq!(
        pair.agent(1, read(&sent)).unwrap_err().to_string(),
        UNAVAILABLE
    );
    Ok(())
}

#[tokio::test]
async fn secret_read_respects_the_relay_queue_head() -> Result<()> {
    let mut pair = Pair::new().await;
    let recipient = pair.agents[1].clone();
    let armor = age::encrypt_and_armor(&age::x25519::Identity::generate().to_public(), b"fixture")?;
    let send = || AgentOp::RequestReply {
        recipient: recipient.clone(),
        request_id: Uuid::now_v7().to_string(),
        text: String::new(),
        files: vec![FilePart {
            name: FILENAME.into(),
            media_type: MEDIA_TYPE.into(),
            data_base64: STANDARD.encode(&armor),
        }],
        file_ids: vec![],
    };
    let first = pair.agent(0, send())?["message_id"]
        .as_str()
        .unwrap()
        .to_owned();
    let next = pair.agent(0, send())?["message_id"]
        .as_str()
        .unwrap()
        .to_owned();
    pair.pump();
    let read = AgentOp::SecretRead { message_id: next };
    assert_eq!(
        pair.agent(1, read.clone()).unwrap_err().to_string(),
        UNAVAILABLE
    );
    pair.agent(
        1,
        AgentOp::RelayRespond {
            turn_id: first,
            request_id: Uuid::now_v7().to_string(),
            text: "done".into(),
            files: vec![],
            file_ids: vec![],
            outcome: RelayResponseKind::Complete,
        },
    )?;
    assert_eq!(pair.agent(1, read)?["armor"], armor);
    Ok(())
}