Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/oauth/google.rs

Raw
//! Google Code Assist project admission (SMH-SPEC-PLUG0001).
use super::{AuthorizationFault, LoginPolicy};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use smith::tool::CancelHandle;
use std::time::{Duration, Instant};

const OPERATION_NAME_BYTES_MAX: usize = 512;
const OPERATION_OBSERVATIONS_MAX: usize = 32;

/// Public installed-app protocol identity, not a user credential.
pub(super) const CLIENT_SECRET: &str = "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";

/// Validated noncredential project identifier; cold profile-owned metadata.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct CodeAssistProject(String);

impl CodeAssistProject {
    pub(super) fn new(project: &str) -> Result<Self, &'static str> {
        if !(6..=63).contains(&project.len())
            || !project.as_bytes()[0].is_ascii_lowercase()
            || !project.as_bytes()[project.len() - 1].is_ascii_alphanumeric()
            || !project
                .bytes()
                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
        {
            return Err("invalid Google Code Assist project ID");
        }
        Ok(Self(project.into()))
    }
    /// Bounded project ID, safe to pass as immutable request context.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}
impl TryFrom<String> for CodeAssistProject {
    type Error = &'static str;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(&value)
    }
}
impl From<CodeAssistProject> for String {
    fn from(value: CodeAssistProject) -> Self {
        value.0
    }
}

fn project(
    value: Option<&Value>,
    configured: Option<&CodeAssistProject>,
) -> Result<CodeAssistProject, AuthorizationFault> {
    match value {
        Some(value) => CodeAssistProject::new(
            value
                .as_str()
                .ok_or(AuthorizationFault::Rejected("invalid Code Assist project"))?,
        )
        .map_err(AuthorizationFault::Rejected),
        None => configured.cloned().ok_or(AuthorizationFault::Rejected(
            "Code Assist requires --project or eligible managed project",
        )),
    }
}

const OPERATION_POLL_INTERVAL: Duration = Duration::from_secs(5);
const OPERATION_WAIT_CHECK_INTERVAL: Duration = Duration::from_millis(50);

trait OperationWait {
    fn wait(&self, deadline: Instant, cancel: &CancelHandle) -> Result<(), AuthorizationFault>;
}

struct DeadlineOperationWait;

impl OperationWait for DeadlineOperationWait {
    fn wait(&self, deadline: Instant, cancel: &CancelHandle) -> Result<(), AuthorizationFault> {
        let wait_deadline = Instant::now()
            .checked_add(OPERATION_POLL_INTERVAL)
            .unwrap_or(deadline)
            .min(deadline);
        loop {
            if cancel.is_cancelled() {
                return Err(AuthorizationFault::Cancelled);
            }
            let remaining = wait_deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return if Instant::now() >= deadline {
                    Err(AuthorizationFault::Deadline)
                } else {
                    Ok(())
                };
            }
            std::thread::sleep(remaining.min(OPERATION_WAIT_CHECK_INTERVAL));
        }
    }
}

fn observe_operation<W, F>(
    mut operation: Value,
    deadline: Instant,
    cancel: &CancelHandle,
    waiter: &W,
    mut observe: F,
) -> Result<Value, AuthorizationFault>
where
    W: OperationWait,
    F: FnMut() -> Result<Value, AuthorizationFault>,
{
    for _ in 0..OPERATION_OBSERVATIONS_MAX {
        if operation["done"] == true {
            return Ok(operation);
        }
        waiter.wait(deadline, cancel)?;
        if cancel.is_cancelled() {
            return Err(AuthorizationFault::Cancelled);
        }
        if Instant::now() >= deadline {
            return Err(AuthorizationFault::Deadline);
        }
        operation = observe()?;
    }
    Ok(operation)
}
fn operation_path(name: &str) -> Result<String, AuthorizationFault> {
    if name.len() > OPERATION_NAME_BYTES_MAX {
        return Err(AuthorizationFault::Rejected(
            "Code Assist operation path bound exceeded",
        ));
    }
    let segments: Vec<_> = name.split('/').collect();
    let valid = matches!(
        segments.as_slice(),
        ["operations", _] | ["projects", _, "locations", _, "operations", _]
    );
    if !valid
        || segments.iter().any(|segment| {
            segment.is_empty()
                || !segment
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
        })
    {
        return Err(AuthorizationFault::Rejected(
            "unauthorized Code Assist operation path",
        ));
    }
    Ok(format!("/v1internal/{name}"))
}

pub(super) fn setup(
    policy: &LoginPolicy,
    access: &str,
    configured: Option<&CodeAssistProject>,
    deadline: Instant,
    cancel: &CancelHandle,
) -> Result<CodeAssistProject, AuthorizationFault> {
    let origin = policy
        .resource
        .strip_suffix("/v1internal")
        .ok_or(AuthorizationFault::Authority)?;
    if origin != "https://cloudcode-pa.googleapis.com"
        && !(origin == policy.issuer && origin.starts_with("http://127.0.0.1:"))
    {
        return Err(AuthorizationFault::Authority);
    }
    let metadata = json!({"ideType":"IDE_UNSPECIFIED","platform":"PLATFORM_UNSPECIFIED","pluginType":"GEMINI"});
    let mut load = json!({"metadata":metadata});
    if let Some(configured) = configured {
        load["cloudaicompanionProject"] = json!(configured.as_str());
        load["metadata"]["duetProject"] = json!(configured.as_str());
    }
    let loaded = crate::http::CredentialHttp::control(
        &format!("{origin}/v1internal:loadCodeAssist"),
        Some(&load),
        access,
        deadline,
        cancel,
    )?;
    let onboard = match setup_decision(&loaded, configured, &metadata)? {
        SetupDecision::Ready(project) => return Ok(project),
        SetupDecision::Onboard(request) => request,
    };
    // One onboarding POST only: an uncertain response never replays this effect.
    let operation = crate::http::CredentialHttp::control(
        &format!("{origin}/v1internal:onboardUser"),
        Some(&onboard),
        access,
        deadline,
        cancel,
    )?;
    let path = if operation["done"] == true {
        None
    } else {
        Some(operation_path(operation["name"].as_str().ok_or(
            AuthorizationFault::Rejected("missing Code Assist operation"),
        )?)?)
    };
    // Bounded observations, no automatic re-onboarding or untrusted URL following.
    let operation = observe_operation(operation, deadline, cancel, &DeadlineOperationWait, || {
        let path = path.as_deref().ok_or(AuthorizationFault::Authority)?;
        crate::http::CredentialHttp::control(
            &format!("{origin}{path}"),
            None,
            access,
            deadline,
            cancel,
        )
        .map_err(AuthorizationFault::from)
    })?;
    if operation["done"] != true {
        return Err(AuthorizationFault::Rejected(
            "Code Assist operation observation bound exceeded",
        ));
    }
    if operation.get("error").is_some() {
        return Err(AuthorizationFault::Rejected(
            "Code Assist onboarding rejected",
        ));
    }
    project(
        operation.pointer("/response/cloudaicompanionProject/id"),
        configured,
    )
}

enum SetupDecision {
    Ready(CodeAssistProject),
    Onboard(Value),
}

fn setup_decision(
    loaded: &Value,
    configured: Option<&CodeAssistProject>,
    metadata: &Value,
) -> Result<SetupDecision, AuthorizationFault> {
    if loaded.get("currentTier").is_some_and(Value::is_object) {
        return project(loaded.get("cloudaicompanionProject"), configured)
            .map(SetupDecision::Ready);
    }
    if loaded
        .get("ineligibleTiers")
        .and_then(Value::as_array)
        .is_some_and(|tiers| {
            tiers
                .iter()
                .any(|tier| tier["reasonCode"] == "VALIDATION_REQUIRED")
        })
    {
        return Err(AuthorizationFault::Rejected(
            "Code Assist setup requires unsupported validation",
        ));
    }
    let tiers = loaded.get("allowedTiers").and_then(Value::as_array);
    if tiers.is_some_and(|tiers| tiers.len() > 16) {
        return Err(AuthorizationFault::Rejected(
            "Code Assist tier bound exceeded",
        ));
    }
    let tier = tiers
        .and_then(|tiers| tiers.iter().find(|tier| tier["isDefault"] == true))
        .and_then(|tier| tier["id"].as_str())
        .unwrap_or("legacy-tier");
    if !matches!(tier, "free-tier" | "standard-tier" | "legacy-tier") {
        return Err(AuthorizationFault::Rejected("unsupported Code Assist tier"));
    }
    let mut onboard = json!({"tierId":tier,"metadata":metadata});
    if tier != "free-tier" {
        let configured = configured.ok_or(AuthorizationFault::Rejected(
            "nonfree Code Assist setup requires --project",
        ))?;
        onboard["cloudaicompanionProject"] = json!(configured.as_str());
        onboard["metadata"]["duetProject"] = json!(configured.as_str());
    }
    Ok(SetupDecision::Onboard(onboard))
}

pub(super) fn retain_refresh(
    response: &mut Value,
    previous: &str,
) -> Result<(), AuthorizationFault> {
    let response = response
        .as_object_mut()
        .ok_or(AuthorizationFault::Rejected("invalid OAuth token response"))?;
    if !response.contains_key("refresh_token") {
        response.insert("refresh_token".into(), Value::String(previous.into()));
    }
    Ok(())
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;

    struct ImmediateWait {
        calls: Cell<usize>,
        outcome: Result<(), AuthorizationFault>,
    }

    impl OperationWait for ImmediateWait {
        fn wait(&self, _: Instant, _: &CancelHandle) -> Result<(), AuthorizationFault> {
            self.calls.set(self.calls.get() + 1);
            self.outcome
        }
    }

    #[test]
    fn operation_waits_before_get_and_blocks_cancel_or_deadline_dispatch() {
        let waiter = ImmediateWait {
            calls: Cell::new(0),
            outcome: Ok(()),
        };
        let dispatched = Cell::new(0);
        let operation = observe_operation(
            json!({"done":false}),
            Instant::now() + Duration::from_secs(1),
            &CancelHandle::new(),
            &waiter,
            || {
                dispatched.set(dispatched.get() + 1);
                Ok(json!({"done":true}))
            },
        )
        .unwrap();
        assert_eq!(operation["done"], true);
        assert_eq!(waiter.calls.get(), 1);
        assert_eq!(dispatched.get(), 1);
        for (deadline, outcome, expected) in [
            (
                Instant::now() + Duration::from_secs(1),
                Err(AuthorizationFault::Cancelled),
                AuthorizationFault::Cancelled,
            ),
            (Instant::now(), Ok(()), AuthorizationFault::Deadline),
        ] {
            let waiter = ImmediateWait {
                calls: Cell::new(0),
                outcome,
            };
            let dispatched = Cell::new(0);
            let result = observe_operation(
                json!({"done":false}),
                deadline,
                &CancelHandle::new(),
                &waiter,
                || {
                    dispatched.set(dispatched.get() + 1);
                    Ok(json!({"done":true}))
                },
            );
            assert_eq!(result, Err(expected));
            assert_eq!(dispatched.get(), 0);
        }
    }
    #[test]
    fn setup_admits_returned_project_prefers_it_over_config_and_requires_project_for_nonfree() {
        let configured = CodeAssistProject::new("configured-project").unwrap();
        for (loaded, expected) in [
            (
                json!({"currentTier":{"id":"standard-tier"},"cloudaicompanionProject":"returned-project"}),
                "returned-project",
            ),
            (
                json!({"currentTier":{"id":"standard-tier"}}),
                "configured-project",
            ),
        ] {
            let SetupDecision::Ready(project) =
                setup_decision(&loaded, Some(&configured), &json!({})).unwrap()
            else {
                panic!("existing tier should not onboard")
            };
            assert_eq!(project.as_str(), expected);
        }
        for loaded in [
            json!({"currentTier":{"id":"standard-tier"}}),
            json!({"allowedTiers":[{"id":"standard-tier","isDefault":true}]}),
            json!({"ineligibleTiers":[{"reasonCode":"VALIDATION_REQUIRED","validationUrl":"https://untrusted"}]}),
            json!({"allowedTiers":[{"id":"unknown-tier","isDefault":true}]}),
            json!({"currentTier":{},"cloudaicompanionProject":"not/a/project"}),
        ] {
            assert!(
                setup_decision(&loaded, None, &json!({})).is_err(),
                "{loaded}"
            );
        }
        let SetupDecision::Onboard(request) = setup_decision(
            &json!({"allowedTiers":[{"id":"free-tier","isDefault":true}]}),
            Some(&configured),
            &json!({"pluginType":"GEMINI"}),
        )
        .unwrap() else {
            panic!("free tier should onboard")
        };
        assert_eq!(
            request,
            json!({"tierId":"free-tier","metadata":{"pluginType":"GEMINI"}})
        );
        let SetupDecision::Onboard(request) = setup_decision(
            &json!({}),
            Some(&configured),
            &json!({"pluginType":"GEMINI"}),
        )
        .unwrap() else {
            panic!("legacy tier should onboard")
        };
        assert_eq!(
            request,
            json!({"tierId":"legacy-tier","cloudaicompanionProject":"configured-project","metadata":{"pluginType":"GEMINI","duetProject":"configured-project"}})
        );
    }

    #[test]
    fn operation_authority_rejects_urls_traversal_and_other_methods() {
        for name in [
            "https://evil/operations/one",
            "../operations/one",
            "operations/%2e%2e",
            "operations/a?alt=json",
            "v1internal:loadCodeAssist",
            "operations/",
            "projects/p/operations/o",
        ] {
            assert!(operation_path(name).is_err(), "{name}");
        }
        assert_eq!(
            operation_path("operations/one").unwrap(),
            "/v1internal/operations/one"
        );
        assert!(operation_path("projects/project/locations/global/operations/one").is_ok());
    }
    #[test]
    fn setup_allows_configured_standard_tier_despite_unrelated_ineligibility() {
        let configured = CodeAssistProject::new("configured-project").unwrap();
        let SetupDecision::Onboard(request) = setup_decision(
            &json!({
                "allowedTiers":[{"id":"standard-tier","isDefault":true}],
                "ineligibleTiers":[{"id":"free-tier","reasonCode":"INELIGIBLE"}]
            }),
            Some(&configured),
            &json!({"pluginType":"GEMINI"}),
        )
        .unwrap() else {
            panic!("configured standard tier should onboard")
        };
        assert_eq!(request["tierId"], "standard-tier");
    }

    #[test]
    fn retain_refresh_rejects_nonobject_renewal_responses_without_panicking() {
        for mut response in [
            json!([]),
            json!(true),
            json!(7),
            json!("token"),
            json!(null),
        ] {
            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                retain_refresh(&mut response, "previous-refresh")
            }));
            assert!(
                matches!(
                    outcome,
                    Ok(Err(AuthorizationFault::Rejected(
                        "invalid OAuth token response"
                    )))
                ),
                "{response}"
            );
        }
    }
    #[test]
    fn project_metadata_validates_deserialization_and_size() {
        assert_eq!(size_of::<CodeAssistProject>(), size_of::<String>());
        for value in [
            "",
            "123456",
            "UPPER-project",
            "has/slash",
            "bad-project-",
            "short",
        ] {
            assert!(CodeAssistProject::new(value).is_err());
            assert!(serde_json::from_value::<CodeAssistProject>(json!(value)).is_err());
        }
        assert_eq!(
            CodeAssistProject::new("managed-project").unwrap().as_str(),
            "managed-project"
        );
    }
}