Initial commit
This commit is contained in:
commit
c708a2690c
7 changed files with 1820 additions and 0 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
/target
|
1372
Cargo.lock
generated
Normal file
1372
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
15
Cargo.toml
Normal file
15
Cargo.toml
Normal file
|
@ -0,0 +1,15 @@
|
|||
[package]
|
||||
name = "concourse-http-resource"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.91"
|
||||
hex = "0.4.3"
|
||||
reqwest = { version = "0.12.8", features = ["json", "multipart"] }
|
||||
serde = { version = "1.0.213", features = ["derive"] }
|
||||
serde_json = "1.0.132"
|
||||
serde_yaml = "0.9.34"
|
||||
sha3 = "0.10.8"
|
||||
tokio = { version = "1.41.0", features = ["fs", "macros", "rt-multi-thread"] }
|
||||
url = { version = "2.5.2", features = ["serde"] }
|
9
LICENSE
Normal file
9
LICENSE
Normal file
|
@ -0,0 +1,9 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2024 redxef
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
2
README.md
Normal file
2
README.md
Normal file
|
@ -0,0 +1,2 @@
|
|||
# concourse-http-resource
|
||||
|
239
src/main.rs
Normal file
239
src/main.rs
Normal file
|
@ -0,0 +1,239 @@
|
|||
use anyhow::{anyhow, Result};
|
||||
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
|
||||
use sha3::Digest;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, BufReader, BufWriter};
|
||||
use std::str::FromStr;
|
||||
use std::{
|
||||
env,
|
||||
ffi::OsStr,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
pub mod model;
|
||||
|
||||
async fn build_request(
|
||||
source: &model::Source,
|
||||
srcpath: Option<&Path>,
|
||||
) -> Result<(reqwest::Client, reqwest::Request)> {
|
||||
let mut request_builder =
|
||||
reqwest::Client::new().request(source.method.0.clone(), source.url.clone());
|
||||
let headers: Result<Vec<(_, _)>> = source
|
||||
.headers
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(|(k, v)| {
|
||||
let hn = HeaderName::from_str(&k)?;
|
||||
let hv = HeaderValue::from_str(&v)?;
|
||||
Ok((hn, hv))
|
||||
})
|
||||
.collect();
|
||||
request_builder = request_builder.headers(HeaderMap::from_iter(headers?));
|
||||
request_builder = request_builder.query(&source.query);
|
||||
request_builder = match &source.auth {
|
||||
None => request_builder,
|
||||
Some(auth) => match auth {
|
||||
model::Auth::Basic(b) => {
|
||||
request_builder.basic_auth(b.username.clone(), Some(b.password.clone()))
|
||||
}
|
||||
model::Auth::Bearer(b) => request_builder.bearer_auth(b),
|
||||
},
|
||||
};
|
||||
if let Some(source_body) = &source.body {
|
||||
if let Some(srcpath_) = srcpath {
|
||||
request_builder = match source_body {
|
||||
model::Body::Raw(rb) => {
|
||||
let mut buffer = Vec::<u8>::new();
|
||||
let mut file = tokio::fs::File::open(srcpath_.to_owned().join(rb)).await?;
|
||||
let read = file.read_buf(&mut buffer).await?;
|
||||
buffer.truncate(read);
|
||||
request_builder.body(buffer)
|
||||
}
|
||||
model::Body::Form(fb) => {
|
||||
let mut buffer = Vec::<u8>::new();
|
||||
let mut file = tokio::fs::File::open(srcpath_.to_owned().join(fb)).await?;
|
||||
let read = file.read_buf(&mut buffer).await?;
|
||||
buffer.truncate(read);
|
||||
request_builder
|
||||
.form(&serde_json::from_slice::<HashMap<String, String>>(&buffer)?)
|
||||
}
|
||||
model::Body::Multipart(fbvec) => {
|
||||
let mut form = reqwest::multipart::Form::new();
|
||||
for mb in fbvec {
|
||||
let mb_ = srcpath_.to_owned().join(mb);
|
||||
let mut buffer = Vec::<u8>::new();
|
||||
let mut file = tokio::fs::File::open(&mb_).await?;
|
||||
let read = file.read_buf(&mut buffer).await?;
|
||||
buffer.truncate(read);
|
||||
let name = mb_
|
||||
.file_name()
|
||||
.ok_or_else(|| anyhow!("Failed to get file name"))?
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow!("Failed to get file name"))?
|
||||
.to_string();
|
||||
form = form.part(name, reqwest::multipart::Part::bytes(buffer));
|
||||
}
|
||||
request_builder.multipart(form)
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
let (client, request) = request_builder.build_split();
|
||||
let request: reqwest::Request = request?;
|
||||
Ok((client, request))
|
||||
}
|
||||
|
||||
async fn check(input: model::CheckInput) -> Result<model::CheckOutput> {
|
||||
let (client, request) = build_request(&input.source, None).await?;
|
||||
let mut response = client.execute(request).await?;
|
||||
Ok(model::CheckOutput(
|
||||
match input.source.version_check_method {
|
||||
model::VersionCheckMethod::None => vec![model::Version::None],
|
||||
model::VersionCheckMethod::Hash => {
|
||||
let mut hasher = sha3::Sha3_256::new();
|
||||
while let Some(chunk) = response.chunk().await? {
|
||||
hasher.update(&chunk);
|
||||
}
|
||||
let hash = hasher.finalize();
|
||||
vec![model::Version::Hash(hex::encode(hash))]
|
||||
}
|
||||
model::VersionCheckMethod::Header(headername) => {
|
||||
let headervalue: &HeaderValue = response
|
||||
.headers()
|
||||
.get(headername)
|
||||
.ok_or_else(|| anyhow!(""))?;
|
||||
vec![model::Version::Header(headervalue.to_str()?.to_string())]
|
||||
}
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
async fn in_(input: model::InInput, dest: &Path) -> Result<model::InOutput> {
|
||||
let input: model::InInput = model::InInput {
|
||||
source: input.source.merge_params(&input.params),
|
||||
version: input.version,
|
||||
params: input.params,
|
||||
};
|
||||
let (client, request) = build_request(&input.source, None).await?;
|
||||
let mut response = client.execute(request).await?;
|
||||
|
||||
let dest_code = dest.to_owned().join("code");
|
||||
let dest_headers = dest.to_owned().join("headers");
|
||||
let dest_bytes = dest.to_owned().join("output");
|
||||
|
||||
let mut dest_code_writer = tokio::io::BufWriter::new(tokio::fs::File::create(dest_code).await?);
|
||||
dest_code_writer
|
||||
.write_all(response.status().to_string().as_bytes())
|
||||
.await?;
|
||||
dest_code_writer.flush().await?;
|
||||
|
||||
let response_headers: Result<Vec<(String, String)>> = response
|
||||
.headers()
|
||||
.iter()
|
||||
.map(|(headername, headervalue)| {
|
||||
Ok((
|
||||
headername.as_str().to_string(),
|
||||
headervalue.to_str()?.to_string(),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let mut dest_headers_writer =
|
||||
tokio::io::BufWriter::new(tokio::fs::File::create(dest_headers).await?);
|
||||
dest_headers_writer
|
||||
.write_all(serde_json::to_vec(&response_headers?)?.as_ref())
|
||||
.await?;
|
||||
|
||||
let mut hasher = sha3::Sha3_256::new();
|
||||
let mut dest_bytes_writer =
|
||||
tokio::io::BufWriter::new(tokio::fs::File::create(dest_bytes).await?);
|
||||
while let Some(chunk) = response.chunk().await? {
|
||||
if input.source.version_check_method == model::VersionCheckMethod::Hash {
|
||||
hasher.update(&chunk);
|
||||
}
|
||||
dest_bytes_writer.write_all(&chunk).await?;
|
||||
}
|
||||
let hash = hasher.finalize();
|
||||
dest_bytes_writer.flush().await?;
|
||||
|
||||
let out = model::InOutput {
|
||||
version: match input.source.version_check_method {
|
||||
model::VersionCheckMethod::None => model::Version::None,
|
||||
model::VersionCheckMethod::Hash => model::Version::Hash(hex::encode(hash)),
|
||||
model::VersionCheckMethod::Header(headername) => {
|
||||
let headervalue: &HeaderValue = response
|
||||
.headers()
|
||||
.get(headername)
|
||||
.ok_or_else(|| anyhow!(""))?;
|
||||
model::Version::Header(headervalue.to_str()?.to_string())
|
||||
}
|
||||
},
|
||||
metadata: vec![],
|
||||
};
|
||||
if out.version != input.version {
|
||||
return Err(anyhow!(format!(
|
||||
"Did not get correct version of resource, requested '{:?}', got '{:?}'",
|
||||
input.version, out.version
|
||||
)));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
async fn out(input: model::OutInput, src: &Path) -> Result<model::OutOutput> {
|
||||
let input = model::OutInput {
|
||||
source: input.source.merge_params(&input.params),
|
||||
params: input.params,
|
||||
};
|
||||
let (client, request) = build_request(&input.source, Some(src)).await?;
|
||||
let response = client.execute(request).await?;
|
||||
response.error_for_status()?;
|
||||
let version = check(model::CheckInput {
|
||||
source: input.source.clone(),
|
||||
version: model::Version::None,
|
||||
})
|
||||
.await?
|
||||
.0[0]
|
||||
.clone();
|
||||
Ok(model::OutOutput {
|
||||
version,
|
||||
metadata: vec![],
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let mut args = env::args();
|
||||
let operation: PathBuf = args
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("No binary name! This should never happen"))?
|
||||
.into();
|
||||
let operation: &OsStr = operation
|
||||
.file_name()
|
||||
.ok_or_else(|| anyhow!("Could not get binary name! This should never happen"))?;
|
||||
if operation == "check" {
|
||||
let input: model::CheckInput = serde_json::from_reader(BufReader::new(io::stdin()))?;
|
||||
let r = check(input).await?;
|
||||
serde_json::to_writer(BufWriter::new(io::stdout()), &r)?;
|
||||
Ok(())
|
||||
} else if operation == "in" {
|
||||
let input: model::InInput = serde_json::from_reader(BufReader::new(io::stdin()))?;
|
||||
let path: PathBuf = args
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("No destination specified!"))?
|
||||
.into();
|
||||
let r = in_(input, &path).await?;
|
||||
serde_json::to_writer(BufWriter::new(io::stdout()), &r)?;
|
||||
Ok(())
|
||||
} else if operation == "out" {
|
||||
let input: model::OutInput = serde_json::from_reader(BufReader::new(io::stdin()))?;
|
||||
let path: PathBuf = args
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("No destination specified!"))?
|
||||
.into();
|
||||
let r = out(input, &path).await?;
|
||||
serde_json::to_writer(BufWriter::new(io::stdout()), &r)?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("Invalid binary name!"))
|
||||
}
|
||||
}
|
182
src/model.rs
Normal file
182
src/model.rs
Normal file
|
@ -0,0 +1,182 @@
|
|||
use anyhow::Result;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Method(pub reqwest::Method);
|
||||
|
||||
impl From<reqwest::Method> for Method {
|
||||
fn from(item: reqwest::Method) -> Self {
|
||||
Method(item)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Method {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
struct MethodData(String);
|
||||
|
||||
let data = MethodData::deserialize(deserializer)?;
|
||||
let r_m = reqwest::Method::from_str(&data.0.to_uppercase());
|
||||
match r_m {
|
||||
Ok(r_m) => Ok(r_m.into()),
|
||||
Err(_e) => Err(serde::de::Error::custom(format!(
|
||||
"No such method '{}'",
|
||||
data.0
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Method {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(&self.0.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AuthBasic {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Auth {
|
||||
Basic(AuthBasic),
|
||||
Bearer(String),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Body {
|
||||
Raw(PathBuf),
|
||||
Form(PathBuf),
|
||||
Multipart(Vec<PathBuf>),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum VersionCheckMethod {
|
||||
Header(String),
|
||||
#[default]
|
||||
Hash,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Source {
|
||||
pub url: url::Url,
|
||||
pub method: Method,
|
||||
#[serde(default)]
|
||||
pub headers: Vec<(String, String)>,
|
||||
#[serde(default)]
|
||||
pub query: Vec<(String, String)>,
|
||||
#[serde(default)]
|
||||
pub auth: Option<Auth>,
|
||||
#[serde(default)]
|
||||
pub body: Option<Body>,
|
||||
#[serde(default)]
|
||||
pub version_check_method: VersionCheckMethod,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
pub fn merge_params(self, params: &Params) -> Self {
|
||||
let url = self.url.clone();
|
||||
let mut method: Method = self.method.clone();
|
||||
let mut headers: Vec<(String, String)> = self.headers.clone();
|
||||
let mut query: Vec<(String, String)> = self.query.clone();
|
||||
let mut auth: Option<Auth> = self.auth.clone();
|
||||
let mut body: Option<Body> = self.body.clone();
|
||||
let version_check_method = self.version_check_method.clone();
|
||||
if let Some(params_method) = ¶ms.method {
|
||||
method = params_method.clone();
|
||||
}
|
||||
if let Some(params_headers) = ¶ms.headers {
|
||||
headers.extend(params_headers.clone());
|
||||
}
|
||||
if let Some(params_query) = ¶ms.query {
|
||||
query.extend(params_query.clone());
|
||||
}
|
||||
if let Some(params_auth) = ¶ms.auth {
|
||||
auth = Some(params_auth.clone());
|
||||
}
|
||||
if let Some(params_body) = ¶ms.body {
|
||||
body = Some(params_body.clone());
|
||||
}
|
||||
|
||||
Self {
|
||||
url,
|
||||
method,
|
||||
headers,
|
||||
query,
|
||||
auth,
|
||||
body,
|
||||
version_check_method,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Version {
|
||||
Header(String),
|
||||
Hash(String),
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Metadata {
|
||||
pub name: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Params {
|
||||
pub method: Option<Method>,
|
||||
pub headers: Option<Vec<(String, String)>>,
|
||||
pub query: Option<Vec<(String, String)>>,
|
||||
pub auth: Option<Auth>,
|
||||
pub body: Option<Body>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CheckInput {
|
||||
pub source: Source,
|
||||
pub version: Version,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct InInput {
|
||||
pub source: Source,
|
||||
pub version: Version,
|
||||
pub params: Params,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct OutInput {
|
||||
pub source: Source,
|
||||
pub params: Params,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CheckOutput(pub Vec<Version>);
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct InOutput {
|
||||
pub version: Version,
|
||||
pub metadata: Vec<Metadata>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct OutOutput {
|
||||
pub version: Version,
|
||||
pub metadata: Vec<Metadata>,
|
||||
}
|
Loading…
Reference in a new issue