Skip to content

Commit

Permalink
Fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
augustuswm committed Oct 12, 2023
1 parent a2e3aa6 commit 19db9ef
Show file tree
Hide file tree
Showing 14 changed files with 118 additions and 78 deletions.
35 changes: 22 additions & 13 deletions rfd-api/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,10 @@ impl ApiContext {
// Login Operations

#[instrument(skip(self, info), fields(info.external_id))]
pub async fn register_api_user(&self, info: UserInfo) -> Result<(User, ApiUserProvider), ApiError> {
pub async fn register_api_user(
&self,
info: UserInfo,
) -> Result<(User, ApiUserProvider), ApiError> {
// Check if we have seen this identity before
let mut filter = ApiUserProviderFilter::default();
filter.provider = Some(vec![info.external_id.provider().to_string()]);
Expand All @@ -576,14 +579,15 @@ impl ApiContext {
let user = self
.ensure_api_user(Uuid::new_v4(), mapped_permissions, mapped_groups)
.await?;
let user_provider = self.update_api_user_provider(NewApiUserProvider {
id: Uuid::new_v4(),
api_user_id: user.id,
emails: info.verified_emails,
provider: info.external_id.provider().to_string(),
provider_id: info.external_id.id().to_string(),
})
.await?;
let user_provider = self
.update_api_user_provider(NewApiUserProvider {
id: Uuid::new_v4(),
api_user_id: user.id,
emails: info.verified_emails,
provider: info.external_id.provider().to_string(),
provider_id: info.external_id.id().to_string(),
})
.await?;

Ok((user, user_provider))
}
Expand All @@ -592,9 +596,11 @@ impl ApiContext {

// This branch ensures that there is a 0th indexed item
let provider = api_user_providers.into_iter().nth(0).unwrap();
Ok((self
.ensure_api_user(provider.api_user_id, mapped_permissions, mapped_groups)
.await?, provider))
Ok((
self.ensure_api_user(provider.api_user_id, mapped_permissions, mapped_groups)
.await?,
provider,
))
}
_ => {
// If we found more than one provider, then we have encountered an inconsistency in
Expand Down Expand Up @@ -1166,7 +1172,10 @@ impl ApiContext {
update_request.completed_at = Some(Utc::now());
LinkRequestStore::upsert(&*self.storage, &update_request).await?;

Ok(Some(ApiUserProviderStore::transfer(&*self.storage, provider.into(), source_api_user_id).await?))
Ok(Some(
ApiUserProviderStore::transfer(&*self.storage, provider.into(), source_api_user_id)
.await?,
))
} else {
tracing::warn!(?link_request, "Expected to find a provider that was assigned to a link request, but it looks to have gone missing");
Ok(None)
Expand Down
5 changes: 4 additions & 1 deletion rfd-api/src/endpoints/api_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ use dropshot::{
RequestContext, TypedBody,
};
use partial_struct::partial;
use rfd_model::{storage::{ListPagination, ApiUserProviderFilter}, ApiUser, NewApiKey, NewApiUser, ApiUserProvider};
use rfd_model::{
storage::{ApiUserProviderFilter, ListPagination},
ApiUser, ApiUserProvider, NewApiKey, NewApiUser,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tap::TapFallible;
Expand Down
14 changes: 8 additions & 6 deletions rfd-api/src/endpoints/api_user_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,17 @@ pub async fn create_link_token(
let path = path.into_inner();
let body = body.into_inner();

let provider = ctx.get_api_user_provider(&path.identifier).await.map_err(ApiError::Storage)?;
let provider = ctx
.get_api_user_provider(&path.identifier)
.await
.map_err(ApiError::Storage)?;

if let Some(provider) = provider {
if provider.api_user_id == caller.id && caller.can(&ApiPermission::CreateUserApiProviderLinkToken) {
if provider.api_user_id == caller.id
&& caller.can(&ApiPermission::CreateUserApiProviderLinkToken)
{
let token = ctx
.create_link_request_token(
&path.identifier,
&caller.id,
&body.user_identifier)
.create_link_request_token(&path.identifier, &caller.id, &body.user_identifier)
.await
.map_err(ApiError::Storage)?;

Expand Down
2 changes: 1 addition & 1 deletion rfd-api/src/endpoints/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub mod well_known;
pub mod api_user;
pub mod api_user_provider;
pub mod group;
pub mod login;
pub mod rfd;
pub mod webhook;
pub mod well_known;
50 changes: 27 additions & 23 deletions rfd-api/src/endpoints/well_known/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use dropshot::{RequestContext, HttpResponseOk, HttpError, endpoint};
use jsonwebtoken::jwk::{JwkSet, AlgorithmParameters, PublicKeyUse};
use dropshot::{endpoint, HttpError, HttpResponseOk, RequestContext};
use jsonwebtoken::jwk::{AlgorithmParameters, JwkSet, PublicKeyUse};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use trace_request::trace_request;
Expand All @@ -19,10 +19,10 @@ pub struct OpenIdConfiguration {
}]
#[instrument(skip(rqctx), err(Debug))]
pub async fn openid_configuration(
rqctx: RequestContext<ApiContext>
rqctx: RequestContext<ApiContext>,
) -> Result<HttpResponseOk<OpenIdConfiguration>, HttpError> {
Ok(HttpResponseOk(OpenIdConfiguration {
jwks_uri: format!("{}/.well-known/jwks.json", &rqctx.context().public_url)
jwks_uri: format!("{}/.well-known/jwks.json", &rqctx.context().public_url),
}))
}

Expand Down Expand Up @@ -57,25 +57,29 @@ pub async fn jwks_json(
impl From<&JwkSet> for Jwks {
fn from(value: &JwkSet) -> Self {
Self {
keys: value.keys.iter().map(|jwk| {
let (algo, n, e) = match &jwk.algorithm {
AlgorithmParameters::RSA(params) => {
("RSA".to_string(), params.n.clone(), params.e.clone())
}
_ => panic!("Unexpected key type"),
};
keys: value
.keys
.iter()
.map(|jwk| {
let (algo, n, e) = match &jwk.algorithm {
AlgorithmParameters::RSA(params) => {
("RSA".to_string(), params.n.clone(), params.e.clone())
}
_ => panic!("Unexpected key type"),
};

Jwk {
kty: algo,
kid: jwk.common.key_id.as_ref().unwrap().clone(),
use_: match jwk.common.public_key_use {
Some(PublicKeyUse::Signature) => "sig".to_string(),
_ => panic!("Unexpected key use"),
},
n,
e,
}
}).collect()
Jwk {
kty: algo,
kid: jwk.common.key_id.as_ref().unwrap().clone(),
use_: match jwk.common.public_key_use {
Some(PublicKeyUse::Signature) => "sig".to_string(),
_ => panic!("Unexpected key use"),
},
n,
e,
}
})
.collect(),
}
}
}
}
6 changes: 5 additions & 1 deletion rfd-api/src/initial_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ impl InitialData {
let span = tracing::info_span!("Initializing group", group = ?group);

async {
let id = existing_groups.iter().find(|g| g.name == group.name).map(|g| g.id).unwrap_or(Uuid::new_v4());
let id = existing_groups
.iter()
.find(|g| g.name == group.name)
.map(|g| g.id)
.unwrap_or(Uuid::new_v4());

ctx.create_group(NewAccessGroup {
id,
Expand Down
4 changes: 3 additions & 1 deletion rfd-api/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,9 @@ impl PermissionStorage for Permissions<ApiPermission> {
}
}

contracted.push(ApiPermission::ManageGroupMemberships(manage_group_memberships));
contracted.push(ApiPermission::ManageGroupMemberships(
manage_group_memberships,
));
contracted.push(ApiPermission::ManageGroups(manage_groups));
contracted.push(ApiPermission::GetRfds(rfds));
contracted.push(ApiPermission::GetDiscussions(discussions));
Expand Down
3 changes: 2 additions & 1 deletion rfd-api/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ use crate::{
device_token::{exchange_device_token, get_device_provider},
},
rfd::{get_rfd, get_rfds, search_rfds},
webhook::github_webhook, well_known::{openid_configuration, jwks_json},
webhook::github_webhook,
well_known::{jwks_json, openid_configuration},
},
};

Expand Down
27 changes: 15 additions & 12 deletions rfd-cli/src/auth/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ use core::panic;

use anyhow::Result;
use clap::{Parser, Subcommand};
use jsonwebtoken::{DecodingKey, Validation, Algorithm};
use jsonwebtoken::{Algorithm, DecodingKey, Validation};
use oauth2::TokenResponse;
use rfd_sdk::types::OAuthProviderName;
use serde::Deserialize;
use uuid::Uuid;

use crate::{Context, auth::oauth};
use crate::{auth::oauth, Context};

use super::login::LoginProvider;

Expand Down Expand Up @@ -37,27 +37,30 @@ impl Link {
let jwk = &jwks.keys[0];

// Decode the access token to extract the provider token
let jwt = jsonwebtoken::decode::<Claims>(&access_token, &DecodingKey::from_rsa_components(&jwk.n, &jwk.e)?, &Validation::new(Algorithm::RS256))?;
let jwt = jsonwebtoken::decode::<Claims>(
&access_token,
&DecodingKey::from_rsa_components(&jwk.n, &jwk.e)?,
&Validation::new(Algorithm::RS256),
)?;

// An account linking request can only be generated by the owning account. Therefore we
// need to use the sdk to generate a new client
let client = Context::new_client(Ok(&access_token), ctx.config.host()?)?;

// This needs to be the id of the provider the client just logged in with
let link_token = client.create_link_token().identifier(jwt.claims.prv)
.body_map(|body| {
body.user_identifier(self_id)
})
let link_token = client
.create_link_token()
.identifier(jwt.claims.prv)
.body_map(|body| body.user_identifier(self_id))
.send()
.await?
.into_inner()
.token;

ctx.client()?.link_provider()
ctx.client()?
.link_provider()
.identifier(self_id)
.body_map(|body| {
body.token(link_token)
})
.body_map(|body| body.token(link_token))
.send()
.await?;

Expand Down
2 changes: 1 addition & 1 deletion rfd-cli/src/auth/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use clap::{Parser, Subcommand};
use oauth2::TokenResponse;
use rfd_sdk::types::OAuthProviderName;

use crate::{Context, auth::oauth};
use crate::{auth::oauth, Context};

// Authenticates and generates an access token for interacting with the api
#[derive(Parser, Debug)]
Expand Down
5 changes: 2 additions & 3 deletions rfd-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ impl Context {
let mut default_headers = HeaderMap::new();

if let Ok(token) = token {
let mut auth_header =
HeaderValue::from_str(&format!("Bearer {}", token))?;
let mut auth_header = HeaderValue::from_str(&format!("Bearer {}", token))?;
auth_header.set_sensitive(true);
default_headers.insert(AUTHORIZATION, auth_header);
}
Expand All @@ -67,7 +66,7 @@ impl Context {

self.client
.as_ref()
.ok_or_else(|| anyhow!("Failed to construct client"))
.ok_or_else(|| anyhow!("Failed to construct client"))
}
}

Expand Down
10 changes: 8 additions & 2 deletions rfd-cli/src/printer/tab.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use itertools::{EitherOrBoth, Itertools};
use rfd_sdk::types::{AccessGroupForApiPermission, ApiUserForApiPermission, Error, ListRfd, GetApiUserResponse};
use rfd_sdk::types::{
AccessGroupForApiPermission, ApiUserForApiPermission, Error, GetApiUserResponse, ListRfd,
};
use std::{fs::File, io::Write, process::Command};
use tabwriter::TabWriter;

Expand Down Expand Up @@ -233,7 +235,11 @@ fn print_user(user: &GetApiUserResponse) {
HEADER_COLOR
);

let lines = user.info.permissions.iter().zip_longest(user.info.groups.iter());
let lines = user
.info
.permissions
.iter()
.zip_longest(user.info.groups.iter());

for (i, line) in lines.enumerate() {
let inner = match line {
Expand Down
8 changes: 6 additions & 2 deletions rfd-model/src/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,12 @@ pub trait ApiUserProviderStore {
filter: ApiUserProviderFilter,
pagination: &ListPagination,
) -> Result<Vec<ApiUserProvider>, StoreError>;
async fn upsert(&self, api_user: NewApiUserProvider,) -> Result<ApiUserProvider, StoreError>;
async fn transfer(&self, api_user: NewApiUserProvider, current_api_user_id: Uuid) -> Result<ApiUserProvider, StoreError>;
async fn upsert(&self, api_user: NewApiUserProvider) -> Result<ApiUserProvider, StoreError>;
async fn transfer(
&self,
api_user: NewApiUserProvider,
current_api_user_id: Uuid,
) -> Result<ApiUserProvider, StoreError>;
async fn delete(&self, id: &Uuid) -> Result<Option<ApiUserProvider>, StoreError>;
}

Expand Down
25 changes: 14 additions & 11 deletions rfd-model/src/storage/postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,19 +846,22 @@ impl ApiUserProviderStore for PostgresStore {
})
}

async fn transfer(&self, provider: NewApiUserProvider, current_api_user_id: Uuid) -> Result<ApiUserProvider, StoreError> {
async fn transfer(
&self,
provider: NewApiUserProvider,
current_api_user_id: Uuid,
) -> Result<ApiUserProvider, StoreError> {
tracing::trace!(id = ?provider.id, api_user_id = ?provider.api_user_id, provider = ?provider, "Updating user provider");

let provider_m: ApiUserProviderModel =
update(api_user_provider::dsl::api_user_provider)
.set((
api_user_provider::api_user_id.eq(provider.api_user_id),
api_user_provider::updated_at.eq(Utc::now()),
))
.filter(api_user_provider::id.eq(provider.id))
.filter(api_user_provider::api_user_id.eq(current_api_user_id))
.get_result_async(&self.conn)
.await?;
let provider_m: ApiUserProviderModel = update(api_user_provider::dsl::api_user_provider)
.set((
api_user_provider::api_user_id.eq(provider.api_user_id),
api_user_provider::updated_at.eq(Utc::now()),
))
.filter(api_user_provider::id.eq(provider.id))
.filter(api_user_provider::api_user_id.eq(current_api_user_id))
.get_result_async(&self.conn)
.await?;

Ok(ApiUserProvider {
id: provider_m.id,
Expand Down

0 comments on commit 19db9ef

Please sign in to comment.