-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feat(webrtc): certificate, can now be managed like node secret key #12621
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gab8i
wants to merge
2
commits into
master
Choose a base branch
from
gab_webrtc_certhash
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| title: 'feat(webrtc): certificate, can now be managed like node secret key' | ||
| doc: | ||
| - audience: Todo | ||
| description: |- | ||
| # Description | ||
|
|
||
| The WebRTC certificate, which determines the node's WebRTC `/certhash`, can now be managed like the node secret key. | ||
|
|
||
| ## Integration | ||
|
|
||
| A new `key generate-webrtc-certificate` subcommand generates a certificate, writes it to a file (or stdout) and prints the corresponding certhash to stderr, mirroring `key generate-node-key`. | ||
|
|
||
| Additionally, `--experimental-webrtc` now accepts an optional certificate file path (`--experimental-webrtc=<CERT_FILE>`): the certificate is loaded from the file if it exists, or generated and persisted there otherwise. | ||
|
|
||
| Without a path the behavior is unchanged, the certificate is loaded from or generated at `<base_path>/chains/<chain_id>/network/webrtc_certificate`. | ||
| crates: | ||
| - name: sc-cli | ||
| bump: major | ||
| - name: sc-network | ||
| bump: major |
159 changes: 159 additions & 0 deletions
159
substrate/client/cli/src/commands/generate_webrtc_certificate.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| // This file is part of Substrate. | ||
|
|
||
| // Copyright (C) Parity Technologies (UK) Ltd. | ||
| // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 | ||
|
|
||
| // This program is free software: you can redistribute it and/or modify | ||
| // it under the terms of the GNU General Public License as published by | ||
| // the Free Software Foundation, either version 3 of the License, or | ||
| // (at your option) any later version. | ||
|
|
||
| // This program is distributed in the hope that it will be useful, | ||
| // but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| // GNU General Public License for more details. | ||
|
|
||
| // You should have received a copy of the GNU General Public License | ||
| // along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
|
|
||
| //! Implementation of the `generate-webrtc-certificate` subcommand | ||
|
|
||
| use crate::{build_network_key_dir_or_default, Error}; | ||
| use clap::Parser; | ||
| use sc_network::webrtc::{ | ||
| certhash, encode_certificate, generate_certificate, WEBRTC_CERTIFICATE_FILE, | ||
| }; | ||
| use sc_service::BasePath; | ||
| use std::{ | ||
| fs, | ||
| io::{self, Write}, | ||
| path::PathBuf, | ||
| }; | ||
|
|
||
| /// The `generate-webrtc-certificate` command | ||
| #[derive(Debug, Clone, Parser)] | ||
| #[command( | ||
| name = "generate-webrtc-certificate", | ||
| about = "Generate a WebRTC DTLS certificate, write it to a file or stdout \ | ||
| and write the corresponding certhash to stderr" | ||
| )] | ||
| pub struct GenerateWebRtcCertificateCmd { | ||
| /// Name of file to save the certificate to. | ||
| /// If not given, the certificate is printed to stdout. | ||
| #[arg(long)] | ||
| file: Option<PathBuf>, | ||
|
|
||
| /// The output is in raw binary format. | ||
| /// If not given, the output is written as an hex encoded string. | ||
| #[arg(long)] | ||
| bin: bool, | ||
|
|
||
| /// Specify the chain specification. | ||
| /// | ||
| /// It can be any of the predefined chains like dev, local, staging, polkadot, kusama. | ||
| #[arg(long, value_name = "CHAIN_SPEC")] | ||
| pub chain: Option<String>, | ||
|
|
||
| /// A directory where the certificate should be saved. If a certificate already | ||
| /// exists in the directory, it won't be overwritten. | ||
| #[arg(long, conflicts_with_all = ["file", "default_base_path"])] | ||
| base_path: Option<PathBuf>, | ||
|
|
||
| /// Save the certificate in the default directory. If a certificate already | ||
| /// exists in the directory, it won't be overwritten. | ||
| #[arg(long, conflicts_with_all = ["base_path", "file"])] | ||
| default_base_path: bool, | ||
| } | ||
|
|
||
| impl GenerateWebRtcCertificateCmd { | ||
| /// Run the command | ||
| pub fn run(&self, chain_spec_id: &str, executable_name: &String) -> Result<(), Error> { | ||
| let certificate = generate_certificate().map_err(Error::Input)?; | ||
|
|
||
| let encoded = encode_certificate(&certificate); | ||
| let file_data = | ||
| if self.bin { encoded } else { array_bytes::bytes2hex("", &encoded).into_bytes() }; | ||
|
|
||
| match (&self.file, &self.base_path, self.default_base_path) { | ||
| (Some(file), None, false) => fs::write(file, file_data)?, | ||
| (None, Some(_), false) | (None, None, true) => { | ||
| let network_path = build_network_key_dir_or_default( | ||
| self.base_path.clone().map(BasePath::new), | ||
| chain_spec_id, | ||
| executable_name, | ||
| ); | ||
|
|
||
| fs::create_dir_all(network_path.as_path())?; | ||
|
|
||
| let certificate_path = network_path.join(WEBRTC_CERTIFICATE_FILE); | ||
| if certificate_path.exists() { | ||
| eprintln!( | ||
| "Skip generation, a certificate already exists in {:?}", | ||
| certificate_path | ||
| ); | ||
| return Err(Error::KeyAlreadyExistsInPath(certificate_path)); | ||
| } else { | ||
| eprintln!("Generating certificate in {:?}", certificate_path); | ||
| fs::write(certificate_path, file_data)? | ||
| } | ||
| }, | ||
| (None, None, false) => io::stdout().lock().write_all(&file_data)?, | ||
| (_, _, _) => { | ||
| // This should not happen, arguments are marked as mutually exclusive. | ||
| return Err(Error::Input("Mutually exclusive arguments provided".into())); | ||
| }, | ||
| } | ||
|
|
||
| eprintln!("{}", certhash(&certificate)); | ||
|
|
||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| pub mod tests { | ||
| use crate::DEFAULT_NETWORK_CONFIG_PATH; | ||
|
|
||
| use super::*; | ||
| use sc_network::webrtc::decode_certificate; | ||
| use std::io::Read; | ||
| use tempfile::Builder; | ||
|
|
||
| #[test] | ||
| fn generate_webrtc_certificate_file() { | ||
| let mut file = Builder::new().prefix("certfile").tempfile().unwrap(); | ||
| let file_path = file.path().display().to_string(); | ||
| let generate = GenerateWebRtcCertificateCmd::parse_from(&[ | ||
| "generate-webrtc-certificate", | ||
| "--file", | ||
| &file_path, | ||
| ]); | ||
| assert!(generate.run("test", &String::from("test")).is_ok()); | ||
| let mut buf = String::new(); | ||
| assert!(file.read_to_string(&mut buf).is_ok()); | ||
| assert!(decode_certificate(buf.as_bytes()).is_ok()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn generate_webrtc_certificate_base_path() { | ||
| let base_dir = Builder::new().prefix("certfile").tempdir().unwrap(); | ||
| let certificate_path = base_dir | ||
| .path() | ||
| .join("chains/test_id/") | ||
| .join(DEFAULT_NETWORK_CONFIG_PATH) | ||
| .join(WEBRTC_CERTIFICATE_FILE); | ||
| let base_path = base_dir.path().display().to_string(); | ||
| let generate = GenerateWebRtcCertificateCmd::parse_from(&[ | ||
| "generate-webrtc-certificate", | ||
| "--base-path", | ||
| &base_path, | ||
| ]); | ||
| assert!(generate.run("test_id", &String::from("test")).is_ok()); | ||
| let buf = fs::read_to_string(certificate_path.as_path()).unwrap(); | ||
| assert!(decode_certificate(buf.as_bytes()).is_ok()); | ||
|
|
||
| assert!(generate.run("test_id", &String::from("test")).is_err()); | ||
| let new_buf = fs::read_to_string(certificate_path).unwrap(); | ||
| assert_eq!(new_buf, buf); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -78,8 +78,16 @@ pub struct NetworkParams { | |
| /// | ||
| /// Without this enabled, WebRTC addresses specified in `listen_addr` | ||
| /// will be skipped. Only works on litep2p network backend. | ||
| #[arg(long)] | ||
| pub experimental_webrtc: bool, | ||
| /// | ||
| /// Optionally takes a path to the WebRTC DTLS certificate file | ||
| /// (`--experimental-webrtc=<CERT_FILE>`), which determines the node's `/certhash`. | ||
| /// The certificate is loaded from the file if it exists, otherwise a new certificate | ||
| /// is generated and persisted there. It can be generated ahead of time with the | ||
| /// `key generate-webrtc-certificate` subcommand, which accepts both hex and raw | ||
| /// binary formats. When no path is given, the certificate is loaded from or | ||
| /// generated at `<base_path>/chains/<chain_id>/network/webrtc_certificate`. | ||
| #[arg(long, value_name = "CERT_FILE", num_args = 0..=1, require_equals = true)] | ||
| pub experimental_webrtc: Option<Option<PathBuf>>, | ||
|
Comment on lines
+82
to
+90
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would add a dedicated |
||
|
|
||
| /// Specify p2p protocol TCP port. | ||
| #[arg(long, value_name = "PORT", conflicts_with_all = &[ "listen_addr" ])] | ||
|
|
@@ -283,7 +291,8 @@ impl NetworkParams { | |
| }, | ||
| default_peers_set_num_full: self.in_peers + self.out_peers, | ||
| listen_addresses, | ||
| experimental_webrtc: self.experimental_webrtc, | ||
| experimental_webrtc: self.experimental_webrtc.is_some(), | ||
| webrtc_certificate_file: self.experimental_webrtc.clone().flatten(), | ||
| public_addresses, | ||
| node_key, | ||
| node_name: node_name.to_string(), | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IMO we should drop hexifying completely and store binary data only.