referrerpolicy=no-referrer-when-downgrade

cumulus_aura_authorizer_utils/
lib.rs

1// This file is part of Cumulus.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Shared AURA authorization types, signing payloads, and collator proofs.
19
20#![cfg_attr(not(feature = "std"), no_std)]
21
22extern crate alloc;
23
24use codec::{Decode, Encode, MaxEncodedLen};
25use jam_types::{Slot, WorkPackage};
26
27mod config;
28mod merkle;
29mod signing;
30mod token;
31mod work_package;
32
33pub use polkadot_parachain_primitives::primitives::Id as ParaId;
34
35/// Parachain work-item payload (§3.2). The PoV is carried in extrinsic 0.
36#[derive(Debug, Encode, Decode)]
37pub struct ParachainCandidate {
38	/// Parachain ID checked against the authorizer config.
39	pub para_id: ParaId,
40	/// Validation-code hash used by Refine to look up the PVF.
41	pub validation_code: polkadot_parachain_primitives::primitives::ValidationCodeHash,
42}
43
44pub use config::{AuthConfig, CandidateError, ConfigError};
45pub use merkle::{build_collator_proof, expected_siblings, CollatorProofError};
46pub use signing::{signable_work_package_hash, WORK_PACKAGE_SIGN_CTX};
47pub use token::{AuthToken, CollatorKey, CollatorSignature, TokenError};
48pub use work_package::WorkPackageBody;
49
50/// Signature verification for Collator keys.
51pub trait SignatureVerifier {
52	/// Whether `signature` is `key`'s signature over `payload`.
53	fn verify(key: &CollatorKey, signature: &CollatorSignature, payload: &[u8]) -> bool;
54}
55
56/// The collator authenticated by AURA for the work package.
57#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, MaxEncodedLen)]
58pub struct AuthTrace {
59	pub author_key: CollatorKey,
60}
61
62/// AURA authorization failed.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum AuthorizationError {
65	BadConfig(ConfigError),
66	BadToken(TokenError),
67}
68
69impl AuthTrace {
70	/// Validate the work items and AURA token, returning the author trace.
71	///
72	/// The caller must supply the configuration bound to the authorized code/config
73	/// combination and the slot from the host's trusted refinement context.
74	pub fn try_from_token<S: SignatureVerifier>(
75		config: &AuthConfig,
76		token: &AuthToken,
77		package: &WorkPackage,
78		slot: Slot,
79	) -> Result<Self, AuthorizationError> {
80		config.check_work_items(&package.items).map_err(AuthorizationError::BadConfig)?;
81
82		let collator_index = config.expected_collator_index(slot);
83		token
84			.check_proof(config, collator_index)
85			.map_err(AuthorizationError::BadToken)?;
86		token
87			.check_signature::<S>(signable_work_package_hash(package))
88			.map_err(AuthorizationError::BadToken)?;
89
90		Ok(Self { author_key: token.key })
91	}
92}
93
94#[cfg(test)]
95mod tests {
96	use super::*;
97	use alloc::vec;
98
99	// Check every argument without coupling these protocol tests to a signature scheme.
100	pub(crate) struct Verifier;
101	impl SignatureVerifier for Verifier {
102		fn verify(key: &CollatorKey, signature: &CollatorSignature, payload: &[u8]) -> bool {
103			key == &[2; 32] && &signature[..32] == payload && signature[32..] == [0; 32]
104		}
105	}
106
107	pub(crate) struct NeverVerify;
108	impl SignatureVerifier for NeverVerify {
109		fn verify(_: &CollatorKey, _: &CollatorSignature, _: &[u8]) -> bool {
110			panic!("signature verification must not run after an earlier failure")
111		}
112	}
113
114	pub(crate) fn fixture() -> (AuthConfig, AuthToken, WorkPackage) {
115		let package = WorkPackage {
116			authorization: Default::default(),
117			auth_code_host: 1,
118			authorizer: jam_types::Authorizer::any(),
119			context: jam_types::RefineContext {
120				anchor: Default::default(),
121				anchor_slot: 0,
122				state_root: Default::default(),
123				beefy_root: Default::default(),
124				lookup_anchor: Default::default(),
125				lookup_anchor_slot: 0,
126				lookup_anchor_state_root: Default::default(),
127				prerequisites: Default::default(),
128			},
129			items: Default::default(),
130		};
131
132		let (root, proof) =
133			build_collator_proof(&[[1; 32], [2; 32]], 1).expect("two collators form a valid set");
134
135		let hash = signing::SigningPayload::from(&package).hash();
136		let mut token = AuthToken { proof, key: [2; 32], signature: [0; 64] };
137		token.signature[..32].copy_from_slice(hash.as_bytes());
138
139		let config = AuthConfig {
140			para_ids: vec![],
141			parachain_service: 1,
142			collator_set_root: root,
143			collator_set_size: core::num::NonZero::new(2).expect("nonzero configuration"),
144			slot_duration: core::num::NonZero::new(2).expect("nonzero configuration"),
145		};
146
147		(config, token, package)
148	}
149
150	#[test]
151	fn try_from_token_bad_config_errors() {
152		let (mut config, token, package) = fixture();
153		config.para_ids.push(ParaId::new(0));
154
155		assert_eq!(
156			AuthTrace::try_from_token::<NeverVerify>(&config, &token, &package, 2),
157			Err(AuthorizationError::BadConfig(ConfigError::InvalidWorkItemCount))
158		);
159	}
160
161	#[test]
162	fn try_from_token_selected_collator_works() {
163		let (config, token, package) = fixture();
164
165		for slot in [2, 3, 6, 7] {
166			let expected = AuthTrace { author_key: token.key };
167
168			assert_eq!(
169				AuthTrace::try_from_token::<Verifier>(&config, &token, &package, slot)
170					.expect("valid token"),
171				expected
172			);
173		}
174	}
175
176	#[test]
177	fn try_from_token_wrong_slot_errors() {
178		let (config, token, package) = fixture();
179
180		assert!(matches!(
181			AuthTrace::try_from_token::<NeverVerify>(&config, &token, &package, 0),
182			Err(AuthorizationError::BadToken(TokenError::BadCollatorSetProof))
183		));
184	}
185
186	#[test]
187	fn try_from_token_invalid_proof_errors() {
188		let (config, mut token, package) = fixture();
189		token.proof.clear();
190
191		assert!(matches!(
192			AuthTrace::try_from_token::<NeverVerify>(&config, &token, &package, 2),
193			Err(AuthorizationError::BadToken(TokenError::BadCollatorSetProof))
194		));
195	}
196
197	#[test]
198	fn try_from_token_changed_package_errors() {
199		let (config, token, mut package) = fixture();
200		package.auth_code_host += 1;
201
202		assert!(matches!(
203			AuthTrace::try_from_token::<Verifier>(&config, &token, &package, 2),
204			Err(AuthorizationError::BadToken(TokenError::BadCollatorSignature))
205		));
206	}
207
208	#[test]
209	fn try_from_token_invalid_signature_errors() {
210		let (config, mut token, package) = fixture();
211		token.signature[63] ^= 1;
212
213		assert!(matches!(
214			AuthTrace::try_from_token::<Verifier>(&config, &token, &package, 2),
215			Err(AuthorizationError::BadToken(TokenError::BadCollatorSignature))
216		));
217	}
218}