/
middleware.rs
273 lines (245 loc) · 9.77 KB
/
middleware.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::env;
use actix_web::http;
use actix_web::middleware::{Middleware, Started};
use actix_web::{HttpRequest, HttpResponse, Result};
use base64;
use protobuf;
use bldr_core;
use bldr_core::access_token::{BUILDER_ACCOUNT_ID, BUILDER_ACCOUNT_NAME};
use bldr_core::metrics::CounterMetric;
use hab_net::{ErrCode, NetError};
use oauth_client::types::OAuth2User;
use protocol;
use protocol::originsrv;
use protocol::Routable;
use db::models::account::*;
use hab_net::privilege::FeatureFlags;
use server::error;
use server::services::metrics::Counter;
use server::AppState;
lazy_static! {
static ref SESSION_DURATION: u32 = 1 * 24 * 60 * 60;
}
pub fn route_message<M, R>(req: &HttpRequest<AppState>, msg: &M) -> error::Result<R>
where
M: Routable,
R: protobuf::Message,
{
Counter::RouteMessage.increment();
// Route via Protobuf over HTTP
req.state()
.jobsrv
.rpc::<M, R>(msg)
.map_err(error::Error::BuilderCore)
}
// Optional Authentication - this middleware does not enforce authentication,
// but will insert a Session if a valid Bearer token is received
pub struct Authentication;
impl Middleware<AppState> for Authentication {
fn start(&self, req: &HttpRequest<AppState>) -> Result<Started> {
let hdr = match req.headers().get(http::header::AUTHORIZATION) {
Some(hdr) => hdr.to_str().unwrap(), // unwrap Ok
None => return Ok(Started::Done),
};
let hdr_components: Vec<&str> = hdr.split_whitespace().collect();
if (hdr_components.len() != 2) || (hdr_components[0] != "Bearer") {
return Ok(Started::Response(HttpResponse::Unauthorized().finish()));
}
let token = hdr_components[1];
let session = match authenticate(req, &token) {
Ok(session) => session,
Err(_) => return Ok(Started::Response(HttpResponse::Unauthorized().finish())),
};
req.extensions_mut().insert::<originsrv::Session>(session);
Ok(Started::Done)
}
}
fn authenticate(req: &HttpRequest<AppState>, token: &str) -> error::Result<originsrv::Session> {
// Test hook - always create a valid session
if env::var_os("HAB_FUNC_TEST").is_some() {
debug!(
"HAB_FUNC_TEST: {:?}; calling session_create_short_circuit",
env::var_os("HAB_FUNC_TEST")
);
return session_create_short_circuit(req, token);
};
let mut memcache = req.state().memcache.borrow_mut();
match memcache.get_session(token) {
Some(session) => {
trace!("Session {} Cache Hit!", token);
return Ok(session);
}
None => {
trace!("Session {} Cache Miss!", token);
if !bldr_core::access_token::is_access_token(token) {
// No token in cache and not a PAT - bail
return Err(error::Error::NetError(NetError::new(
ErrCode::BAD_TOKEN,
"net:auth:expired-token",
)));
}
// Pull the session out of the current token provided so we can validate
// it against the db's tokens
let mut session = bldr_core::access_token::validate_access_token(
&req.state().config.api.key_path,
token,
).map_err(|_| NetError::new(ErrCode::BAD_TOKEN, "net:auth:bad-token"))?;
if session.get_id() == BUILDER_ACCOUNT_ID {
trace!("Builder token identified");
session.set_name(BUILDER_ACCOUNT_NAME.to_owned());
memcache.set_session(token, &session, None);
return Ok(session);
}
// If we can't find a token in the cache, we need to round-trip to the
// db to see if we have a valid session token.
let conn = req.state().db.get_conn().map_err(error::Error::DbError)?;
match AccountToken::list(session.get_id(), &*conn).map_err(error::Error::DieselError) {
Ok(access_tokens) => {
assert!(access_tokens.len() <= 1); // Can only have max of 1 for now
match access_tokens.first() {
Some(access_token) => {
let new_token = access_token.token.clone();
if token.trim_right_matches('=') != new_token.trim_right_matches('=') {
// Token is valid but revoked or otherwise expired
return Err(error::Error::NetError(NetError::new(
ErrCode::BAD_TOKEN,
"net:auth:revoked-token",
)));
}
let account = Account::get_by_id(session.get_id(), &*conn)
.map_err(error::Error::DieselError)?;
session.set_name(account.name);
session.set_email(account.email);
memcache.set_session(&new_token, &session, None);
return Ok(session);
}
None => {
// We have no tokens in the database for this user
return Err(error::Error::NetError(NetError::new(
ErrCode::BAD_TOKEN,
"net:auth:revoked-token",
)));
}
}
}
Err(_) => {
// Failed to fetch tokens from the database for this user
return Err(error::Error::NetError(NetError::new(
ErrCode::BAD_TOKEN,
"net:auth:revoked-token",
)));
}
}
}
}
}
pub fn session_create_oauth(
req: &HttpRequest<AppState>,
oauth_token: &str,
user: &OAuth2User,
provider: &str,
) -> error::Result<originsrv::Session> {
let mut session = originsrv::Session::new();
let mut session_token = originsrv::SessionToken::new();
let conn = req.state().db.get_conn().map_err(error::Error::DbError)?;
let email = match user.email {
Some(ref email) => {
session.set_email(email.clone());
email
}
None => "",
};
match Account::find_or_create(&user.username, email, &*conn) {
Ok(account) => {
session_token.set_account_id(account.id as u64);
session_token.set_extern_id(user.id.to_string());
session_token.set_token(oauth_token.to_string().into_bytes());
match provider.parse::<originsrv::OAuthProvider>() {
Ok(p) => session_token.set_provider(p),
Err(e) => {
warn!(
"Error parsing oauth provider: provider={}, err={:?}",
provider, e
);
return Err(error::Error::NetError(NetError::new(
ErrCode::BUG,
"session_create_oauth:1",
)));
}
}
let encoded_token = encode_token(&session_token);
session.set_id(account.id as u64);
session.set_name(account.name);
session.set_token(encoded_token.clone());
session.set_flags(FeatureFlags::empty().bits());
session.set_oauth_token(oauth_token.to_owned());
debug!("issuing session, {:?}", session);
req.state().memcache.borrow_mut().set_session(
&session.get_token(),
&session,
Some(*SESSION_DURATION),
);
Ok(session)
}
Err(e) => {
error!("Failed to create session {}", e);
Err(e.into())
}
}
}
pub fn session_create_short_circuit(
req: &HttpRequest<AppState>,
token: &str,
) -> error::Result<originsrv::Session> {
let (user, provider) = match token.as_ref() {
"bobo" => (
OAuth2User {
id: "0".to_string(),
email: Some("bobo@example.com".to_string()),
username: "bobo".to_string(),
},
"GitHub",
),
"mystique" => (
OAuth2User {
id: "1".to_string(),
email: Some("mystique@example.com".to_string()),
username: "mystique".to_string(),
},
"GitHub",
),
"hank" => (
OAuth2User {
id: "2".to_string(),
email: Some("hank@example.com".to_string()),
username: "hank".to_string(),
},
"GitHub",
),
user => {
error!("Unexpected short circuit token {:?}", user);
return Err(error::Error::NetError(NetError::new(
ErrCode::BUG,
"net:session-short-circuit:unknown-token",
)));
}
};
session_create_oauth(req, token, &user, provider)
}
fn encode_token(token: &originsrv::SessionToken) -> String {
let bytes = protocol::message::encode(token).unwrap(); //Unwrap is safe
base64::encode(&bytes)
}