Skip to main content

cast/cmd/tempo/zone/
auth.rs

1//! Zone RPC auth wire format, mirrored from tempoxyz/zones at a1c15e9f.
2//!
3//! Source: <https://github.com/tempoxyz/zones/tree/a1c15e9f002a5efd150f56c5076fb35519288396/crates/rpc/src/auth/token.rs>
4//!
5//! The signature is a Tempo transaction signature over the token digest. tempoxyz/tempo's zone
6//! RPC accepts configurable account (`0x05`) signatures from #9045; see `authenticate_token` in
7//! <https://github.com/tempoxyz/tempo/blob/c8b89f9b6d9f011a8a277ab431183b2b105c4af7/crates/zones/rpc/src/server.rs>.
8
9use super::signer::ZoneSigner;
10use alloy_primitives::{B256, hex, keccak256};
11use eyre::Result;
12use std::time::{SystemTime, UNIX_EPOCH};
13
14pub(super) const HEADER: &str = "x-authorization-token";
15
16/// Sign a short-lived token as `signer`, see [`ZoneSigner::sign_token_digest`].
17pub(super) async fn sign_token(signer: &ZoneSigner, zone_id: u32, chain_id: u64) -> Result<String> {
18    let issued = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
19    let (fields, digest) = token_fields(zone_id, chain_id, issued, issued + 600);
20    let mut token = signer.sign_token_digest(digest).await?.to_vec();
21    token.extend_from_slice(&fields);
22    Ok(hex::encode(token))
23}
24
25fn token_fields(zone_id: u32, chain_id: u64, issued: u64, expires: u64) -> ([u8; 29], B256) {
26    let mut message = [0u8; 61];
27    message[..12].copy_from_slice(b"TempoZoneRPC");
28    message[33..37].copy_from_slice(&zone_id.to_be_bytes());
29    message[37..45].copy_from_slice(&chain_id.to_be_bytes());
30    message[45..53].copy_from_slice(&issued.to_be_bytes());
31    message[53..61].copy_from_slice(&expires.to_be_bytes());
32    (message[32..].try_into().unwrap(), keccak256(message))
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38    use alloy_primitives::{Signature, b256};
39    use alloy_signer::Signer;
40    use alloy_signer_local::PrivateKeySigner;
41    use foundry_common::tempo::configurable_account::{
42        ConfigurableAccountSigner, single_owner_config,
43    };
44    use foundry_wallets::WalletSigner;
45    use tempo_primitives::transaction::{
46        ConfigurableAccountSignature, PrimitiveSignature, tt_signature::TempoSignature,
47    };
48
49    #[tokio::test]
50    async fn token_recovers_wallet_from_raw_digest() {
51        let signer = PrivateKeySigner::random();
52        let address = signer.address();
53        let signer = ZoneSigner::Wallet(WalletSigner::Local(signer));
54        let token = hex::decode(sign_token(&signer, 42, 1337).await.unwrap()).unwrap();
55        assert_eq!(token.len(), 94);
56        let fields = &token[65..];
57        assert_eq!(&fields[..13], &hex::decode("000000002a0000000000000539").unwrap());
58        let issued = u64::from_be_bytes(fields[13..21].try_into().unwrap());
59        let expires = u64::from_be_bytes(fields[21..29].try_into().unwrap());
60        assert_eq!(expires - issued, 600);
61        let (_, digest) = token_fields(42, 1337, issued, expires);
62        let signature = Signature::try_from(&token[..65]).unwrap();
63        assert_eq!(signature.recover_address_from_prehash(&digest).unwrap(), address);
64    }
65
66    /// Repeats the signature checks of tempoxyz/tempo's zone RPC at c8b89f9 (`authenticate_token`
67    /// in crates/zones/rpc/src/server.rs) on a configurable account token, with Tempo's own
68    /// types, and pins the owners' digest.
69    #[tokio::test]
70    async fn configurable_account_token_matches_zone_rpc_checks() {
71        let owner = PrivateKeySigner::random();
72        let config = single_owner_config(owner.address());
73        let account = config.derive_account().unwrap();
74        let signer = ZoneSigner::ConfigurableAccount(
75            ConfigurableAccountSigner::new(
76                account,
77                config.clone(),
78                [WalletSigner::Local(owner.clone()).into()],
79                "",
80            )
81            .unwrap(),
82        );
83        let token = hex::decode(sign_token(&signer, 42, 1337).await.unwrap()).unwrap();
84
85        // `<signature><29 fixed bytes>`, with a `0x05` signature.
86        let (signature, fields) = token.split_at(token.len() - 29);
87        assert_eq!(signature[0], 0x05);
88        let issued = u64::from_be_bytes(fields[13..21].try_into().unwrap());
89        let (expected_fields, digest) = token_fields(42, 1337, issued, issued + 600);
90        assert_eq!(fields, expected_fields);
91
92        let parsed = TempoSignature::from_bytes(signature).unwrap();
93        assert!(!parsed.is_legacy_keychain());
94        assert_eq!(parsed.recover_signer(&digest).unwrap(), account);
95        let TempoSignature::ConfigurableAccount(approval) = &parsed else {
96            panic!("a configurable account signature")
97        };
98        // Unregistered, the owners derive the account; registered, they match its commitment.
99        approval.validate_account_commitment(B256::ZERO).unwrap();
100        approval.validate_account_commitment(config.commitment().unwrap()).unwrap();
101        assert!(approval.validate_account_commitment(B256::repeat_byte(1)).is_err());
102
103        // The owner approves keccak256(domain || token digest || account || version).
104        let mut preimage = b"tempo:configurable-account:signature".to_vec();
105        preimage.extend_from_slice(digest.as_slice());
106        preimage.extend_from_slice(account.as_slice());
107        preimage.extend_from_slice(&0u64.to_be_bytes());
108        let approval = owner.sign_hash(&keccak256(preimage)).await.unwrap();
109        let expected = ConfigurableAccountSignature::try_new(
110            account,
111            config,
112            vec![PrimitiveSignature::Secp256k1(approval)],
113        )
114        .unwrap();
115        assert_eq!(signature, TempoSignature::ConfigurableAccount(expected).to_bytes().as_ref());
116    }
117
118    #[test]
119    fn matches_zones_wire_vector() {
120        let (fields, digest) = token_fields(
121            0x0102_0304,
122            0x0506_0708_090a_0b0c,
123            0x0d0e_0f10_1112_1314,
124            0x1516_1718_191a_1b1c,
125        );
126        assert_eq!(
127            hex::encode(fields),
128            "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c"
129        );
130        assert_eq!(
131            digest,
132            b256!("0xf827387a933f40dfedece81ba4933feaef89e98a269f52f4f54dda2f1dac4171")
133        );
134    }
135}