Skip to content

Commit 5a455cd

Browse files
Move keys to configuration file
1 parent 2537ac7 commit 5a455cd

File tree

6 files changed

+50
-25
lines changed

6 files changed

+50
-25
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

site/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ hex = "0.3.2"
2424
regex = "1"
2525
lazy_static = "1"
2626
reqwest = "0.8"
27+
toml = "0.4"
2728

2829
[dependencies.collector]
2930
path = "../collector"

site/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ extern crate regex;
3333
#[macro_use]
3434
extern crate lazy_static;
3535
extern crate reqwest;
36+
extern crate toml;
3637

3738
#[derive(Fail, Debug)]
3839
#[fail(display = "command failed: {}", command)]

site/src/load.rs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use failure::SyncFailure;
2020
use rust_sysroot;
2121
use rust_sysroot::git::Commit as GitCommit;
2222
use chrono::{Duration, Utc};
23+
use toml;
2324

2425
use util;
2526
use git;
@@ -63,6 +64,18 @@ impl Persistent {
6364
}
6465
}
6566

67+
#[derive(Debug, Default, Deserialize)]
68+
pub struct Keys {
69+
pub github: Option<String>,
70+
pub secret: Option<String>,
71+
}
72+
73+
#[derive(Debug, Deserialize)]
74+
pub struct Config {
75+
pub users: Vec<String>,
76+
pub keys: Keys,
77+
}
78+
6679
#[derive(Debug)]
6780
pub struct InputData {
6881
/// A set containing all crate names of the bootstrap kind.
@@ -83,6 +96,8 @@ pub struct InputData {
8396
pub commits: Vec<GitCommit>,
8497

8598
pub persistent: Mutex<Persistent>,
99+
100+
pub config: Config,
86101
}
87102

88103
impl InputData {
@@ -168,12 +183,22 @@ impl InputData {
168183
info!("{} skipped files", skipped);
169184
info!("{} measured", data.len());
170185

171-
InputData::new(data, artifact_data)
186+
let config = if let Ok(s) = fs::read_to_string("site-config.toml") {
187+
toml::from_str(&s)?
188+
} else {
189+
Config {
190+
users: Vec::new(),
191+
keys: Keys::default(),
192+
}
193+
};
194+
195+
InputData::new(data, artifact_data, config)
172196
}
173197

174198
pub fn new(
175199
data: BTreeMap<Commit, CommitData>,
176200
artifact_data: BTreeMap<String, ArtifactData>,
201+
config: Config,
177202
) -> Result<InputData, Error> {
178203
let mut last_date = None;
179204
let mut crate_list = BTreeSet::new();
@@ -210,6 +235,7 @@ impl InputData {
210235
artifact_data,
211236
commits,
212237
persistent: Mutex::new(Persistent::load()),
238+
config,
213239
})
214240
}
215241

site/src/main.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,5 @@ fn main() {
2424
.unwrap_or(2346);
2525
println!("Starting server with port={:?}", port);
2626

27-
let key = env::var("PERF_SECRET_KEY").unwrap_or(String::from("QuiteSecret"));
28-
29-
server::start(data, port, key);
27+
server::start(data, port);
3028
}

site/src/server.rs

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ use std::path::Path;
1616
use std::net::SocketAddr;
1717
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
1818
use std::cmp::Ordering;
19-
use std::env;
2019

2120
use serde::Serialize;
2221
use serde::de::DeserializeOwned;
@@ -45,7 +44,7 @@ use util::{self, get_repo_path};
4544
pub use api::{self, github, status, nll_dashboard, dashboard, data, days, graph, info, CommitResponse, ServerResult};
4645
use collector::{Date, Run, version_supports_incremental};
4746
use collector::api::collected;
48-
use load::{CommitData, InputData};
47+
use load::{Config, CommitData, InputData};
4948
use antidote::RwLock;
5049
use load::CurrentState;
5150

@@ -510,16 +509,17 @@ lazy_static! {
510509
static ref BODY_TRY_COMMIT: Regex = Regex::new(r#"(?:\b|^)@rust-timer\s+build\s+(\w+)(?:\b|$)"#).unwrap();
511510
}
512511

513-
pub fn post_comment(request: &github::Request, body: &str) -> ServerResult<()> {
514-
println!("post comment: {}", body);
512+
pub fn post_comment(cfg: &Config, request: &github::Request, body: &str) -> ServerResult<()> {
513+
let timer_token = cfg.keys.github.clone().expect("needs rust-timer token");
515514
let client = reqwest::Client::new();
516515
let mut req = client.post(&request.issue.comments_url);
517516
req
518517
.json(&github::PostComment {
519518
body: body.to_owned(),
520519
})
521520
.header(UserAgent::new("perf-rust-lang-org-server"))
522-
.basic_auth("rust-timer", Some(env::var("RUST_TIMER_GH_TOKEN").unwrap()));
521+
.basic_auth("rust-timer", Some(timer_token));
522+
523523
let res = req.send();
524524
match res {
525525
Ok(_) => { }
@@ -531,15 +531,14 @@ pub fn post_comment(request: &github::Request, body: &str) -> ServerResult<()> {
531531
}
532532

533533
pub fn handle_github(request: github::Request, data: &InputData) -> ServerResult<github::Response> {
534-
println!("handle_github({:?})", request);
535534
if !request.comment.body.contains("@rust-timer ") {
536535
return Ok(github::Response);
537536
}
538537

539-
// FIXME: Better auth / config
540-
if request.comment.author_association != github::Association::Owner {
541-
post_comment(&request,
542-
"Only owners of the repository are permitted to issue commands to rust-timer.")?;
538+
if request.comment.author_association != github::Association::Owner ||
539+
data.config.users.contains(&request.comment.user.login) {
540+
post_comment(&data.config, &request,
541+
"Insufficient permissions to issue commands to rust-timer.")?;
543542
return Ok(github::Response);
544543
}
545544

@@ -548,7 +547,7 @@ pub fn handle_github(request: github::Request, data: &InputData) -> ServerResult
548547
if let Some(captures) = BODY_TRY_COMMIT.captures(&body) {
549548
if let Some(commit) = captures.get(1).map(|c| c.as_str()) {
550549
if commit.len() != 40 {
551-
post_comment(&request, "Please provide the full 40 character commit hash.")?;
550+
post_comment(&data.config, &request, "Please provide the full 40 character commit hash.")?;
552551
return Ok(github::Response);
553552
}
554553
let client = reqwest::Client::new();
@@ -557,7 +556,7 @@ pub fn handle_github(request: github::Request, data: &InputData) -> ServerResult
557556
.send().map_err(|_| String::from("cannot get commit"))?
558557
.json().map_err(|_| String::from("cannot deserialize commit"))?;
559558
if commit_response.parents.len() != 1 {
560-
post_comment(&request,
559+
post_comment(&data.config, &request,
561560
&format!("Bors try commit {} unexpectedly has {} parents.",
562561
commit_response.sha, commit_response.parents.len()))?;
563562
return Ok(github::Response);
@@ -569,7 +568,7 @@ pub fn handle_github(request: github::Request, data: &InputData) -> ServerResult
569568
}
570569
persistent.write().expect("successful encode");
571570
}
572-
post_comment(&request,
571+
post_comment(&data.config, &request,
573572
&format!("Success: Queued {} with parent {}, [comparison URL]({}).",
574573
commit_response.sha, commit_response.parents[0].sha,
575574
format!("https://perf.rust-lang.org/compare.html?start={}&end={}",
@@ -622,7 +621,6 @@ struct Server {
622621
data: Arc<RwLock<InputData>>,
623622
pool: CpuPool,
624623
updating: Arc<AtomicBool>,
625-
key: String,
626624
}
627625

628626
macro_rules! check_http_method {
@@ -667,7 +665,8 @@ impl Server {
667665

668666
fn check_auth(&self, req: &Request) -> bool {
669667
if let Some(auth) = req.headers().get::<Authorization<Bearer>>() {
670-
if auth.0.token == self.key {
668+
let data = self.data.read();
669+
if auth.0.token == *data.config.keys.secret.as_ref().unwrap() {
671670
return true;
672671
}
673672
}
@@ -741,10 +740,10 @@ impl Server {
741740
futures::future::ok::<_, <Self as Service>::Error>(acc)
742741
})
743742
.map(move |body| {
744-
if gh && !verify_gh_sig(gh_header.unwrap(), &body).unwrap_or(false) {
743+
let data = data.read();
744+
if gh && !verify_gh_sig(&data.config, gh_header.unwrap(), &body).unwrap_or(false) {
745745
return Response::new().with_status(StatusCode::Unauthorized);
746746
}
747-
let data = data.read();
748747
let body: D = match serde_json::from_slice(&body) {
749748
Ok(d) => d,
750749
Err(err) => {
@@ -934,10 +933,10 @@ impl Service for Server {
934933
}
935934
}
936935

937-
fn verify_gh_sig(header: HubSignature, body: &[u8]) -> Option<bool> {
936+
fn verify_gh_sig(cfg: &Config, header: HubSignature, body: &[u8]) -> Option<bool> {
938937
let key = hmac::VerificationKey::new(
939938
&digest::SHA1,
940-
env::var("PERF_SECRET_KEY").unwrap().as_bytes(),
939+
cfg.keys.secret.as_ref().unwrap().as_bytes(),
941940
);
942941
let sha = header.0.get(5..)?; // strip sha1=
943942
let sha = hex::decode(sha).ok()?;
@@ -948,12 +947,11 @@ fn verify_gh_sig(header: HubSignature, body: &[u8]) -> Option<bool> {
948947
Some(false)
949948
}
950949

951-
pub fn start(data: InputData, port: u16, key: String) {
950+
pub fn start(data: InputData, port: u16) {
952951
let server = Arc::new(Server {
953952
data: Arc::new(RwLock::new(data)),
954953
pool: CpuPool::new_num_cpus(),
955954
updating: Arc::new(AtomicBool::new(false)),
956-
key,
957955
});
958956
let mut server_address: SocketAddr = "0.0.0.0:2346".parse().unwrap();
959957
server_address.set_port(port);

0 commit comments

Comments
 (0)