Skip to content

Commit

Permalink
fix(auth_rust): reflect code review
Browse files Browse the repository at this point in the history
  • Loading branch information
aldy505 committed Apr 11, 2024
1 parent a0e5e7b commit d8e3aff
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 33 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/systems-nightly.yml
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ jobs:
environment: production
ignore_empty: true

build-auth)rust:
build-auth_rust:
name: Build Auth Rust
runs-on: ubuntu-latest
timeout-minutes: 30
Expand Down
39 changes: 39 additions & 0 deletions .github/workflows/systems-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,45 @@ jobs:
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

auth_rust:
name: Auth Rust
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
packages: write
steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3

- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-auth_rust
flavor: |
latest=true
tags: |
type=semver,pattern={{version}}
- name: Build and push Docker image
uses: docker/build-push-action@v4
with:
context: "{{defaultContext}}:auth_rust"
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

database:
name: Database
runs-on: ubuntu-latest
Expand Down
78 changes: 46 additions & 32 deletions auth_rust/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,31 +23,42 @@ async fn authenticate<Command: AsyncCommands>(
headers: HeaderMap,
State(mut auth_repo): State<AuthRepo<Command>>,
) -> impl IntoResponse {
if headers.get("X-Pesto-Token").is_none() {
return (
StatusCode::UNAUTHORIZED,
[(header::CONTENT_TYPE, "application/json")],
r#"{"message":"Token must be supplied"}"#,
);
}

let token: String = headers.get("X-Pesto-Token").unwrap().to_str().unwrap().to_string();
let token_value = match auth_repo.acquire_token_value(token).await {
Ok(token_value) => token_value,
Err(AuthError::TokenNotRegistered) => {
let token_value = match headers
.get("X-Pesto-Token")
.and_then(|v| v.to_str().ok())
.map(String::from)
{
None => {
return (
StatusCode::UNAUTHORIZED,
[(header::CONTENT_TYPE, "application/json")],
r#"{"message":"Token not registered"}"#,
);
}
Err(AuthError::FailedToAcquireToken(_)) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, "application/json")],
r#"{"message":"Internal server error"}"#,
r#"{"message":"Token must be supplied"}"#,
);
}
Some(token) => match auth_repo.acquire_token_value(token).await {
Ok(token_value) => token_value,
Err(AuthError::TokenNotRegistered) => {
return (
StatusCode::UNAUTHORIZED,
[(header::CONTENT_TYPE, "application/json")],
r#"{"message":"Token not registered"}"#,
);
}
Err(AuthError::FailedToAcquireToken(_)) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, "application/json")],
r#"{"message":"Internal server error"}"#,
);
}
Err(AuthError::ParseError) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, "application/json")],
r#"{"message":"Internal server error"}"#,
);
}
},
};

if token_value.revoked {
Expand Down Expand Up @@ -77,15 +88,16 @@ async fn authenticate<Command: AsyncCommands>(
);
}

match auth_repo.increment_monthly_counter(&token_value, counter_limit).await {
Ok(_) => (),
Err(_) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, "application/json")],
r#"{"message":"Internal server error"}"#,
);
}
if auth_repo
.increment_monthly_counter(&token_value, counter_limit)
.await
.is_err()
{
return (
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, "application/json")],
r#"{"message":"Internal server error"}"#,
);
}

Metric::count("pesto.successful_auth")
Expand All @@ -97,13 +109,15 @@ async fn authenticate<Command: AsyncCommands>(
enum AuthError {
TokenNotRegistered,
FailedToAcquireToken(RedisError),
ParseError,
}

impl Display for AuthError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
AuthError::TokenNotRegistered => write!(f, "Token not registered"),
AuthError::FailedToAcquireToken(e) => write!(f, "Failed to acquire token: {}", e),
AuthError::ParseError => write!(f, "Parse error"),
}
}
}
Expand Down Expand Up @@ -138,7 +152,7 @@ impl<Command: AsyncCommands> AuthRepo<Command> {

match token_value {
Ok(Some(value)) => {
let token_value: TokenValue = serde_json::from_str(&value).unwrap();
let token_value: TokenValue = serde_json::from_str(&value).map_err(|_| AuthError::ParseError)?;
Ok(token_value)
}
Ok(None) => Err(AuthError::TokenNotRegistered),
Expand All @@ -157,7 +171,7 @@ impl<Command: AsyncCommands> AuthRepo<Command> {

match value {
Ok(Some(value)) => {
let counter_limit: i64 = value.parse().unwrap();
let counter_limit: i64 = value.parse().map_err(|_| AuthError::ParseError)?;
Ok(counter_limit)
}
Ok(None) => Ok(0),
Expand Down Expand Up @@ -201,7 +215,7 @@ fn main() -> Result<(), Box<dyn Error>> {
.with(sentry::integrations::tracing::layer())
.init();

let _guard = sentry::init((env::var("SENTRY_DSN").unwrap_or(String::from("")), sentry::ClientOptions {
let _guard = sentry::init((env::var("SENTRY_DSN").unwrap_or_default(), sentry::ClientOptions {
release: sentry::release_name!(),
sample_rate: 1.0,
traces_sample_rate: 0.5,
Expand Down

0 comments on commit d8e3aff

Please sign in to comment.