Skip to content

Commit

Permalink
refactor: clean up code
Browse files Browse the repository at this point in the history
  • Loading branch information
nanderstabel committed Jul 23, 2024
1 parent dd630e0 commit 3295f41
Show file tree
Hide file tree
Showing 19 changed files with 33 additions and 213 deletions.
3 changes: 1 addition & 2 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
AGENT__LOG_FORMAT=text
AGENT__EVENT_STORE__TYPE=postgres
AGENT__EVENT_STORE__CONNECTION_STRING="postgresql://demo_user:demo_pass@localhost:5432/demo"
AGENT__URL="http://192.168.1.234:3033"
AGENT__EVENT_STORE__CONNECTION_STRING="postgresql://demo_user:demo_pass@cqrs-postgres-db:5432/demo"

AGENT__SECRET_MANAGER__STRONGHOLD_PATH="agent_secret_manager/tests/res/test.stronghold"
AGENT__SECRET_MANAGER__STRONGHOLD_PASSWORD="secure_password"
Expand Down
1 change: 0 additions & 1 deletion 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 agent_api_rest/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Browse to http://localhost:9090

### CORS

If you want to access UniCore's API from a browser, you can set the `AGENT_APPLICATION_CORS_ENABLED` environment variable to `true`. This will enable a permissive CORS policy (allow all).
If you want to access UniCore's API from a browser, you can set the `AGENT__CORS_ENABLED` environment variable to `true`. This will enable a permissive CORS policy (allow all).

## Usage
Below we describe a typical usage of the REST API for UniCore.
Expand Down
48 changes: 1 addition & 47 deletions agent_api_rest/src/issuance/credential_issuer/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ pub(crate) async fn credential(
_ => return StatusCode::UNAUTHORIZED.into_response(),
};

info!("test1");

// Get the `credential_issuer_metadata` and `authorization_server_metadata` from the `ServerConfigView`.
let (credential_issuer_metadata, authorization_server_metadata) =
match query_handler(SERVER_CONFIG_ID, &state.query.server_config).await {
Expand All @@ -54,32 +52,23 @@ pub(crate) async fn credential(
_ => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
};

info!("test2");

let command = OfferCommand::VerifyCredentialRequest {
offer_id: offer_id.clone(),
credential_issuer_metadata,
authorization_server_metadata,
credential_request,
};

info!("test3");

// Use the `offer_id` to verify the `proof` inside the `CredentialRequest`.
if command_handler(&offer_id, &state.command.offer, command).await.is_err() {
StatusCode::INTERNAL_SERVER_ERROR.into_response();
};

info!("test4");

let timeout = config()
.external_server_response_timeout_ms
.unwrap_or(DEFAULT_EXTERNAL_SERVER_RESPONSE_TIMEOUT_MS);
let start_time = Instant::now();

info!("time out: {}", timeout);
info!("test5");

// TODO: replace this polling solution with a call to the `TxChannelRegistry` as described here: https://github.com/impierce/ssi-agent/issues/75
// Use the `offer_id` to get the `credential_ids` and `subject_id` from the `OfferView`.
let (credential_ids, subject_id) = loop {
Expand All @@ -104,8 +93,6 @@ pub(crate) async fn credential(
}
};

info!("test6");

// Use the `credential_ids` and `subject_id` to sign all the credentials.
let mut signed_credentials = vec![];
for credential_id in credential_ids {
Expand All @@ -132,22 +119,16 @@ pub(crate) async fn credential(
signed_credentials.push(signed_credential);
}

info!("test7");

let command = OfferCommand::CreateCredentialResponse {
offer_id: offer_id.clone(),
signed_credentials,
};

info!("test8");

// Use the `offer_id` to create a `CredentialResponse` from the `CredentialRequest` and `credentials`.
if command_handler(&offer_id, &state.command.offer, command).await.is_err() {
StatusCode::INTERNAL_SERVER_ERROR.into_response();
};

info!("test9");

// Use the `offer_id` to get the `credential_response` from the `OfferView`.
match query_handler(&offer_id, &state.query.offer).await {
Ok(Some(OfferView {
Expand Down Expand Up @@ -213,7 +194,6 @@ mod tests {
is_self_signed: bool,
delay: u64,
) {
println!("HEEERRREE1");
Mock::given(method("POST"))
.and(path("/ssi-events-subscriber"))
.and(
Expand All @@ -222,13 +202,9 @@ mod tests {
OfferEvent::CredentialRequestVerified { offer_id, subject_id } => {
let app_clone = app.clone();

let temp = futures::executor::block_on(async {
println!("testA");

futures::executor::block_on(async {
let app_clone = app_clone.lock().await.take().unwrap();

println!("testB");

// This assertion is a representation of the 'outside' backend server retrieving the
// data that corresponds to the `offer_id`.
assert_eq!(offer_id, OFFER_ID);
Expand Down Expand Up @@ -257,12 +233,8 @@ mod tests {
}
};

println!("testC");

std::thread::sleep(Duration::from_millis(delay));

println!("testD");

// Sends the `CredentialsRequest` to the `credentials` endpoint.
app_clone
.oneshot(
Expand All @@ -279,8 +251,6 @@ mod tests {
})
.unwrap();

println!("{}", temp.status());

true
}
_ => false,
Expand Down Expand Up @@ -311,11 +281,6 @@ mod tests {

let target_url = format!("{}/ssi-events-subscriber", &external_server.uri());

// std::env::set_var("TEST_AGENT__EVENT_PUBLISHERS__HTTP__TARGET_URL", target_url.clone());
// std::env::set_var("TEST_AGENT__DID_METHODS__DID_JWK__PREFERRED", "false".to_string());
// std::env::set_var("TEST_AGENT__DID_METHODS__DID_KEY__PREFERRED", "true".to_string());
// reload_config();

set_config().enable_event_publisher_http();
set_config().set_event_publisher_http_target_url(target_url.clone());
set_config().set_event_publisher_http_target_events(Events {
Expand All @@ -332,17 +297,6 @@ mod tests {
(None, Default::default(), Default::default())
};

println!("issuance_event_publishers: {:#?}", EventPublisherHttp::load().unwrap());

println!("CONFIG: {:#?}", config());
println!(
"with_external_server: {:#?}, external_server: {}",
with_external_server,
external_server.is_some()
);
println!("is_self_signed: {:#?}", is_self_signed);
println!("delay: {:#?}", delay);

let issuance_state = in_memory::issuance_state(issuance_event_publishers).await;
let verification_state =
in_memory::verification_state(test_verification_services(), verification_event_publishers).await;
Expand Down
2 changes: 1 addition & 1 deletion agent_api_rest/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ fn get_base_path() -> Result<String, ConfigError> {
}

if base_path.is_empty() {
panic!("AGENT_APPLICATION_BASE_PATH can't be empty, remove or set path");
panic!("AGENT__BASE_PATH can't be empty, remove or set path");
}

tracing::info!("Base path: {:?}", base_path);
Expand Down
8 changes: 5 additions & 3 deletions agent_application/docker/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ services:

AGENT__SECRET_MANAGER__STRONGHOLD_PATH: "/app/res/stronghold"
AGENT__SECRET_MANAGER__STRONGHOLD_PASSWORD: "secure_password"
AGENT__SECRET_MANAGER__ISSUER_KEY_ID: "9O66nzWqYYy1LmmiOudOlh2SMIaUWoTS"
AGENT__SECRET_MANAGER__ISSUER_DID: "did:iota:rms:0x42ad588322e58b3c07aa39e4948d021ee17ecb5747915e9e1f35f028d7ecaf90"
AGENT__SECRET_MANAGER__ISSUER_FRAGMENT: "bQKQRzaop7CgEvqVq8UlgLGsdF-R-hnLFkKFZqW2VN0"

# Uncomment the following lines to use the DID method `did:iota:rms`
# AGENT__SECRET_MANAGER__ISSUER_KEY_ID: "9O66nzWqYYy1LmmiOudOlh2SMIaUWoTS"
# AGENT__SECRET_MANAGER__ISSUER_DID: "did:iota:rms:0x42ad588322e58b3c07aa39e4948d021ee17ecb5747915e9e1f35f028d7ecaf90"
# AGENT__SECRET_MANAGER__ISSUER_FRAGMENT: "bQKQRzaop7CgEvqVq8UlgLGsdF-R-hnLFkKFZqW2VN0"
volumes:
- ../../agent_application/example-config.yaml:/app/agent_application/example-config.yaml
- ../../agent_secret_manager/tests/res/test.stronghold:/app/res/stronghold
Expand Down
7 changes: 0 additions & 7 deletions agent_application/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,8 @@ async fn main() -> io::Result<()> {
match config().log_format {
LogFormat::Json => tracing_subscriber.with(tracing_subscriber::fmt::layer().json()).init(),
LogFormat::Text => tracing_subscriber.with(tracing_subscriber::fmt::layer()).init(),
// Ok(log_format) if log_format == "json" => {
// tracing_subscriber.with(tracing_subscriber::fmt::layer().json()).init()
// }
// _ => tracing_subscriber.with(tracing_subscriber::fmt::layer()).init(),
}

info!("Configuration loaded.");
info!("Configuration: {:#?}", config());

let verification_services = Arc::new(VerificationServices::new(Arc::new(Subject {
secret_manager: secret_manager().await,
})));
Expand Down
1 change: 0 additions & 1 deletion agent_event_publisher_http/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ rustls = { version = "0.23", default-features = false, features = [
] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
serde.workspace = true
serde_json.workspace = true
serde_with.workspace = true
serde_yaml.workspace = true
tokio.workspace = true
Expand Down
19 changes: 9 additions & 10 deletions agent_event_publisher_http/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,21 @@

A simple HTTP event publisher for the SSI Agent.

To make use of this publisher you need to configure it by creating a `config.yaml` file in this same directory. For each
aggregate you want to publish events for, you need to set the following properties:
To make use of this publisher you need to configure it by adding the `http` object to your configuration file.

- The `target_url` is the URL to which the events will be published.
- The `target_events` is a list of events that will be published to the `target_url`.

Example `config.yaml`:
Example:

```yaml
target_url: &target_url "https://my-domain.example.org/ssi-event-subscriber"

connection:
{
target_url: *target_url,
target_events: [SIOPv2AuthorizationResponseVerified],
}
event_publishers:
http:
enabled: false
target_url: "https://my-domain.example.org/event-subscriber"
events:
server_config: []
credential: [UnsignedCredentialCreated, CredentialSigned]
```
### Available events
Expand Down
64 changes: 0 additions & 64 deletions agent_event_publisher_http/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,35 +29,8 @@ pub struct EventPublisherHttp {

impl EventPublisherHttp {
pub fn load() -> anyhow::Result<Self> {
// #[cfg(feature = "test_utils")]
// let mut config = TEST_EVENT_PUBLISHER_HTTP_CONFIG
// .lock()
// .unwrap()
// .as_ref()
// .unwrap()
// .clone();
// #[cfg(not(feature = "test_utils"))]
// let mut config: serde_yaml::Value = {
// match std::fs::File::open("agent_event_publisher_http/config.yml") {
// Ok(config_file) => serde_yaml::from_reader(config_file)?,
// // If the config file does not exist, return an empty config.
// Err(_) => serde_yaml::Value::Null,
// }
// };
// let config = agent_shared::config::config("AGENT_EVENT_PUBLISHER_HTTP");

let event_publisher_http = config().event_publishers.clone().unwrap().http.unwrap();

// let event_publishers = config.get_table("event_publishers").unwrap_or_default();
// let event_publisher_http = event_publishers
// .get("http")
// .unwrap()
// .clone()
// .into_table()
// .unwrap_or_default();

println!("event_publisher_http: {:?}", event_publisher_http);

// If it's not enabled, return an empty event publisher.
if !event_publisher_http.enabled {
return Ok(EventPublisherHttp {
Expand All @@ -69,19 +42,6 @@ impl EventPublisherHttp {
});
}

// TODO: map events to aggregates
// let mapping = HashMap::<Event, DomainAggregate>::new();
// let mapping: HashMap<Event, DomainAggregate> = HashMap::from([
// // credential
// (Event::UnsignedCredentialCreated, DomainAggregate::Credential),
// (Event::SignedCredentialCreated, DomainAggregate::Credential),
// (Event::CredentialSigned, DomainAggregate::Credential),
// // offer
// (Event::CredentialOfferCreated, DomainAggregate::Offer),
// // connection
// (Event::SIOPv2AuthorizationResponseVerified, DomainAggregate::Connection),
// ]);

let server_config = (!event_publisher_http.events.server_config.is_empty()).then(|| {
AggregateEventPublisherHttp::<ServerConfig>::new(
event_publisher_http.target_url.clone(),
Expand Down Expand Up @@ -153,30 +113,6 @@ impl EventPublisherHttp {
info!("Loaded HTTP event publisher: {:?}", event_publisher);

Ok(event_publisher)

// let config = if event_publisher_http
// .get("enabled")
// .unwrap()
// .clone()
// .into_bool()
// .unwrap_or_default()
// {
// let publishers: serde_yaml::Value = event_publisher_http
// .get("publishers")
// .unwrap()
// .clone()
// .try_deserialize()
// .unwrap();
// publishers
// } else {
// serde_yaml::Value::Null
// };

// serde_yaml::from_value(config)
// .map_err(Into::into)
// .inspect(|event_publisher| {
// info!("Loaded HTTP event publisher: {:?}", event_publisher);
// })
}
}

Expand Down
2 changes: 1 addition & 1 deletion agent_issuance/src/server_config/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ pub mod server_config_tests {

use super::*;

use agent_shared::issuance::CredentialConfiguration;
use agent_shared::config::CredentialConfiguration;
use lazy_static::lazy_static;
use oid4vci::credential_format_profiles::w3c_verifiable_credentials::jwt_vc_json::JwtVcJson;
use oid4vci::credential_format_profiles::{w3c_verifiable_credentials, CredentialFormats, Parameters};
Expand Down
2 changes: 1 addition & 1 deletion agent_issuance/src/server_config/command.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use agent_shared::issuance::CredentialConfiguration;
use agent_shared::config::CredentialConfiguration;
use oid4vci::credential_issuer::{
authorization_server_metadata::AuthorizationServerMetadata, credential_issuer_metadata::CredentialIssuerMetadata,
};
Expand Down
1 change: 0 additions & 1 deletion agent_secret_manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,5 @@ pub async fn secret_manager() -> SecretManager {
.unwrap()
}
(snapshot_path, password, None, _, _) => SecretManager::generate(snapshot_path, password).await.unwrap(),
// _ => panic!("Unable to load or generate `SecretManager`. Please make sure to set both `AGENT__SECRET_MANAGER__STRONGHOLD_PATH` and `AGENT__SECRET_MANAGER__STRONGHOLD_PASSWORD` environment variables."),
}
}
Binary file removed agent_secret_manager/tests/res/temp.stronghold
Binary file not shown.
Loading

0 comments on commit 3295f41

Please sign in to comment.