Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/main' into gateway-support-plu…
Browse files Browse the repository at this point in the history
…gin-instance
  • Loading branch information
4t145 committed Mar 27, 2024
2 parents 159267b + e32a207 commit a788186
Show file tree
Hide file tree
Showing 30 changed files with 778 additions and 333 deletions.
132 changes: 116 additions & 16 deletions basic/src/helper/bios_ctx_helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,28 @@ use tardis::{
TardisFuns, TardisFunsInst,
};

pub async fn unsafe_fill_ctx(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
fn unsafe_check_ctx<F>(request: &Request, f: F, check: bool, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()>
where
F: FnOnce(TardisContext, &mut TardisContext),
{
if check && !ctx.owner.is_empty() {
return Ok(());
}
let bios_ctx = if let Some(bios_ctx) = request.header(&funs.rbum_head_key_bios_ctx()).or_else(|| request.header(&funs.rbum_head_key_bios_ctx().to_lowercase())) {
TardisFuns::json.str_to_obj::<TardisContext>(&TardisFuns::crypto.base64.decode_to_string(bios_ctx)?)?
} else {
return Err(TardisError::unauthorized(
&format!("[Basic] Request is not legal, missing header [{}]", funs.rbum_head_key_bios_ctx()),
"401-auth-req-ak-not-exist",
));
if ctx.owner.is_empty() && ctx.ak.is_empty() && ctx.own_paths.is_empty() && ctx.roles.is_empty() && ctx.groups.is_empty() {
return Err(TardisError::unauthorized(
&format!("[Basic] Request is not legal, missing header [{}]", funs.rbum_head_key_bios_ctx()),
"401-auth-req-ak-not-exist",
));
} else {
return Ok(());
}
};

if bios_ctx.own_paths.contains(&ctx.own_paths) {
let mut roles = bios_ctx.roles.clone();
for role in bios_ctx.roles.clone() {
if role.contains(':') {
let extend_role = role.split(':').collect::<Vec<_>>()[0];
roles.push(extend_role.to_string());
}
}
ctx.owner = bios_ctx.owner.clone();
ctx.roles = roles;
ctx.groups = bios_ctx.groups;
ctx.own_paths = bios_ctx.own_paths;
f(bios_ctx, ctx);

Ok(())
} else {
Expand All @@ -36,3 +36,103 @@ pub async fn unsafe_fill_ctx(request: &Request, funs: &TardisFunsInst, ctx: &mut
))
}
}

// xxx_check_own function will check the owner is empty or not.
pub fn check_own_fill_ctx(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
unsafe_check_ctx(
request,
|bios_ctx, ctx| {
let mut roles = bios_ctx.roles.clone();
for role in bios_ctx.roles.clone() {
if role.contains(':') {
let extend_role = role.split(':').collect::<Vec<_>>()[0];
roles.push(extend_role.to_string());
}
}
ctx.owner = bios_ctx.owner.clone();
ctx.roles = roles;
ctx.groups = bios_ctx.groups;
ctx.own_paths = bios_ctx.own_paths;
},
true,
funs,
ctx,
)
}

pub fn unsafe_fill_ctx(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
unsafe_check_ctx(
request,
|bios_ctx, ctx| {
let mut roles = bios_ctx.roles.clone();
for role in bios_ctx.roles.clone() {
if role.contains(':') {
let extend_role = role.split(':').collect::<Vec<_>>()[0];
roles.push(extend_role.to_string());
}
}
ctx.owner = bios_ctx.owner.clone();
ctx.roles = roles;
ctx.groups = bios_ctx.groups;
ctx.own_paths = bios_ctx.own_paths;
},
false,
funs,
ctx,
)
}

pub fn unsfae_fill_owner_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
unsafe_check_ctx(
request,
|bios_ctx, ctx| {
ctx.owner = bios_ctx.owner.clone();
},
false,
funs,
ctx,
)
}

pub fn unsfae_fill_own_paths_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
unsafe_check_ctx(
request,
|bios_ctx, ctx| {
ctx.own_paths = bios_ctx.own_paths;
},
false,
funs,
ctx,
)
}

pub fn unsfae_fill_roles_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
unsafe_check_ctx(
request,
|bios_ctx, ctx| {
let mut roles = bios_ctx.roles.clone();
for role in bios_ctx.roles.clone() {
if role.contains(':') {
let extend_role = role.split(':').collect::<Vec<_>>()[0];
roles.push(extend_role.to_string());
}
}
ctx.roles = roles;
},
false,
funs,
ctx,
)
}

pub fn unsfae_fill_groups_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
unsafe_check_ctx(
request,
|bios_ctx, ctx| {
ctx.groups = bios_ctx.groups;
},
false,
funs,
ctx,
)
}
1 change: 1 addition & 0 deletions gateway/spacegate-lib/src/marker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

2 changes: 1 addition & 1 deletion gateway/spacegate-lib/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ pub mod anti_xss;
pub mod audit_log;
pub mod auth;
pub mod ip_time;
pub mod rewrite_ns_b_ip;
pub mod rewrite_ns_b_ip;
4 changes: 4 additions & 0 deletions gateway/spacegate-lib/src/plugin/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,10 @@ fn success_auth_result_to_req(auth_result: AuthResult, config: &AuthConfig, req:
let auth_resp: AuthResp = auth_result.into();
parts.headers.extend(hashmap_header_to_headermap(auth_resp.headers.clone())?);
if let Some(new_body) = auth_resp.body {
parts.headers.insert(
header::CONTENT_LENGTH,
HeaderValue::from_str(&format!("{}", new_body.as_bytes().len())).map_err(|e| TardisError::format_error(&format!("[SG.Filter.Auth] error parse str :{e}"), ""))?,
);
body = SgBody::full(new_body);
};
Ok(Request::from_parts(parts, body))
Expand Down
24 changes: 12 additions & 12 deletions gateway/spacegate-lib/src/plugin/auth/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,26 +340,26 @@ async fn test_auth_plugin_crypto() {
fn crypto_req(body: &str, serv_pub_key: &str, front_pub_key: &str, need_crypto_resp: bool) -> (String, String) {
let pub_key = TardisFuns::crypto.sm2.new_public_key_from_public_key(serv_pub_key).unwrap();

let sm4_key = TardisFuns::crypto.key.rand_16_bytes();
let sm4_key_hex = TardisFuns::crypto.hex.encode(sm4_key);
let sm4_iv = TardisFuns::crypto.key.rand_16_bytes();
let sm4_iv_hex = TardisFuns::crypto.hex.encode(sm4_iv);
let sm4_key = TardisFuns::crypto.key.rand_16_hex();
// let sm4_key_hex = TardisFuns::crypto.hex.encode(sm4_key);
let sm4_iv = TardisFuns::crypto.key.rand_16_hex();
// let sm4_iv_hex = TardisFuns::crypto.hex.encode(sm4_iv);

let key = TardisFuns::crypto.hex.decode(sm4_key_hex.clone()).unwrap();
let iv = TardisFuns::crypto.hex.decode(sm4_iv_hex.clone()).unwrap();
// let key = TardisFuns::crypto.hex.decode(sm4_key_hex.clone()).unwrap();
// let iv = TardisFuns::crypto.hex.decode(sm4_iv_hex.clone()).unwrap();

assert_eq!(key.as_slice(), sm4_key);
assert_eq!(iv.as_slice(), sm4_iv);
// assert_eq!(key.as_slice(), sm4_key);
// assert_eq!(iv.as_slice(), sm4_iv);

let data = TardisFuns::crypto.sm4.encrypt_cbc(body, sm4_key, sm4_iv).unwrap();
assert_eq!(TardisFuns::crypto.sm4.decrypt_cbc(&data, key.as_slice(), iv.as_slice()).unwrap(), body);
let data = TardisFuns::crypto.sm4.encrypt_cbc(body, &sm4_key, &sm4_iv).unwrap();
assert_eq!(TardisFuns::crypto.sm4.decrypt_cbc(&data, &sm4_key, &sm4_iv).unwrap(), body);

let sign_data = TardisFuns::crypto.digest.sm3(&data).unwrap();

let sm4_encrypt = if need_crypto_resp {
pub_key.encrypt(&format!("{sign_data} {sm4_key_hex} {sm4_iv_hex} {front_pub_key}",)).unwrap()
pub_key.encrypt(&format!("{sign_data} {sm4_key} {sm4_iv} {front_pub_key}",)).unwrap()
} else {
pub_key.encrypt(&format!("{sign_data} {sm4_key_hex} {sm4_iv_hex}",)).unwrap()
pub_key.encrypt(&format!("{sign_data} {sm4_key} {sm4_iv}",)).unwrap()
};
let base64_encrypt = TardisFuns::crypto.base64.encode(sm4_encrypt);
(data, base64_encrypt)
Expand Down
3 changes: 1 addition & 2 deletions gateway/spacegate-lib/tests/export_schemas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ macro_rules! export_plugins {
#[test]
fn export_schema() {
use spacegate_lib::plugin::{
anti_replay::AntiReplayPlugin, anti_xss::AntiXssPlugin, audit_log::AuditLogPlugin, auth::AuthPlugin, ip_time::SgIpTimePlugin,
rewrite_ns_b_ip::RewriteNsPlugin,
anti_replay::AntiReplayPlugin, anti_xss::AntiXssPlugin, audit_log::AuditLogPlugin, auth::AuthPlugin, ip_time::SgIpTimePlugin, rewrite_ns_b_ip::RewriteNsPlugin,
};
export_plugins!("schema":
AntiReplayPlugin
Expand Down
35 changes: 29 additions & 6 deletions middleware/flow/src/api/cc/flow_cc_inst_api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::HashMap;

use tardis::web::context_extractor::TardisContextExtractor;
use tardis::web::poem::Request;
use tardis::web::poem_openapi;
use tardis::web::poem_openapi::param::{Path, Query};
use tardis::web::poem_openapi::payload::Json;
Expand All @@ -21,7 +22,7 @@ pub struct FlowCcInstApi;
impl FlowCcInstApi {
/// Start Instance / 启动实例
#[oai(path = "/", method = "post")]
async fn start(&self, add_req: Json<FlowInstStartReq>, ctx: TardisContextExtractor) -> TardisApiResult<String> {
async fn start(&self, add_req: Json<FlowInstStartReq>, ctx: TardisContextExtractor, _request: &Request) -> TardisApiResult<String> {
let mut funs = flow_constants::get_tardis_inst();
funs.begin().await?;
let result = FlowInstServ::start(&add_req.0, None, &funs, &ctx.0).await?;
Expand All @@ -31,7 +32,7 @@ impl FlowCcInstApi {

/// Abort Instance / 中止实例
#[oai(path = "/:flow_inst_id", method = "put")]
async fn abort(&self, flow_inst_id: Path<String>, abort_req: Json<FlowInstAbortReq>, ctx: TardisContextExtractor) -> TardisApiResult<Void> {
async fn abort(&self, flow_inst_id: Path<String>, abort_req: Json<FlowInstAbortReq>, ctx: TardisContextExtractor, _request: &Request) -> TardisApiResult<Void> {
let mut funs = flow_constants::get_tardis_inst();
funs.begin().await?;
FlowInstServ::abort(&flow_inst_id.0, &abort_req.0, &funs, &ctx.0).await?;
Expand All @@ -41,7 +42,7 @@ impl FlowCcInstApi {

/// Get Instance By Instance Id / 获取实例信息
#[oai(path = "/:flow_inst_id", method = "get")]
async fn get(&self, flow_inst_id: Path<String>, ctx: TardisContextExtractor) -> TardisApiResult<FlowInstDetailResp> {
async fn get(&self, flow_inst_id: Path<String>, ctx: TardisContextExtractor, _request: &Request) -> TardisApiResult<FlowInstDetailResp> {
let funs = flow_constants::get_tardis_inst();
let result = FlowInstServ::get(&flow_inst_id.0, &funs, &ctx.0).await?;
TardisResp::ok(result)
Expand All @@ -58,6 +59,7 @@ impl FlowCcInstApi {
page_number: Query<u32>,
page_size: Query<u32>,
ctx: TardisContextExtractor,
_request: &Request,
) -> TardisApiResult<TardisPage<FlowInstSummaryResp>> {
let funs = flow_constants::get_tardis_inst();
let result = FlowInstServ::paginate(flow_model_id.0, tag.0, finish.0, with_sub.0, page_number.0, page_size.0, &funs, &ctx.0).await?;
Expand All @@ -71,6 +73,7 @@ impl FlowCcInstApi {
flow_inst_id: Path<String>,
next_req: Json<FlowInstFindNextTransitionsReq>,
ctx: TardisContextExtractor,
_request: &Request,
) -> TardisApiResult<Vec<FlowInstFindNextTransitionResp>> {
let funs = flow_constants::get_tardis_inst();
let result = FlowInstServ::find_next_transitions(&flow_inst_id.0, &next_req.0, &funs, &ctx.0).await?;
Expand All @@ -83,6 +86,7 @@ impl FlowCcInstApi {
&self,
find_req: Json<Vec<FlowInstFindStateAndTransitionsReq>>,
ctx: TardisContextExtractor,
_request: &Request,
) -> TardisApiResult<Vec<FlowInstFindStateAndTransitionsResp>> {
let funs = flow_constants::get_tardis_inst();
let result = FlowInstServ::find_state_and_next_transitions(&find_req.0, &funs, &ctx.0).await?;
Expand All @@ -91,7 +95,13 @@ impl FlowCcInstApi {

/// Transfer State By State Id / 流转
#[oai(path = "/:flow_inst_id/transition/transfer", method = "put")]
async fn transfer(&self, flow_inst_id: Path<String>, transfer_req: Json<FlowInstTransferReq>, ctx: TardisContextExtractor) -> TardisApiResult<FlowInstTransferResp> {
async fn transfer(
&self,
flow_inst_id: Path<String>,
transfer_req: Json<FlowInstTransferReq>,
ctx: TardisContextExtractor,
_request: &Request,
) -> TardisApiResult<FlowInstTransferResp> {
let mut funs = flow_constants::get_tardis_inst();
let mut transfer = transfer_req.0;
FlowInstServ::check_transfer_vars(&flow_inst_id.0, &mut transfer, &funs, &ctx.0).await?;
Expand All @@ -108,6 +118,7 @@ impl FlowCcInstApi {
flow_inst_ids: Path<String>,
transfer_req: Json<FlowInstTransferReq>,
ctx: TardisContextExtractor,
_request: &Request,
) -> TardisApiResult<Vec<FlowInstTransferResp>> {
let mut funs = flow_constants::get_tardis_inst();
let mut result = vec![];
Expand All @@ -129,7 +140,13 @@ impl FlowCcInstApi {

/// Modify Assigned / 同步执行人信息
#[oai(path = "/:flow_inst_id/transition/modify_assigned", method = "post")]
async fn modify_assigned(&self, flow_inst_id: Path<String>, modify_req: Json<FlowInstModifyAssignedReq>, ctx: TardisContextExtractor) -> TardisApiResult<Void> {
async fn modify_assigned(
&self,
flow_inst_id: Path<String>,
modify_req: Json<FlowInstModifyAssignedReq>,
ctx: TardisContextExtractor,
_request: &Request,
) -> TardisApiResult<Void> {
let mut funs = flow_constants::get_tardis_inst();
funs.begin().await?;
FlowInstServ::modify_assigned(&flow_inst_id.0, &modify_req.0.current_assigned, &funs, &ctx.0).await?;
Expand All @@ -139,7 +156,13 @@ impl FlowCcInstApi {

/// Modify list of variables / 同步当前变量列表
#[oai(path = "/:flow_inst_id/modify_current_vars", method = "patch")]
async fn modify_current_vars(&self, flow_inst_id: Path<String>, modify_req: Json<FlowInstModifyCurrentVarsReq>, ctx: TardisContextExtractor) -> TardisApiResult<Void> {
async fn modify_current_vars(
&self,
flow_inst_id: Path<String>,
modify_req: Json<FlowInstModifyCurrentVarsReq>,
ctx: TardisContextExtractor,
_request: &Request,
) -> TardisApiResult<Void> {
let mut funs = flow_constants::get_tardis_inst();
funs.begin().await?;
FlowInstServ::modify_current_vars(&flow_inst_id.0, &modify_req.0.vars, &funs, &ctx.0).await?;
Expand Down
Loading

0 comments on commit a788186

Please sign in to comment.