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

Implement basic CRUD operations for REST API #18

Merged
merged 1 commit into from
Oct 1, 2024
Merged
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
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ flate2 = "1.0"
base64 = "0.22.1"
hmac = "0.12.1"
sha2 = "0.10.8"
serde = { version = "1.0.207", features = ["derive"] }

[dev-dependencies]
rstest = "0.22.0"
126 changes: 125 additions & 1 deletion src/http/urls.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use crate::models::external::identity::{ExternalIdentity, Policy, PolicyAttachment};
use crate::models::external::identity_provider::ExternalIdentityProvider;
use crate::models::external::token::ExternalToken;
use crate::services::base::upsert_repository::{
IdentityRepository, PolicyAttachmentRepository, PolicyRepository,
};
use crate::services::token_service::{TokenProvider, TokenService};
use actix_web::{error, get, web, HttpRequest};
use actix_web::{delete, error, get, post, web, HttpRequest, HttpResponse, Responder};
use log::error;
use std::sync::Arc;

Expand All @@ -27,3 +31,123 @@ pub async fn token(
None => Err(error::ErrorUnauthorized("No Authorization header found")),
}
}

#[post("/policy/{id}")]
pub async fn post_policy(
id: web::Path<String>,
policy: String,
data: web::Data<Arc<PolicyRepository>>,
) -> actix_web::Result<HttpResponse> {
data.upsert(id.to_string(), Policy::new(policy))
.await
.map_err(|e| {
error!("Error: {:?}", e);
error::ErrorInternalServerError("Failed to upsert policy")
})?;
Ok(HttpResponse::Ok().finish())
}

#[get("/policy/{id}")]
pub async fn get_policy(
id: web::Path<String>,
data: web::Data<Arc<PolicyRepository>>,
) -> actix_web::Result<String> {
let policy = data.get(id.to_string()).await.map_err(|e| {
error!("Error: {:?}", e);
error::ErrorInternalServerError("Failed to upsert policy")
})?;
Ok(policy.content)
}

#[delete("/policy/{id}")]
pub async fn delete_policy(
id: web::Path<String>,
data: web::Data<Arc<PolicyRepository>>,
) -> actix_web::Result<HttpResponse> {
data.delete(id.to_string()).await.map_err(|e| {
error!("Error: {:?}", e);
error::ErrorInternalServerError("Failed to upsert policy")
})?;
Ok(HttpResponse::Ok().finish())
}

#[post("/identity/{identity_provider}/{id}")]
pub async fn post_identity(
params: web::Path<(String, String)>,
data: web::Data<Arc<IdentityRepository>>,
) -> actix_web::Result<HttpResponse> {
let key = params.into_inner();
let eid = ExternalIdentity::from(key.clone());
data.upsert(key, eid).await.map_err(|e| {
error!("Error: {:?}", e);
error::ErrorInternalServerError("Failed to upsert policy")
})?;
Ok(HttpResponse::Ok().finish())
}

#[get("/identity/{identity_provider}/{id}")]
pub async fn get_identity(
params: web::Path<(String, String)>,
data: web::Data<Arc<IdentityRepository>>,
) -> actix_web::Result<impl Responder> {
let eid = data.get(params.into_inner()).await.map_err(|e| {
error!("Error: {:?}", e);
error::ErrorInternalServerError("Failed to upsert policy")
})?;
Ok(web::Json(eid))
}

#[delete("/identity/{identity_provider}/{id}")]
pub async fn delete_identity(
params: web::Path<(String, String)>,
data: web::Data<Arc<IdentityRepository>>,
) -> actix_web::Result<HttpResponse> {
data.delete(params.into_inner()).await.map_err(|e| {
error!("Error: {:?}", e);
error::ErrorInternalServerError("Failed to upsert policy")
})?;
Ok(HttpResponse::Ok().finish())
}

#[post("/attachment/{identity_provider}/{id}/{policy_id}")]
pub async fn post_policy_attachment(
params: web::Path<(String, String, String)>,
data: web::Data<Arc<PolicyAttachmentRepository>>,
) -> actix_web::Result<HttpResponse> {
let (identity_provider, id, policy_id) = params.into_inner();
let eid = ExternalIdentity::new(id, identity_provider);
let attachment = PolicyAttachment::single(policy_id);
data.upsert(eid, attachment).await.map_err(|e| {
error!("Error: {:?}", e);
error::ErrorInternalServerError("Failed to upsert policy")
})?;
Ok(HttpResponse::Ok().finish())
}

#[post("/attachment/{identity_provider}/{id}")]
pub async fn get_policy_attachment(
params: web::Path<(String, String)>,
data: web::Data<Arc<PolicyAttachmentRepository>>,
) -> actix_web::Result<impl Responder> {
let (identity_provider, id) = params.into_inner();
let eid = ExternalIdentity::new(id, identity_provider);
let result = data.get(eid).await.map_err(|e| {
error!("Error: {:?}", e);
error::ErrorInternalServerError("Failed to upsert policy")
})?;
Ok(web::Json(result))
}

#[delete("/attachment/{identity_provider}/{id}")]
pub async fn delete_policy_attachment(
params: web::Path<(String, String)>,
data: web::Data<Arc<PolicyAttachmentRepository>>,
) -> actix_web::Result<HttpResponse> {
let (identity_provider, id) = params.into_inner();
let eid = ExternalIdentity::new(id, identity_provider);
data.delete(eid).await.map_err(|e| {
error!("Error: {:?}", e);
error::ErrorInternalServerError("Failed to upsert policy")
})?;
Ok(HttpResponse::Ok().finish())
}
31 changes: 28 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ mod http;
mod models;
mod services;

use crate::http::urls::token;
use crate::http::urls::{
delete_identity, delete_policy, delete_policy_attachment, get_identity, get_policy,
get_policy_attachment, post_identity, post_policy, post_policy_attachment, token,
};
use crate::services::base::upsert_repository::{
IdentityRepository, PolicyAttachmentRepository, PolicyRepository,
};
use crate::services::configuration_manager::ConfigurationManager;
use crate::services::identity_validator_provider;
use crate::services::token_service::TokenService;
Expand All @@ -25,8 +31,10 @@ async fn main() -> Result<()> {
let _ = tokio::spawn(cm.watch_for_identity_providers());
info!("Configuration manager started");

let policy_repository = Arc::new(RwLock::new(HashMap::new()));
let policy_attachments_repository = Arc::new(RwLock::new(HashMap::new()));
let policy_repository: Arc<PolicyRepository> = Arc::new(RwLock::new(HashMap::new()));
let policy_attachments_repository: Arc<PolicyAttachmentRepository> =
Arc::new(RwLock::new(HashMap::new()));
let identity_repository: Arc<IdentityRepository> = Arc::new(RwLock::new(HashMap::new()));

info!("listening on {}:{}", &addr.0, &addr.1);
HttpServer::new(move || {
Expand All @@ -37,8 +45,25 @@ async fn main() -> Result<()> {
Arc::clone(&secret),
));
App::new()
// Application services
.app_data(web::Data::new(token_provider))
.app_data(web::Data::new(policy_repository.clone()))
.app_data(web::Data::new(policy_attachments_repository.clone()))
.app_data(web::Data::new(identity_repository.clone()))
// Token endpoint
.service(token)
// Policy CRUD
.service(post_policy)
.service(get_policy)
.service(delete_policy)
// Identity CRUD
.service(post_identity)
.service(get_identity)
.service(delete_identity)
// Policy Attachment CRUD
.service(post_policy_attachment)
.service(get_policy_attachment)
.service(delete_policy_attachment)
})
.bind(addr)?
.run()
Expand Down
29 changes: 19 additions & 10 deletions src/models/external/identity.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize};
use std::collections::HashSet;

#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize)]
/// Struct that represents an external identity
pub struct ExternalIdentity {
/// The user ID extracted from the external identity provider
Expand All @@ -12,32 +13,40 @@ pub struct ExternalIdentity {

impl ExternalIdentity {
/// Creates a new instance of an external identity
pub fn new(user_id: String, identity_provider: String) -> Self {
pub fn new(identity_provider: String, user_id: String) -> Self {
ExternalIdentity {
user_id: user_id.to_lowercase(),
identity_provider: identity_provider.to_lowercase(),
}
}
}

#[derive(Debug, Clone)]
impl From<(String, String)> for ExternalIdentity {
fn from(value: (String, String)) -> Self {
ExternalIdentity::new(value.0, value.1)
}
}

#[derive(Debug, Clone, Serialize)]
#[allow(dead_code)]
pub struct PolicyAttachment {
pub external_identity: ExternalIdentity,
pub policies: HashSet<String>,
}

#[allow(dead_code)]
impl PolicyAttachment {
pub fn new(external_identity: ExternalIdentity, policies: HashSet<String>) -> Self {
PolicyAttachment {
external_identity,
policies,
}
pub fn new(policies: HashSet<String>) -> Self {
PolicyAttachment { policies }
}

pub fn single(policy: String) -> Self {
let mut set = HashSet::new();
set.insert(policy);
PolicyAttachment { policies: set }
}
}

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Policy {
pub content: String,
}
Expand Down
4 changes: 2 additions & 2 deletions src/services/base/upsert_repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ pub trait UpsertRepository<Entity, Key> {
async fn get(&self, key: Key) -> Result<Entity, Self::Error>;

/// Updates or inserts a policy by id
async fn upsert(&mut self, key: Key, entity: Entity) -> Result<(), Self::Error>;
async fn upsert(&self, key: Key, entity: Entity) -> Result<(), Self::Error>;

/// Deletes policy by id
async fn delete(&mut self, key: Key) -> Result<(), Self::Error>;
async fn delete(&self, key: Key) -> Result<(), Self::Error>;
}
#[allow(dead_code)]
pub type IdentityRepository =
Expand Down
2 changes: 1 addition & 1 deletion src/services/external_identity_validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ fn extract_user_id(
) -> Option<ExternalIdentity> {
let value = claims.get(user_id_claim)?;
let user_id = value.as_str()?.to_owned();
Some(ExternalIdentity::new(user_id, identity_provider))
Some(ExternalIdentity::new(identity_provider, user_id))
}

#[async_trait]
Expand Down
13 changes: 6 additions & 7 deletions src/services/repositories/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl UpsertRepository<ExternalIdentity, (String, String)>
}

async fn upsert(
&mut self,
&self,
key: (String, String),
entity: ExternalIdentity,
) -> Result<(), Self::Error> {
Expand All @@ -29,7 +29,7 @@ impl UpsertRepository<ExternalIdentity, (String, String)>
Ok(())
}

async fn delete(&mut self, key: (String, String)) -> Result<(), Self::Error> {
async fn delete(&self, key: (String, String)) -> Result<(), Self::Error> {
let mut write_guard = self.write().await;
(*write_guard).remove(&key);
Ok(())
Expand All @@ -48,13 +48,13 @@ impl UpsertRepository<Policy, String> for RwLock<HashMap<String, Policy>> {
}
}

async fn upsert(&mut self, key: String, entity: Policy) -> Result<(), Self::Error> {
async fn upsert(&self, key: String, entity: Policy) -> Result<(), Self::Error> {
let mut write_guard = self.write().await;
(*write_guard).insert(key, entity);
Ok(())
}

async fn delete(&mut self, key: String) -> Result<(), Self::Error> {
async fn delete(&self, key: String) -> Result<(), Self::Error> {
let mut write_guard = self.write().await;
(*write_guard).remove(&key);
Ok(())
Expand All @@ -76,7 +76,7 @@ impl UpsertRepository<PolicyAttachment, ExternalIdentity>
}

async fn upsert(
&mut self,
&self,
key: ExternalIdentity,
entity: PolicyAttachment,
) -> Result<(), Self::Error> {
Expand All @@ -85,7 +85,6 @@ impl UpsertRepository<PolicyAttachment, ExternalIdentity>
Some(entity) => {
let new_policies = entity.policies.union(&entity.policies).cloned().collect();
let new_entity = PolicyAttachment {
external_identity: entity.external_identity.clone(),
policies: new_policies,
};
(*write_guard).insert(key, new_entity);
Expand All @@ -97,7 +96,7 @@ impl UpsertRepository<PolicyAttachment, ExternalIdentity>
Ok(())
}

async fn delete(&mut self, key: ExternalIdentity) -> Result<(), Self::Error> {
async fn delete(&self, key: ExternalIdentity) -> Result<(), Self::Error> {
let mut write_guard = self.write().await;
(*write_guard).remove(&key);
Ok(())
Expand Down