Skip to content
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

chore: move ApiKey type to backends, remove AccountTier sqlx::Type #1923

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion auth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ publish = false

[dependencies]
shuttle-backends = { workspace = true }
shuttle-common = { workspace = true, features = ["models", "persist"] }
shuttle-common = { workspace = true, features = ["models"] }

anyhow = { workspace = true }
async-stripe = { version = "0.25.1", default-features = false, features = ["checkout", "runtime-tokio-hyper-rustls"] }
Expand Down
11 changes: 7 additions & 4 deletions auth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@ mod user;
use anyhow::Result;
use args::{CopyPermitEnvArgs, StartArgs, SyncArgs};
use http::StatusCode;
use shuttle_backends::client::{
permit::{self, Error, ResponseContent},
PermissionsDal,
use shuttle_backends::{
client::{
permit::{self, Error, ResponseContent},
PermissionsDal,
},
key::ApiKey,
};
use shuttle_common::{models::user::AccountTier, ApiKey};
use shuttle_common::models::user::AccountTier;
use sqlx::{query, PgPool};
use tracing::info;
pub use user::User;
Expand Down
4 changes: 2 additions & 2 deletions auth/src/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ use axum::{
TypedHeader,
};
use chrono::{DateTime, Utc};
use shuttle_backends::{client::PermissionsDal, headers::XShuttleAdminSecret};
use shuttle_backends::{client::PermissionsDal, headers::XShuttleAdminSecret, key::ApiKey};
use shuttle_common::{
limits::Limits,
models::{
self,
user::{AccountTier, UserId},
},
ApiKey, Secret,
Secret,
};
use sqlx::{postgres::PgRow, query, FromRow, PgPool, Row};
use stripe::{SubscriptionId, SubscriptionStatus};
Expand Down
3 changes: 3 additions & 0 deletions backends/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pin-project = { workspace = true }
permit-client-rs = { git = "https://github.com/shuttle-hq/permit-client-rs", rev = "19085ba" }
permit-pdp-client-rs = { git = "https://github.com/shuttle-hq/permit-pdp-client-rs", rev = "37c7296" }
jonaro00 marked this conversation as resolved.
Show resolved Hide resolved
portpicker = { workspace = true, optional = true }
rand = { workspace = true }
reqwest = { workspace = true, features = ["json"] }
# keep locked to not accidentally invalidate someone's project name
# higher versions have a lot more false positives
Expand All @@ -44,6 +45,7 @@ tracing = { workspace = true, features = ["std"] }
tracing-opentelemetry = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter", "fmt"]}
ttl_cache = { workspace = true }
zeroize = { workspace = true }
wiremock = { workspace = true, optional = true }

[features]
Expand All @@ -54,6 +56,7 @@ test-utils = ["portpicker", "wiremock"]
base64 = { workspace = true }
ctor = { workspace = true }
jsonwebtoken = { workspace = true }
proptest = "1.1.0"
ring = { workspace = true }
serial_test = "3.0.0"
shuttle-common-tests = { workspace = true }
Expand Down
81 changes: 81 additions & 0 deletions backends/src/key.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use anyhow::bail;
use rand::distributions::{Alphanumeric, DistString};
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;

#[derive(Clone, Serialize, Deserialize)]
#[serde(transparent)]
#[cfg_attr(feature = "sqlx", derive(PartialEq, Eq, Hash, sqlx::Type))]
#[cfg_attr(feature = "sqlx", sqlx(transparent))]
pub struct ApiKey(String);

impl Zeroize for ApiKey {
fn zeroize(&mut self) {
self.0.zeroize()
}
}

impl ApiKey {
pub fn parse(key: &str) -> anyhow::Result<Self> {
let key = key.trim();

let mut errors = vec![];
if !key.chars().all(char::is_alphanumeric) {
errors.push("The API key should consist of only alphanumeric characters.");
};
jonaro00 marked this conversation as resolved.
Show resolved Hide resolved

if key.len() != 16 {
errors.push("The API key should be exactly 16 characters in length.");
};

if !errors.is_empty() {
let message = errors.join("\n");
bail!("Invalid API key:\n{message}")
}

Ok(Self(key.to_string()))
}

pub fn generate() -> Self {
Self(Alphanumeric.sample_string(&mut rand::thread_rng(), 16))
}
}

impl AsRef<str> for ApiKey {
fn as_ref(&self) -> &str {
&self.0
}
}

#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;

proptest! {
#[test]
// The API key should be a 16 character alphanumeric string.
fn parses_valid_api_keys(s in "[a-zA-Z0-9]{16}") {
ApiKey::parse(&s).unwrap();
}
}

#[test]
fn generated_api_key_is_valid() {
let key = ApiKey::generate();

assert!(ApiKey::parse(key.as_ref()).is_ok());
}

#[test]
#[should_panic(expected = "The API key should be exactly 16 characters in length.")]
fn invalid_api_key_length() {
ApiKey::parse("tooshort").unwrap();
}

#[test]
#[should_panic(expected = "The API key should consist of only alphanumeric characters.")]
fn non_alphanumeric_api_key() {
ApiKey::parse("dh9z58jttoes3qv@").unwrap();
}
}
1 change: 1 addition & 0 deletions backends/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod cache;
pub mod client;
mod future;
pub mod headers;
pub mod key;
pub mod metrics;
mod otlp_tracing_bridge;
pub mod project_name;
Expand Down
5 changes: 0 additions & 5 deletions common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ jsonwebtoken = { workspace = true, optional = true }
opentelemetry = { workspace = true, optional = true }
opentelemetry-http = { workspace = true, optional = true }
pin-project = { workspace = true, optional = true }
rand = { workspace = true, optional = true }
reqwest = { workspace = true, optional = true }
semver = { workspace = true }
serde = { workspace = true, features = ["derive", "std"] }
Expand Down Expand Up @@ -68,12 +67,8 @@ extract_propagation = [
"tracing-opentelemetry",
]
models = ["async-trait", "reqwest", "service"]
jonaro00 marked this conversation as resolved.
Show resolved Hide resolved
persist = ["sqlx", "rand"]
sqlx = ["dep:sqlx", "sqlx/sqlite", "sqlx/postgres"]
service = ["chrono/serde", "display", "tracing", "tracing-subscriber", "uuid"]
test-utils = ["wiremock"]
tonic = ["dep:tonic"]
tracing = ["dep:tracing"]

[dev-dependencies]
proptest = "1.1.0"
79 changes: 0 additions & 79 deletions common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,56 +29,7 @@ pub mod tracing;

use std::fmt::Debug;

use anyhow::bail;
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;

#[derive(Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "persist", derive(PartialEq, Eq, Hash, sqlx::Type))]
#[cfg_attr(feature = "persist", serde(transparent))]
#[cfg_attr(feature = "persist", sqlx(transparent))]
pub struct ApiKey(String);

impl Zeroize for ApiKey {
fn zeroize(&mut self) {
self.0.zeroize()
}
}

impl ApiKey {
pub fn parse(key: &str) -> anyhow::Result<Self> {
let key = key.trim();

let mut errors = vec![];
if !key.chars().all(char::is_alphanumeric) {
errors.push("The API key should consist of only alphanumeric characters.");
};

if key.len() != 16 {
errors.push("The API key should be exactly 16 characters in length.");
};

if !errors.is_empty() {
let message = errors.join("\n");
bail!("Invalid API key:\n{message}")
}

Ok(Self(key.to_string()))
}

#[cfg(feature = "persist")]
pub fn generate() -> Self {
use rand::distributions::{Alphanumeric, DistString};

Self(Alphanumeric.sample_string(&mut rand::thread_rng(), 16))
}
}

impl AsRef<str> for ApiKey {
fn as_ref(&self) -> &str {
&self.0
}
}

////// Resource Input/Output types

Expand Down Expand Up @@ -296,38 +247,8 @@ pub fn semvers_are_compatible(a: &semver::Version, b: &semver::Version) -> bool

#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
use std::str::FromStr;

proptest! {
#[test]
// The API key should be a 16 character alphanumeric string.
fn parses_valid_api_keys(s in "[a-zA-Z0-9]{16}") {
ApiKey::parse(&s).unwrap();
}
}

#[cfg(feature = "persist")]
#[test]
fn generated_api_key_is_valid() {
let key = ApiKey::generate();

assert!(ApiKey::parse(key.as_ref()).is_ok());
}

#[test]
#[should_panic(expected = "The API key should be exactly 16 characters in length.")]
fn invalid_api_key_length() {
ApiKey::parse("tooshort").unwrap();
}

#[test]
#[should_panic(expected = "The API key should consist of only alphanumeric characters.")]
fn non_alphanumeric_api_key() {
ApiKey::parse("dh9z58jttoes3qv@").unwrap();
}

#[test]
fn semver_compatibility_check_works() {
let semver_tests = &[
Expand Down
2 changes: 0 additions & 2 deletions common/src/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,6 @@ impl UserResponse {
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "display", derive(strum::Display))]
#[cfg_attr(feature = "display", strum(serialize_all = "lowercase"))]
#[cfg_attr(feature = "persist", derive(sqlx::Type))]
#[cfg_attr(feature = "persist", sqlx(rename_all = "lowercase"))]
#[typeshare::typeshare]
pub enum AccountTier {
#[default]
Expand Down
2 changes: 1 addition & 1 deletion gateway/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ publish = false

[dependencies]
shuttle-backends = { workspace = true, features = ["sqlx"] }
shuttle-common = { workspace = true, features = ["models", "persist"] }
shuttle-common = { workspace = true, features = ["models"] }
shuttle-proto = { workspace = true, features = ["provisioner-client"] }

async-posthog = { git = "https://github.com/shuttle-hq/posthog-rs", branch = "main" }
Expand Down
3 changes: 1 addition & 2 deletions gateway/src/api/auth_layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ use once_cell::sync::Lazy;
use opentelemetry::global;
use opentelemetry_http::HeaderInjector;
use shuttle_backends::{
auth::ConvertResponse, cache::CacheManagement, headers::XShuttleAdminSecret,
auth::ConvertResponse, cache::CacheManagement, headers::XShuttleAdminSecret, key::ApiKey,
};
use shuttle_common::ApiKey;
use tower::{Layer, Service};
use tracing::{error, trace, Span};
use tracing_opentelemetry::OpenTelemetrySpanExt;
Expand Down