Skip to content
Draft
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,795 changes: 1,795 additions & 0 deletions actions/websocket-action/Cargo.lock

Large diffs are not rendered by default.

25 changes: 25 additions & 0 deletions actions/websocket-action/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[package]
name = "websocket-action"
version = "0.0.0"
edition = "2024"
publish = false

[dependencies]
hercules = { git = "https://github.com/code0-tech/hercules.git", branch = "#22-primitive-rust-sdk" }
tucana = { version = "0.0.80", default-features = false }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time"] }
tokio-stream = "0.1"
tokio-tungstenite = { version = "0.30", features = ["rustls-tls-webpki-roots"] }
futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] }
http = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
schemars = "1"
log = "0.4"
env_logger = "0.11"
regex = "1"
percent-encoding = "2.3"
form_urlencoded = "1.2"
base64 = "0.22"
ring = "0.17"
uuid = { version = "1", features = ["v4"] }
159 changes: 159 additions & 0 deletions actions/websocket-action/src/auth/credentials.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
use base64::Engine;
use tucana::shared::{Struct, Value, value::Kind};

use super::jwt::validate_hs256_jwt;
use super::types::AuthenticationType;

pub(super) fn matches_authorization(
auth_type: AuthenticationType,
auth_value: &Value,
authorization: &str,
) -> bool {
match auth_type {
AuthenticationType::BearerJwt => {
let Some(secret) = value_as_string(auth_value) else {
return false;
};
validate_hs256_jwt(authorization, secret)
}
AuthenticationType::BearerStatic => {
let Some(expected_token) = value_as_string(auth_value) else {
return false;
};
authorization.trim() == format!("Bearer {}", expected_token.trim())
}
AuthenticationType::Basic => {
let Some(credentials) = basic_credentials(auth_value) else {
return false;
};
let expected_encoded =
base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes());
authorization.trim() == format!("Basic {}", expected_encoded)
}
}
}

/// Builds the `Authorization` header value to *send* on an outbound client
/// handshake, given the flow's configured auth type/value — the inverse of
/// [`matches_authorization`], which *validates* an inbound one.
///
/// `BearerJwt` and `BearerStatic` are handled identically here: this action
/// doesn't mint JWTs (it only validates HS256 signatures on the inbound
/// side, see `jwt.rs`), so a `Bearer JWT`-configured outbound connection just
/// sends the configured value verbatim as the bearer token, same as
/// `Bearer static`. The operator is expected to supply an already-encoded
/// token in that case.
pub(super) fn build_authorization_header(
auth_type: AuthenticationType,
auth_value: &Value,
) -> Option<String> {
match auth_type {
AuthenticationType::BearerJwt | AuthenticationType::BearerStatic => {
value_as_string(auth_value).map(|token| format!("Bearer {}", token.trim()))
}
AuthenticationType::Basic => {
let credentials = basic_credentials(auth_value)?;
let encoded = base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes());
Some(format!("Basic {encoded}"))
}
}
}

fn basic_credentials(value: &Value) -> Option<String> {
if let Some(credentials) = value_as_string(value) {
return Some(credentials.trim().to_string());
}

let Some(Kind::StructValue(Struct { fields })) = value.kind.as_ref() else {
return None;
};

let username = fields
.get("username")
.or_else(|| fields.get("user"))
.and_then(value_as_string)?;
let password = fields
.get("password")
.or_else(|| fields.get("pass"))
.and_then(value_as_string)?;

Some(format!("{username}:{password}"))
}

fn value_as_string(value: &Value) -> Option<&str> {
match value.kind.as_ref() {
Some(Kind::StringValue(value)) => Some(value.as_str()),
_ => None,
}
}

#[cfg(test)]
mod tests {
use std::collections::HashMap;
use tucana::shared::{Struct, Value, value::Kind};

use super::matches_authorization;
use crate::auth::jwt::tests::create_hs256_jwt;
use crate::auth::types::AuthenticationType;

#[test]
fn bearer_static_matches_expected_token() {
let value = string_value("secret");
assert!(matches_authorization(
AuthenticationType::BearerStatic,
&value,
"Bearer secret"
));
assert!(!matches_authorization(
AuthenticationType::BearerStatic,
&value,
"Bearer other"
));
}

#[test]
fn bearer_jwt_verifies_hs256_token() {
let secret = string_value("jwt-secret");
let token = create_hs256_jwt("jwt-secret", r#"{"sub":"123"}"#);
assert!(matches_authorization(
AuthenticationType::BearerJwt,
&secret,
&format!("Bearer {token}")
));
assert!(!matches_authorization(
AuthenticationType::BearerJwt,
&secret,
"Bearer header.payload.bad-signature"
));
}

#[test]
fn basic_matches_encoded_username_password_object_pair() {
let value = basic_value("user", "pass");
assert!(matches_authorization(
AuthenticationType::Basic,
&value,
"Basic dXNlcjpwYXNz"
));
assert!(!matches_authorization(
AuthenticationType::Basic,
&value,
"Basic dXNlcjpvdGhlcg=="
));
}

fn string_value(value: &str) -> Value {
Value {
kind: Some(Kind::StringValue(value.to_string())),
}
}

fn basic_value(username: &str, password: &str) -> Value {
let mut fields = HashMap::new();
fields.insert("username".to_string(), string_value(username));
fields.insert("password".to_string(), string_value(password));
Value {
kind: Some(Kind::StructValue(Struct { fields })),
}
}
}
131 changes: 131 additions & 0 deletions actions/websocket-action/src/auth/jwt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
use base64::Engine;
use ring::hmac;
use std::time::{SystemTime, UNIX_EPOCH};

pub(super) fn validate_hs256_jwt(authorization: &str, secret: &str) -> bool {
let Some(token) = authorization.trim().strip_prefix("Bearer ") else {
return false;
};

validate_token(token, secret)
}

fn validate_token(token: &str, secret: &str) -> bool {
let mut segments = token.split('.');
let Some(header_segment) = segments.next() else {
return false;
};
let Some(payload_segment) = segments.next() else {
return false;
};
let Some(signature_segment) = segments.next() else {
return false;
};

if segments.next().is_some() {
return false;
}

let Some(header) = decode_json_segment(header_segment) else {
return false;
};

// The flow stores only one shared secret, so JWT auth is intentionally
// limited to HS256. Supporting RS/ES algorithms would require a public
// key or JWKS setting instead of a secret string.
if header.get("alg").and_then(|alg| alg.as_str()) != Some("HS256") {
return false;
}

if !verify_signature(header_segment, payload_segment, signature_segment, secret) {
return false;
}

let Some(payload) = decode_json_segment(payload_segment) else {
return false;
};

token_is_not_expired(&payload)
}

fn verify_signature(
header_segment: &str,
payload_segment: &str,
signature_segment: &str,
secret: &str,
) -> bool {
let Some(signature) = decode_base64_url(signature_segment) else {
return false;
};

let signing_input = format!("{header_segment}.{payload_segment}");
let key = hmac::Key::new(hmac::HMAC_SHA256, secret.as_bytes());

hmac::verify(&key, signing_input.as_bytes(), &signature).is_ok()
}

fn token_is_not_expired(payload: &serde_json::Value) -> bool {
let Some(exp) = payload.get("exp").and_then(|exp| exp.as_i64()) else {
return true;
};

let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) else {
return false;
};

exp > now.as_secs() as i64
}

fn decode_json_segment(segment: &str) -> Option<serde_json::Value> {
let bytes = decode_base64_url(segment)?;
serde_json::from_slice::<serde_json::Value>(&bytes).ok()
}

fn decode_base64_url(value: &str) -> Option<Vec<u8>> {
base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(value)
.or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(value))
.ok()
}

#[cfg(test)]
pub(crate) mod tests {
use base64::Engine;
use ring::hmac;

use super::validate_hs256_jwt;

#[test]
fn verifies_hs256_token() {
let token = create_hs256_jwt("jwt-secret", r#"{"sub":"123"}"#);
assert!(validate_hs256_jwt(&format!("Bearer {token}"), "jwt-secret"));
}

#[test]
fn rejects_expired_token() {
let token = create_hs256_jwt("jwt-secret", r#"{"exp":1}"#);
assert!(!validate_hs256_jwt(
&format!("Bearer {token}"),
"jwt-secret"
));
}

#[test]
fn rejects_wrong_secret() {
let token = create_hs256_jwt("jwt-secret", r#"{"sub":"123"}"#);
assert!(!validate_hs256_jwt(&format!("Bearer {token}"), "wrong"));
}

pub(crate) fn create_hs256_jwt(secret: &str, payload: &str) -> String {
let header = r#"{"alg":"HS256","typ":"JWT"}"#;
let header_segment = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(header);
let payload_segment = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload);
let signing_input = format!("{header_segment}.{payload_segment}");
let key = hmac::Key::new(hmac::HMAC_SHA256, secret.as_bytes());
let signature = hmac::sign(&key, signing_input.as_bytes());
let signature_segment =
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(signature.as_ref());

format!("{signing_input}.{signature_segment}")
}
}
Loading