-
Notifications
You must be signed in to change notification settings - Fork 139
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
API Authentication #285
+489
−18
Merged
API Authentication #285
Changes from 10 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
95ebf57
Add a model for external apps
elegaanz ac4bca3
Add an API endpoint to register apps
elegaanz c845551
Add an ApiToken model, and an endpoint to get one
elegaanz 2a98251
Disable CSRF for the whole API
elegaanz 056f4fd
impl FromRequest for ApiToken
elegaanz 3629710
Document API authentication and apps API
elegaanz 4249f5c
New request guard: Authorization<Action, Scope>
elegaanz 21f4c9d
AppEndpoint.name is required for both the client and server
elegaanz a1a062d
Make it impossible to know if an username is used or not with the API
elegaanz 8e4ab95
Use the full URL to refer to the Apps API
trinity-1686a 1a2ad8d
Use PhantomData intead of two Options useless for Authorization
elegaanz 827026a
ApiToken: rename what to scope
elegaanz 0006bdf
Make Authorization optional for read routes
elegaanz 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 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 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 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,2 @@ | ||
-- This file should undo anything in `up.sql` | ||
DROP TABLE apps; |
This file contains 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,10 @@ | ||
-- Your SQL goes here | ||
CREATE TABLE apps ( | ||
id SERIAL PRIMARY KEY, | ||
name TEXT NOT NULL DEFAULT '', | ||
client_id TEXT NOT NULL, | ||
client_secret TEXT NOT NULL, | ||
redirect_uri TEXT, | ||
website TEXT, | ||
creation_date TIMESTAMP NOT NULL DEFAULT now() | ||
); |
2 changes: 2 additions & 0 deletions
2
migrations/postgres/2018-10-21-163227_create_api_token/down.sql
This file contains 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,2 @@ | ||
-- This file should undo anything in `up.sql` | ||
DROP TABLE api_tokens; |
9 changes: 9 additions & 0 deletions
9
migrations/postgres/2018-10-21-163227_create_api_token/up.sql
This file contains 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,9 @@ | ||
-- Your SQL goes here | ||
CREATE TABLE api_tokens ( | ||
id SERIAL PRIMARY KEY, | ||
creation_date TIMESTAMP NOT NULL DEFAULT now(), | ||
value TEXT NOT NULL, | ||
scopes TEXT NOT NULL, | ||
app_id INTEGER NOT NULL REFERENCES apps(id) ON DELETE CASCADE, | ||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE | ||
) |
This file contains 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,2 @@ | ||
-- This file should undo anything in `up.sql` | ||
DROP TABLE apps; |
This file contains 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,10 @@ | ||
-- Your SQL goes here | ||
CREATE TABLE apps ( | ||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | ||
name TEXT NOT NULL DEFAULT '', | ||
client_id TEXT NOT NULL, | ||
client_secret TEXT NOT NULL, | ||
redirect_uri TEXT, | ||
website TEXT, | ||
creation_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP | ||
); |
2 changes: 2 additions & 0 deletions
2
migrations/sqlite/2018-10-21-163241_create_api_token/down.sql
This file contains 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,2 @@ | ||
-- This file should undo anything in `up.sql` | ||
DROP TABLE api_tokens; |
This file contains 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,9 @@ | ||
-- Your SQL goes here | ||
CREATE TABLE api_tokens ( | ||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | ||
creation_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
value TEXT NOT NULL, | ||
scopes TEXT NOT NULL, | ||
app_id INTEGER NOT NULL REFERENCES apps(id) ON DELETE CASCADE, | ||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE | ||
) |
This file contains 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,13 @@ | ||
use canapi::Endpoint; | ||
|
||
#[derive(Clone, Default, Serialize, Deserialize)] | ||
pub struct AppEndpoint { | ||
pub id: Option<i32>, | ||
pub name: String, | ||
pub website: Option<String>, | ||
pub redirect_uri: Option<String>, | ||
pub client_id: Option<String>, | ||
pub client_secret: Option<String>, | ||
} | ||
|
||
api!("/api/v1/apps" => AppEndpoint); |
This file contains 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 |
---|---|---|
|
@@ -15,4 +15,5 @@ macro_rules! api { | |
}; | ||
} | ||
|
||
pub mod apps; | ||
pub mod posts; |
This file contains 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 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,88 @@ | ||
use chrono::NaiveDateTime; | ||
use diesel::{self, ExpressionMethods, QueryDsl, RunQueryDsl}; | ||
use rocket::{ | ||
Outcome, | ||
http::Status, | ||
request::{self, FromRequest, Request} | ||
}; | ||
|
||
use db_conn::DbConn; | ||
use schema::api_tokens; | ||
|
||
#[derive(Clone, Queryable)] | ||
pub struct ApiToken { | ||
pub id: i32, | ||
pub creation_date: NaiveDateTime, | ||
pub value: String, | ||
|
||
/// Scopes, separated by + | ||
/// Global scopes are read and write | ||
/// and both can be limited to an endpoint by affixing them with :ENDPOINT | ||
/// | ||
/// Examples : | ||
/// | ||
/// read | ||
/// read+write | ||
/// read:posts | ||
/// read:posts+write:posts | ||
pub scopes: String, | ||
pub app_id: i32, | ||
pub user_id: i32, | ||
} | ||
|
||
#[derive(Insertable)] | ||
#[table_name = "api_tokens"] | ||
pub struct NewApiToken { | ||
pub value: String, | ||
pub scopes: String, | ||
pub app_id: i32, | ||
pub user_id: i32, | ||
} | ||
|
||
impl ApiToken { | ||
get!(api_tokens); | ||
insert!(api_tokens, NewApiToken); | ||
find_by!(api_tokens, find_by_value, value as String); | ||
|
||
pub fn can(&self, what: &'static str, scope: &'static str) -> bool { | ||
let full_scope = what.to_owned() + ":" + scope; | ||
for s in self.scopes.split('+') { | ||
if s == what || s == full_scope { | ||
return true | ||
} | ||
} | ||
false | ||
} | ||
|
||
pub fn can_read(&self, what: &'static str) -> bool { | ||
self.can("read", what) | ||
} | ||
trinity-1686a marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
pub fn can_write(&self, what: &'static str) -> bool { | ||
self.can("write", what) | ||
} | ||
trinity-1686a marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
impl<'a, 'r> FromRequest<'a, 'r> for ApiToken { | ||
type Error = (); | ||
|
||
fn from_request(request: &'a Request<'r>) -> request::Outcome<ApiToken, ()> { | ||
let headers: Vec<_> = request.headers().get("Authorization").collect(); | ||
if headers.len() != 1 { | ||
return Outcome::Failure((Status::BadRequest, ())); | ||
} | ||
|
||
let mut parsed_header = headers[0].split(' '); | ||
let auth_type = parsed_header.next().expect("Expect a token type"); | ||
let val = parsed_header.next().expect("Expect a token value"); | ||
|
||
if auth_type == "Bearer" { | ||
let conn = request.guard::<DbConn>().expect("Couldn't connect to DB"); | ||
if let Some(token) = ApiToken::find_by_value(&*conn, val.to_string()) { | ||
return Outcome::Success(token); | ||
} | ||
} | ||
|
||
return Outcome::Forward(()); | ||
} | ||
} |
This file contains 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,77 @@ | ||
use canapi::{Error, Provider}; | ||
igalic marked this conversation as resolved.
Show resolved
Hide resolved
|
||
use chrono::NaiveDateTime; | ||
use diesel::{self, RunQueryDsl, QueryDsl, ExpressionMethods}; | ||
|
||
use plume_api::apps::AppEndpoint; | ||
use plume_common::utils::random_hex; | ||
use Connection; | ||
use schema::apps; | ||
|
||
#[derive(Clone, Queryable)] | ||
pub struct App { | ||
pub id: i32, | ||
pub name: String, | ||
pub client_id: String, | ||
pub client_secret: String, | ||
pub redirect_uri: Option<String>, | ||
pub website: Option<String>, | ||
pub creation_date: NaiveDateTime, | ||
} | ||
|
||
#[derive(Insertable)] | ||
#[table_name= "apps"] | ||
pub struct NewApp { | ||
pub name: String, | ||
pub client_id: String, | ||
pub client_secret: String, | ||
pub redirect_uri: Option<String>, | ||
pub website: Option<String>, | ||
} | ||
|
||
impl Provider<Connection> for App { | ||
type Data = AppEndpoint; | ||
|
||
fn get(conn: &Connection, id: i32) -> Result<AppEndpoint, Error> { | ||
unimplemented!() | ||
} | ||
|
||
fn list(conn: &Connection, query: AppEndpoint) -> Vec<AppEndpoint> { | ||
unimplemented!() | ||
} | ||
|
||
fn create(conn: &Connection, data: AppEndpoint) -> Result<AppEndpoint, Error> { | ||
let client_id = random_hex(); | ||
|
||
let client_secret = random_hex(); | ||
let app = App::insert(conn, NewApp { | ||
name: data.name, | ||
client_id: client_id, | ||
client_secret: client_secret, | ||
redirect_uri: data.redirect_uri, | ||
website: data.website, | ||
}); | ||
|
||
Ok(AppEndpoint { | ||
id: Some(app.id), | ||
name: app.name, | ||
client_id: Some(app.client_id), | ||
client_secret: Some(app.client_secret), | ||
redirect_uri: app.redirect_uri, | ||
website: app.website, | ||
}) | ||
} | ||
|
||
fn update(conn: &Connection, id: i32, new_data: AppEndpoint) -> Result<AppEndpoint, Error> { | ||
unimplemented!() | ||
} | ||
|
||
fn delete(conn: &Connection, id: i32) { | ||
unimplemented!() | ||
} | ||
} | ||
|
||
impl App { | ||
get!(apps); | ||
insert!(apps, NewApp); | ||
find_by!(apps, find_by_client_id, client_id as String); | ||
} |
This file contains 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 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.
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.
This feel strange to be at the same time data received from Post (with id, client_id and client_secret ignored, as they must be generated by the server) and data returned by the api (with those same field used, and most likely different than what was originally posted if they where). It should either be 2 different struct or at least a struct with FromForm custom-implemented to ensure that
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.
We can't use
FromForm
in plume-api, or we would loose all the benefits of canapi.But I think I may add a
Server
/Client
/Both
wrapper type to specify when a field is required and make it easier to check if something has been forgotten.Or maybe canapi is just a bad idea and we should drop it... 🤔