feat: resolve upstream auth at runtime

This commit is contained in:
a.tolmachev
2026-04-07 01:00:24 +03:00
parent 191e749b14
commit da94d308de
17 changed files with 702 additions and 78 deletions
+1 -1
View File
@@ -227,6 +227,7 @@ mod tests {
};
use crank_mapping::{MappingRule, MappingSet};
use crank_registry::PostgresRegistry;
use crank_runtime::SecretCrypto;
use crank_schema::{Schema, SchemaKind};
use serde_json::{Value, json};
use serial_test::serial;
@@ -236,7 +237,6 @@ mod tests {
use crate::{
app::build_app,
auth::{AuthSettings, BootstrapAdminConfig, hash_password},
secret_crypto::SecretCrypto,
service::{AdminService, OperationPayload},
state::AppState,
};
+6
View File
@@ -251,5 +251,11 @@ fn runtime_test_failure_code(error: &RuntimeError) -> &'static str {
RuntimeError::MissingStreamingConfig { .. } => "runtime_streaming_config_error",
RuntimeError::UnsupportedExecutionMode { .. } => "runtime_streaming_mode_error",
RuntimeError::InvalidStreamingPayload { .. } => "runtime_streaming_payload_error",
RuntimeError::MissingAuthProfile { .. } => "runtime_auth_profile_error",
RuntimeError::MissingSecret { .. } | RuntimeError::MissingSecretVersion { .. } => {
"runtime_secret_error"
}
RuntimeError::InvalidAuthSecretValue { .. } => "runtime_secret_value_error",
RuntimeError::SecretCrypto { .. } => "runtime_secret_crypto_error",
}
}
+1 -2
View File
@@ -2,7 +2,6 @@ mod app;
mod auth;
mod error;
mod routes;
mod secret_crypto;
mod service;
mod state;
mod storage;
@@ -16,10 +15,10 @@ use tracing::info;
use crate::{
app::build_app,
auth::{AuthSettings, BootstrapAdminConfig},
secret_crypto::SecretCrypto,
service::AdminService,
state::AppState,
};
use crank_runtime::SecretCrypto;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
-112
View File
@@ -1,112 +0,0 @@
use aes_gcm::{
Aes256Gcm, KeyInit, Nonce,
aead::{Aead, OsRng, rand_core::RngCore},
};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::error::ApiError;
#[derive(Clone)]
pub struct SecretCrypto {
cipher: Aes256Gcm,
key_version: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct CipherEnvelope {
nonce_b64: String,
ciphertext_b64: String,
}
impl SecretCrypto {
pub fn new(master_key: &str) -> Result<Self, ApiError> {
let trimmed = master_key.trim();
if trimmed.is_empty() {
return Err(ApiError::internal("CRANK_MASTER_KEY must not be empty"));
}
let digest = Sha256::digest(trimmed.as_bytes());
let cipher = Aes256Gcm::new_from_slice(digest.as_slice()).map_err(|error| {
ApiError::internal(format!("failed to initialize secret crypto: {error}"))
})?;
Ok(Self {
cipher,
key_version: "v1".to_owned(),
})
}
pub fn key_version(&self) -> &str {
&self.key_version
}
pub fn encrypt(&self, value: &Value) -> Result<String, ApiError> {
let plaintext = serde_json::to_vec(value).map_err(|error| {
ApiError::internal(format!("failed to serialize secret value: {error}"))
})?;
let mut nonce_bytes = [0_u8; 12];
OsRng.fill_bytes(&mut nonce_bytes);
let nonce = Nonce::from_slice(&nonce_bytes);
let ciphertext = self
.cipher
.encrypt(nonce, plaintext.as_ref())
.map_err(|error| {
ApiError::internal(format!("failed to encrypt secret value: {error}"))
})?;
let envelope = CipherEnvelope {
nonce_b64: STANDARD.encode(nonce_bytes),
ciphertext_b64: STANDARD.encode(ciphertext),
};
serde_json::to_string(&envelope).map_err(|error| {
ApiError::internal(format!("failed to encode secret ciphertext: {error}"))
})
}
#[cfg(test)]
pub fn decrypt(&self, ciphertext: &str) -> Result<Value, ApiError> {
let envelope: CipherEnvelope = serde_json::from_str(ciphertext).map_err(|error| {
ApiError::internal(format!("failed to decode secret envelope: {error}"))
})?;
let nonce_bytes = STANDARD.decode(envelope.nonce_b64).map_err(|error| {
ApiError::internal(format!("failed to decode secret nonce: {error}"))
})?;
let ciphertext_bytes = STANDARD.decode(envelope.ciphertext_b64).map_err(|error| {
ApiError::internal(format!("failed to decode secret payload: {error}"))
})?;
let plaintext = self
.cipher
.decrypt(Nonce::from_slice(&nonce_bytes), ciphertext_bytes.as_ref())
.map_err(|error| {
ApiError::internal(format!("failed to decrypt secret value: {error}"))
})?;
serde_json::from_slice(&plaintext).map_err(|error| {
ApiError::internal(format!("failed to deserialize secret value: {error}"))
})
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::SecretCrypto;
#[test]
fn roundtrips_secret_payload() {
let crypto = SecretCrypto::new("test-master-key").unwrap();
let plaintext = json!({
"token": "top-secret",
"username": "demo"
});
let ciphertext = crypto.encrypt(&plaintext).unwrap();
let decrypted = crypto.decrypt(&ciphertext).unwrap();
assert_eq!(decrypted, plaintext);
}
}
+100 -5
View File
@@ -31,7 +31,9 @@ use crank_registry::{
UpdateWorkspaceRequest, UsageAgentBreakdown, UsageBucket, UsageOperationBreakdown, UsageQuery,
UsageSummary, UsageTimelinePoint, WorkspaceMembershipRecord, WorkspaceRecord,
};
use crank_runtime::{PreparedRequest, RuntimeError, RuntimeExecutor, RuntimeOperation};
use crank_runtime::{
PreparedRequest, ResolvedAuth, RuntimeError, RuntimeExecutor, RuntimeOperation, SecretCrypto,
};
use crank_schema::Schema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -46,7 +48,6 @@ use crate::{
hash_session_secret, verify_password,
},
error::ApiError,
secret_crypto::SecretCrypto,
storage::LocalArtifactStorage,
};
@@ -1918,8 +1919,18 @@ impl AdminService {
}
};
let resolved_auth = self
.resolve_operation_auth(workspace_id, &runtime.execution_config)
.await;
let started_at = std::time::Instant::now();
match self.runtime.execute(&runtime, &payload.input).await {
match match resolved_auth {
Ok(resolved_auth) => {
self.runtime
.execute_with_auth(&runtime, &payload.input, resolved_auth.as_ref())
.await
}
Err(error) => Err(error),
} {
Ok(output) => {
let duration_ms =
u64::try_from(started_at.elapsed().as_millis()).unwrap_or(u64::MAX);
@@ -1973,6 +1984,78 @@ impl AdminService {
}
}
async fn resolve_operation_auth(
&self,
workspace_id: &WorkspaceId,
execution_config: &crank_core::ExecutionConfig,
) -> Result<Option<ResolvedAuth>, RuntimeError> {
let Some(auth_profile_id) = execution_config.auth_profile_ref.as_ref() else {
return Ok(None);
};
let auth_profile = self
.registry
.get_auth_profile(workspace_id, auth_profile_id)
.await
.map_err(|error| RuntimeError::SecretCrypto {
details: error.to_string(),
})?
.ok_or_else(|| RuntimeError::MissingAuthProfile {
auth_profile_id: auth_profile_id.as_str().to_owned(),
})?;
self.resolve_auth_profile(workspace_id, &auth_profile)
.await
.map(Some)
}
async fn resolve_auth_profile(
&self,
workspace_id: &WorkspaceId,
auth_profile: &AuthProfile,
) -> Result<ResolvedAuth, RuntimeError> {
let mut secrets = BTreeMap::new();
let used_at = now_string().map_err(|error| RuntimeError::SecretCrypto {
details: error.to_string(),
})?;
for secret_id in auth_profile.config.secret_ids() {
let secret = self
.registry
.get_secret(workspace_id, secret_id)
.await
.map_err(|error| RuntimeError::SecretCrypto {
details: error.to_string(),
})?
.ok_or_else(|| RuntimeError::MissingSecret {
secret_id: secret_id.as_str().to_owned(),
})?;
let version = self
.registry
.get_current_secret_version(workspace_id, secret_id)
.await
.map_err(|error| RuntimeError::SecretCrypto {
details: error.to_string(),
})?
.ok_or_else(|| RuntimeError::MissingSecretVersion {
secret_id: secret_id.as_str().to_owned(),
version: secret.secret.current_version,
})?;
let plaintext = self
.secret_crypto
.decrypt(&version.secret_version.ciphertext)?;
self.registry
.touch_secret(workspace_id, secret_id, &used_at)
.await
.map_err(|error| RuntimeError::SecretCrypto {
details: error.to_string(),
})?;
secrets.insert(secret_id.clone(), plaintext);
}
ResolvedAuth::from_profile(auth_profile, &secrets)
}
#[instrument(skip(self))]
pub async fn list_auth_profiles(
&self,
@@ -2032,7 +2115,10 @@ impl AdminService {
updated_at: now,
last_used_at: None,
};
let ciphertext = self.secret_crypto.encrypt(&payload.value)?;
let ciphertext = self
.secret_crypto
.encrypt(&payload.value)
.map_err(|error| ApiError::internal(error.to_string()))?;
self.registry
.create_secret(CreateSecretRequest {
@@ -2061,7 +2147,10 @@ impl AdminService {
}
let now = now_string()?;
let ciphertext = self.secret_crypto.encrypt(&payload.value)?;
let ciphertext = self
.secret_crypto
.encrypt(&payload.value)
.map_err(|error| ApiError::internal(error.to_string()))?;
self.registry
.rotate_secret(RotateSecretRequest {
workspace_id,
@@ -4200,6 +4289,12 @@ fn runtime_error_code(error: &RuntimeError) -> &'static str {
RuntimeError::MissingStreamingConfig { .. } => "streaming_config_error",
RuntimeError::UnsupportedExecutionMode { .. } => "streaming_mode_error",
RuntimeError::InvalidStreamingPayload { .. } => "streaming_payload_error",
RuntimeError::MissingAuthProfile { .. } => "auth_profile_not_found",
RuntimeError::MissingSecret { .. } | RuntimeError::MissingSecretVersion { .. } => {
"secret_not_found"
}
RuntimeError::InvalidAuthSecretValue { .. } => "secret_value_error",
RuntimeError::SecretCrypto { .. } => "secret_crypto_error",
}
}