Files
crank/crates/crank-community-mcp/src/app/auth_resolution.rs
T
bsodfather f9f8c625d1
CI / UI Checks (pull_request) Successful in 15s
CI / Rust Checks (pull_request) Failing after 4m58s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
feat(epic4): исполнять durable Task через PG lease/fence и восстанавливать после сбоев (Story 4.3)
mcp-server запускает сохранённые фоновые задачи: захват по PostgreSQL lease с
fence-токеном, зашифрованный input и повторная проверка доступа до сетевого
вызова, checkpoint с AttemptID до dispatch и восстановление только по PG.
Устаревший worker не может зафиксировать результат.

Добавлены миграции v26–v28 (V25 не меняется), guard их отсутствия в старой
схеме, метрики/трассы попыток (attempt_trace) и остановка до отправки запроса:
стоп в окне после checkpoint и до permit завершает задачу как
failed(shutdown_before_dispatch) без сетевых вызовов, соседние queued-задачи
остаются доступными. Retry-попытки получают отдельные дочерние spans с durable
current_attempt_id. Shared admission/fairness из Story 4.1 сохранены.

Проверки: durable_tasks 13/13, stages 11/11 (retry 5), runtime lib 47,
bin shutdown 1, registry tasks 16, admission 11, migrations 58 (независимая QA
и исходный runtime-прогон), точный exact-head CI остаётся обязательным.
2026-10-29 22:26:52 +00:00

143 lines
5.1 KiB
Rust

//! Auth-profile resolution for a tool call: which profile applies to the operation/agent pair, and
//! the runtime auth projection derived from it.
//!
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309). `resolve_operation_auth` keeps its
//! crate-visible path through a targeted `pub(super) use` in `app.rs`; the other two stay private to
//! this module. No behaviour changed.
use crank_core::{AuthProfile, SecretId, SecretStatus};
use crank_registry::PostgresRegistry;
use crank_runtime::{ResolvedAuth, RuntimeError, SecretCrypto};
use crank_trace::{DbOperation, ErrorCategory, Stage, StageOutcome, observe_db_query};
use std::{collections::BTreeMap, sync::Arc};
use time::OffsetDateTime;
use tracing::{Instrument, warn};
use super::AppState;
pub(crate) async fn resolve_operation_auth(
state: &Arc<AppState>,
workspace_id: &crank_core::WorkspaceId,
execution_config: &crank_core::ExecutionConfig,
) -> Result<Option<ResolvedAuth>, RuntimeError> {
resolve_operation_auth_with(
&state.registry,
&state.secret_crypto,
workspace_id,
execution_config,
)
.await
}
/// Same resolution for callers that hold the authoritative registry/secret-crypto pair without the
/// HTTP application state (the durable Task worker).
pub(crate) async fn resolve_operation_auth_with(
registry: &PostgresRegistry,
secret_crypto: &SecretCrypto,
workspace_id: &crank_core::WorkspaceId,
execution_config: &crank_core::ExecutionConfig,
) -> Result<Option<ResolvedAuth>, RuntimeError> {
if execution_config.auth_profile_ref.is_none() {
return Ok(None);
}
let span = Stage::AuthResolve.span();
let result =
resolve_runtime_auth_for_task(registry, secret_crypto, workspace_id, execution_config)
.instrument(span.clone())
.await;
match &result {
Ok(_) => StageOutcome::Success.record(&span),
Err(_) => {
StageOutcome::Error.record(&span);
ErrorCategory::Configuration.record(&span);
}
}
result
}
async fn resolve_runtime_auth_for_task(
registry: &PostgresRegistry,
secret_crypto: &SecretCrypto,
workspace_id: &crank_core::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 = observe_db_query(
DbOperation::AuthProfileRead,
registry.get_auth_profile(workspace_id, auth_profile_id),
)
.await
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
.ok_or_else(|| RuntimeError::MissingAuthProfile {
auth_profile_id: auth_profile_id.as_str().to_owned(),
})?;
resolve_auth_profile(registry, secret_crypto, workspace_id, &auth_profile)
.await
.map(Some)
}
async fn resolve_auth_profile(
registry: &PostgresRegistry,
secret_crypto: &SecretCrypto,
workspace_id: &crank_core::WorkspaceId,
auth_profile: &AuthProfile,
) -> Result<ResolvedAuth, RuntimeError> {
let mut secrets = BTreeMap::new();
let used_at = OffsetDateTime::now_utc();
for secret_id in auth_profile.config.secret_ids() {
let secret = observe_db_query(
DbOperation::SecretRead,
registry.get_secret(workspace_id, secret_id),
)
.await
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
.ok_or_else(|| RuntimeError::MissingSecret {
secret_id: secret_id.as_str().to_owned(),
})?;
if secret.secret.status != SecretStatus::Active {
return Err(RuntimeError::InvalidAuthSecretValue {
secret_id: secret_id.as_str().to_owned(),
reason: "secret is not active".to_owned(),
});
}
let version = observe_db_query(
DbOperation::SecretRead,
registry.get_current_secret_version(workspace_id, secret_id),
)
.await
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
.ok_or_else(|| RuntimeError::MissingSecretVersion {
secret_id: secret_id.as_str().to_owned(),
version: secret.secret.current_version,
})?;
let plaintext = secret_crypto.decrypt_for_epoch(
&version.secret_version.key_version,
version.master_key_epoch,
&version.secret_version.ciphertext,
)?;
if observe_db_query(
DbOperation::SecretTouch,
registry.touch_secret(workspace_id, secret_id, &used_at),
)
.await
.is_err()
{
warn!(
target: "crank::audit",
action = "credential.secret.touch_failed",
credential_type = "secret",
credential_ref = %secret_id.as_str(),
outcome = "metadata_touch_failed",
"secret last-used metadata was not updated"
);
}
secrets.insert(SecretId::new(secret_id.as_str()), plaintext);
}
ResolvedAuth::from_profile(auth_profile, &secrets)
}