Skip to content

Commit

Permalink
feat: Support Broker Authentication Mechanisms [BC]
Browse files Browse the repository at this point in the history
∙
∙ pact-graph-network now supports Pact Broker Auth

For Basic Auth users, set

∙  - PACT_BROKER_USERNAME
∙    - PACT_BROKER_PASSWORD

For Bearer Token users, set

   - PACT_BROKER_TOKEN

For options, see `--help`

Notes:- description/metadata fields set to optional. This was due to errors
seen using the https://testdemo.pactflow.io hosted broker, it may be due to invalid
contracts.
  • Loading branch information
YOU54F authored and Guillaume CAMUS committed Jun 8, 2023
1 parent 1dc7759 commit 9b91b8a
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 52 deletions.
67 changes: 47 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,21 @@ Available for linux, alpine and OSX.

# Table of contents

* [Pact graph network](#pact-graph-network)
* [Broker APIs](#broker-apis)
* [Table of contents](#table-of-contents)
* [Screenshots](#screenshots)
* [Tech Stack](#tech-stack)
* [Features](#features)
* [How to install](#how-to-install)
* [Usage](#usage)
* [Options](#options)
* [Environment Variables](#environment-variables)
* [Feedback](#feedback)
* [License](#license)
- [Pact graph network](#pact-graph-network)
- [Broker APIs](#broker-apis)
- [Table of contents](#table-of-contents)
- [Screenshots](#screenshots)
- [Tech Stack](#tech-stack)
- [Features](#features)
- [How to install](#how-to-install)
- [Usage](#usage)
- [Basic Auth](#basic-auth)
- [Bearer Auth](#bearer-auth)
- [Environment Variables](#environment-variables)
- [Options](#options)
- [Environment Variables](#environment-variables-1)
- [Feedback](#feedback)
- [License](#license)

## Screenshots

Expand All @@ -55,7 +58,7 @@ This project is created with:
- [x] generate a force directed layout chart
- [x] exclude sevices with pattern
- [ ] filter only services
- [ ] add support fort Pact Broker authentification
- [X] add support fort Pact Broker authentification (Basic Auth + Bearer Based)

## How to install

Expand All @@ -71,22 +74,46 @@ chmod u+x $HOME/.local/bin/pact-graph-network

## Usage

Generate the graph

~~~bash
pact-graph-network \
--url https://pact-brocker.your.com/ \
--output report
~~~

View the output in your browser

~~~bash
open report/edge-bundling.html
~~~

### Basic Auth

~~~bash
pact-graph-network --url https://pact-brocker.your.com/ --output report --username $PACT_BROKER_USERNAME --password $PACT_BROKER_PASSWORD
~~~

### Bearer Auth

~~~bash
pact-graph-network --url https://pact-brocker.your.com/ --output report --token $PACT_BROKER_TOKEN
~~~

## Environment Variables
### Options

```
-u, --url <URL> Pact broker URL
-o, --output <OUTPUT> Path of the output dir [default: report]
-g, --graph <GRAPH> [default: edge] [possible values: edge, directed]
--timeout <TIMEOUT> timeout of http request in milliseconds [default: 2000]
--exclude <EXCLUDE> list of service to exclude
-h, --help Print help information
-V, --version Print version information
-b, --url <URL> Pact broker URL
-u, --username <USERNAME> Pact broker username
-p, --password <PASSWORD> Pact broker password
-t, --token <TOKEN> Pact broker token
-o, --output <OUTPUT> Path of the output dir [default: report]
-g, --graph <GRAPH> [default: edge] [possible values: edge, directed]
--timeout <TIMEOUT> timeout of http request in milliseconds [default: 2000]
--exclude <EXCLUDE> list of service to exclude
-h, --help Print help information
-V, --version Print version information
```

### Environment Variables
Expand Down
27 changes: 20 additions & 7 deletions pact-broker-api/src/client/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use snafu::{Backtrace, Snafu};
use snafu::{Backtrace, ErrorCompat, Snafu};

#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
Expand All @@ -7,19 +7,32 @@ pub enum Error {
source: url::ParseError,
backtrace: Backtrace,
},
#[snafu(display("HTTP Error: {}\n\nFound at {}", source, backtrace))]
#[snafu(display("HTTP Error: {}", source))]
Http {
source: reqwest::Error,
backtrace: Backtrace,
#[snafu(backtrace)]
backtrace: Option<Backtrace>,
},
#[snafu(display("Serde Error: {}\nFound at {}", source, backtrace))]
#[snafu(display("Serde Error: {}", source))]
Serde {
source: serde_json::Error,
backtrace: Backtrace,
#[snafu(backtrace)]
backtrace: Option<Backtrace>,
},
#[snafu(display("JSON Error in {}: {}\nFound at {}", source.path(), source.inner(), backtrace))]
#[snafu(display("JSON Error in {}: {}", source.path(), source.inner()))]
Json {
source: serde_path_to_error::Error<serde_json::Error>,
backtrace: Backtrace,
#[snafu(backtrace)]
backtrace: Option<Backtrace>,
},
}

impl Error {
pub fn display_backtrace(&self, verbose: bool) {
if verbose {
if let Some(backtrace) = self.backtrace() {
eprintln!("{}", backtrace);
}
}
}
}
4 changes: 2 additions & 2 deletions pact-broker-models/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
pub struct Contract {
pub consumer: Pacticant,
pub interactions: Option<Vec<Interaction>>,
pub metadata: Metadata,
pub metadata: Option<Metadata>,
pub provider: Pacticant,
#[serde(rename = "createdAt")]
pub created_at: String,
Expand All @@ -21,7 +21,7 @@ pub struct Pacticant {
pub struct Interaction {
#[serde(rename = "_id")]
pub id: String,
pub description: String,
pub description: Option<String>,
#[serde(rename = "providerStates")]
pub provider_states: Option<Vec<State>>,
pub request: Request,
Expand Down
11 changes: 10 additions & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,17 @@ pub enum GraphChoice {
)]
pub struct Cli {
/// Pact broker URL
#[arg(short, long)]
#[arg(short = 'b', long)]
pub url: String,
/// Pact broker username
#[arg(short, long)]
pub username: Option<String>,
/// Pact broker password
#[arg(short, long)]
pub password: Option<String>,
/// Pact broker token
#[arg(short, long)]
pub token: Option<String>,
/// Path of the output dir
#[arg(short, long, default_value = "report")]
pub output: String,
Expand Down
59 changes: 37 additions & 22 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,30 +21,45 @@ pub async fn run(args: Cli) -> Result<()> {

let timeout = Duration::from_millis(args.timeout as u64);

let api = Builder::new()
let mut api_builder = Builder::new()
.base_url(args.url)
.unwrap()
.with_timeout(timeout)
.build()
.unwrap();

let urls: Vec<Url> = api
.pacts()
.latest()
.await
.unwrap()
.pacts
.iter()
.filter_map(|pact| match pact.links.links_self.first() {
Some(link) => match Url::parse(link.href.as_str()) {
Ok(link) => Some(link),
Err(_) => None,
},
None => None,
})
.collect();

let data = api.batch_get::<Contract>(urls, None).await.unwrap();
.with_timeout(timeout);

if let (Some(username), Some(password)) = (args.username, args.password) {
api_builder = api_builder.basic_auth(&username, &password);
}

if let Some(token) = args.token {
api_builder = api_builder.token(&token);
}

let api = api_builder.build().unwrap();
let urls: Vec<Url> = match api.pacts().latest().await {
Ok(pacts) => pacts
.pacts
.iter()
.filter_map(|pact| match pact.links.links_self.first() {
Some(link) => match Url::parse(link.href.as_str()) {
Ok(link) => Some(link),
Err(_) => None,
},
None => None,
})
.collect(),
Err(e) => {
eprintln!("Failed to fetch latests pacts:");
return Err(e.into());
}
};

let data = match api.batch_get::<Contract>(urls, None).await {
Ok(data) => data,
Err(e) => {
eprintln!("Failed to fetch iterate over contracts:");
return Err(e.into());
}
};

let graph = dataset::Graph::from(&data);
let json_data = serde_json::to_string(&graph)?;
Expand Down

0 comments on commit 9b91b8a

Please sign in to comment.