Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
377 changes: 377 additions & 0 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ chrono = "0.4.41"
config = "0.15.11"
cookie = "0.18.1"
derive_more = { version = "2.0", features = ["display", "error"] }
ed25519-dalek = { version = "2.1", features = ["rand_core"] }
error-stack = "0.6"
fastly = "0.11.7"
fern = "0.7.1"
Expand All @@ -33,10 +34,12 @@ handlebars = "6.3.2"
hex = "0.4.3"
hmac = "0.12.1"
http = "1.3.1"
jose-jwk = "0.1.2"
log = "0.4.27"
log-fastly = "0.11.7"
lol_html = "2.6.0"
pin-project-lite = "0.2"
rand = "0.8"
regex = "1.1.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.145"
Expand Down
3 changes: 3 additions & 0 deletions crates/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ handlebars = { workspace = true }
hex = { workspace = true }
hmac = { workspace = true }
http = { workspace = true }
jose-jwk = { workspace = true }
log = { workspace = true }
rand = { workspace = true }
log-fastly = { workspace = true }
lol_html = { workspace = true }
pin-project-lite = { workspace = true }
Expand All @@ -39,6 +41,7 @@ url = { workspace = true }
urlencoding = { workspace = true }
uuid = { workspace = true }
validator = { workspace = true }
ed25519-dalek = { workspace = true }

[build-dependencies]
config = { workspace = true }
Expand Down
360 changes: 360 additions & 0 deletions crates/common/src/fastly_storage.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,360 @@
use std::io::Read;

use fastly::{ConfigStore, Request, Response, SecretStore};
use http::StatusCode;

use crate::backend::ensure_backend_from_url;
use crate::error::TrustedServerError;

pub struct FastlyConfigStore {
store_name: String,
}

impl FastlyConfigStore {
pub fn new(store_name: impl Into<String>) -> Self {
Self {
store_name: store_name.into(),
}
}

pub fn get(&self, key: &str) -> Result<String, TrustedServerError> {
// TODO use try_open and return the error
let store = ConfigStore::open(&self.store_name);
store
.get(key)
.ok_or_else(|| TrustedServerError::Configuration {
message: format!(
"Key '{}' not found in config store '{}'",
key, self.store_name
),
})
}
}

pub struct FastlySecretStore {
store_name: String,
}

impl FastlySecretStore {
pub fn new(store_name: impl Into<String>) -> Self {
Self {
store_name: store_name.into(),
}
}

pub fn get(&self, key: &str) -> Result<Vec<u8>, TrustedServerError> {
let store =
SecretStore::open(&self.store_name).map_err(|_| TrustedServerError::Configuration {
message: format!("Failed to open SecretStore '{}'", self.store_name),
})?;

let secret = store
.get(key)
.ok_or_else(|| TrustedServerError::Configuration {
message: format!(
"Secret '{}' not found in secret store '{}'",
key, self.store_name
),
})?;

secret
.try_plaintext()
.map_err(|_| TrustedServerError::Configuration {
message: "Failed to get secret plaintext".into(),
})
.map(|bytes| bytes.into_iter().collect())
}

pub fn get_string(&self, key: &str) -> Result<String, TrustedServerError> {
let bytes = self.get(key)?;
String::from_utf8(bytes).map_err(|e| TrustedServerError::Configuration {
message: format!("Failed to decode secret as UTF-8: {}", e),
})
}
}

pub struct FastlyApiClient {
api_key: Vec<u8>,
base_url: String,
}

impl FastlyApiClient {
pub fn new() -> Result<Self, TrustedServerError> {
Self::from_secret_store("api-keys", "api_key")
}

pub fn from_secret_store(store_name: &str, key_name: &str) -> Result<Self, TrustedServerError> {
ensure_backend_from_url("https://api.fastly.com").map_err(|e| {
TrustedServerError::Configuration {
message: format!("Failed to ensure API backend: {}", e),
}
})?;

let secret_store = FastlySecretStore::new(store_name);
let api_key = secret_store.get(key_name)?;

Ok(Self {
api_key,
base_url: "https://api.fastly.com".to_string(),
})
}

fn make_request(
&self,
method: &str,
path: &str,
body: Option<String>,
content_type: &str,
) -> Result<Response, TrustedServerError> {
let url = format!("{}{}", self.base_url, path);

let api_key_str = String::from_utf8_lossy(&self.api_key).to_string();

let mut request = match method {
"GET" => Request::get(&url),
"POST" => Request::post(&url),
"PUT" => Request::put(&url),
"DELETE" => Request::delete(&url),
_ => {
return Err(TrustedServerError::Configuration {
message: format!("Unsupported HTTP method: {}", method),
})
}
};

request = request
.with_header("Fastly-Key", api_key_str)
.with_header("Accept", "application/json");

if let Some(body_content) = body {
request = request
.with_header("Content-Type", content_type)
.with_body(body_content);
}

request.send("backend_https_api_fastly_com").map_err(|e| {
TrustedServerError::Configuration {
message: format!("Failed to send API request: {}", e),
}
})
}

pub fn update_config_item(
&self,
store_id: &str,
key: &str,
value: &str,
) -> Result<(), TrustedServerError> {
let path = format!("/resources/stores/config/{}/item/{}", store_id, key);
let payload = format!("item_value={}", value);

let mut response = self.make_request(
"PUT",
&path,
Some(payload),
"application/x-www-form-urlencoded",
)?;

let mut buf = String::new();
response
.get_body_mut()
.read_to_string(&mut buf)
.map_err(|e| TrustedServerError::Configuration {
message: format!("Failed to read API response: {}", e),
})?;

if response.get_status() == StatusCode::OK {
Ok(())
} else {
Err(TrustedServerError::Configuration {
message: format!(
"Failed to update config item: HTTP {} - {}",
response.get_status(),
buf
),
})
}
}

pub fn create_secret(
&self,
store_id: &str,
secret_name: &str,
secret_value: &str,
) -> Result<(), TrustedServerError> {
let path = format!("/resources/stores/secret/{}/secrets", store_id);

let payload = serde_json::json!({
"name": secret_name,
"secret": secret_value
});

let mut response =
self.make_request("POST", &path, Some(payload.to_string()), "application/json")?;

let mut buf = String::new();
response
.get_body_mut()
.read_to_string(&mut buf)
.map_err(|e| TrustedServerError::Configuration {
message: format!("Failed to read API response: {}", e),
})?;

if response.get_status() == StatusCode::OK {
Ok(())
} else {
Err(TrustedServerError::Configuration {
message: format!(
"Failed to create secret: HTTP {} - {}",
response.get_status(),
buf
),
})
}
}

pub fn delete_config_item(&self, store_id: &str, key: &str) -> Result<(), TrustedServerError> {
let path = format!("/resources/stores/config/{}/item/{}", store_id, key);

let mut response = self.make_request("DELETE", &path, None, "application/json")?;

let mut buf = String::new();
response
.get_body_mut()
.read_to_string(&mut buf)
.map_err(|e| TrustedServerError::Configuration {
message: format!("Failed to read API response: {}", e),
})?;

if response.get_status() == StatusCode::OK
|| response.get_status() == StatusCode::NO_CONTENT
{
Ok(())
} else {
Err(TrustedServerError::Configuration {
message: format!(
"Failed to delete config item: HTTP {} - {}",
response.get_status(),
buf
),
})
}
}

pub fn delete_secret(
&self,
store_id: &str,
secret_name: &str,
) -> Result<(), TrustedServerError> {
let path = format!(
"/resources/stores/secret/{}/secrets/{}",
store_id, secret_name
);

let mut response = self.make_request("DELETE", &path, None, "application/json")?;

let mut buf = String::new();
response
.get_body_mut()
.read_to_string(&mut buf)
.map_err(|e| TrustedServerError::Configuration {
message: format!("Failed to read API response: {}", e),
})?;

if response.get_status() == StatusCode::OK
|| response.get_status() == StatusCode::NO_CONTENT
{
Ok(())
} else {
Err(TrustedServerError::Configuration {
message: format!(
"Failed to delete secret: HTTP {} - {}",
response.get_status(),
buf
),
})
}
}
}

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

#[test]
fn test_config_store_new() {
let store = FastlyConfigStore::new("test_store");
assert_eq!(store.store_name, "test_store");
}

#[test]
fn test_secret_store_new() {
let store = FastlySecretStore::new("test_secrets");
assert_eq!(store.store_name, "test_secrets");
}

#[test]
fn test_config_store_get() {
let store = FastlyConfigStore::new("jwks_store");
let result = store.get("current-kid");
match result {
Ok(kid) => println!("Current KID: {}", kid),
Err(e) => println!("Expected error in test environment: {}", e),
}
}

#[test]
fn test_secret_store_get() {
let store = FastlySecretStore::new("signing_keys");
let config_store = FastlyConfigStore::new("jwks_store");

match config_store.get("current-kid") {
Ok(kid) => match store.get(&kid) {
Ok(bytes) => {
println!("Successfully loaded secret, {} bytes", bytes.len());
assert!(!bytes.is_empty());
}
Err(e) => println!("Error loading secret: {}", e),
},
Err(e) => println!("Error getting current kid: {}", e),
}
}

#[test]
fn test_api_client_creation() {
let result = FastlyApiClient::new();
match result {
Ok(_client) => println!("Successfully created API client"),
Err(e) => println!("Expected error in test environment: {}", e),
}
}

#[test]
fn test_update_config_item() {
let result = FastlyApiClient::new();
if let Ok(client) = result {
let result =
client.update_config_item("5WNlRjznCUAGTU0QeYU8x2", "test-key", "test-value");
match result {
Ok(()) => println!("Successfully updated config item"),
Err(e) => println!("Failed to update config item: {}", e),
}
}
}

#[test]
fn test_create_secret() {
let result = FastlyApiClient::new();
if let Ok(client) = result {
let result = client.create_secret(
"Ltf3CkSGV0Yn2PIC2lDcZx",
"test-secret-new",
"SGVsbG8sIHdvcmxkIQ==",
);
match result {
Ok(()) => println!("Successfully created secret"),
Err(e) => println!("Failed to create secret: {}", e),
}
}
}
}
Loading