Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

16.7 KB
Raw Blame
use crate::{
    api::errors::FlagError, database::get_connection_with_metrics, team::team_models::Team,
};
use common_database::PostgresReader;
use tracing::warn;

/// SQL fragment for selecting all Team columns
const TEAM_COLUMNS: &str = "
    id,
    uuid,
    name,
    api_token,
    organization_id,
    project_id,
    cookieless_server_hash_mode,
    timezone,
    autocapture_opt_out,
    autocapture_exceptions_opt_in,
    autocapture_web_vitals_opt_in,
    capture_performance_opt_in,
    capture_console_log_opt_in,
    logs_settings,
    session_recording_opt_in,
    inject_web_apps,
    surveys_opt_in,
    product_tours_opt_in,
    heatmaps_opt_in,
    conversations_enabled,
    conversations_settings,
    capture_dead_clicks,
    flags_persistence_default,
    session_recording_sample_rate,
    session_recording_minimum_duration_milliseconds,
    autocapture_web_vitals_allowed_metrics,
    autocapture_exceptions_errors_to_ignore,
    session_recording_linked_flag,
    session_recording_network_payload_capture_config,
    session_recording_masking_config,
    session_replay_config,
    survey_config,
    extra_settings,
    session_recording_url_trigger_config,
    session_recording_url_blocklist_config,
    session_recording_event_trigger_config,
    session_recording_trigger_match_type_config,
    recording_domains,
    COALESCE(
        (SELECT minimal_flag_called_events FROM feature_flags_teamfeatureflagsconfig WHERE team_id = posthog_team.id),
        false
    ) AS minimal_flag_called_events,
    COALESCE(
        (SELECT property_matching_version FROM feature_flags_teamfeatureflagsconfig WHERE team_id = posthog_team.id),
        1
    )::smallint AS property_matching_version,
    COALESCE(
        (SELECT blocked_hosts FROM feature_flags_teamfeatureflagpolicyconfig WHERE team_id = posthog_team.id),
        '{}'
    )::text[] AS flags_blocked_hosts,
    COALESCE(
        (SELECT blocked_ips FROM feature_flags_teamfeatureflagpolicyconfig WHERE team_id = posthog_team.id),
        '{}'
    )::text[] AS flags_blocked_ips,
    COALESCE(
        (SELECT level FROM cohort_realtime_team_access WHERE team_id = posthog_team.id),
        'off'
    )::text AS realtime_cohort_level
";

impl Team {
    /// Parses the team's stored timezone string into a `chrono_tz::Tz`, falling back to
    /// UTC (with a warning) for an unrecognized value. Every flag-evaluation path that
    /// interprets naive datetime filter values in the team's local time goes through here,
    /// so the fallback policy and warning live in one place.
    pub fn parsed_timezone(&self) -> chrono_tz::Tz {
        self.timezone.parse().unwrap_or_else(|_| {
            warn!(team_id = self.id, timezone = %self.timezone, "unrecognized team timezone, falling back to UTC for datetime flag evaluation");
            chrono_tz::Tz::UTC
        })
    }

    pub async fn from_pg(client: PostgresReader, token: &str) -> Result<Team, FlagError> {
        let mut conn =
            get_connection_with_metrics(&client, "non_persons_reader", "fetch_team").await?;

        let query = format!("SELECT {TEAM_COLUMNS} FROM posthog_team WHERE api_token = $1");
        let row = sqlx::query_as::<_, Team>(&query)
            .bind(token)
            .fetch_one(&mut *conn)
            .await?;

        Ok(row)
    }

    pub async fn from_pg_by_id(client: PostgresReader, team_id: i32) -> Result<Team, FlagError> {
        let mut conn =
            get_connection_with_metrics(&client, "non_persons_reader", "fetch_team_by_id").await?;

        let query = format!("SELECT {TEAM_COLUMNS} FROM posthog_team WHERE id = $1");
        let row = sqlx::query_as::<_, Team>(&query)
            .bind(team_id)
            .fetch_one(&mut *conn)
            .await?;

        Ok(row)
    }

    pub async fn from_pg_by_secret_token(
        client: PostgresReader,
        token: &str,
    ) -> Result<Team, FlagError> {
        let mut conn =
            get_connection_with_metrics(&client, "non_persons_reader", "fetch_team_by_secret")
                .await?;

        let query = format!(
            "SELECT {TEAM_COLUMNS} FROM posthog_team WHERE secret_api_token = $1 OR secret_api_token_backup = $1"
        );
        let row = sqlx::query_as::<_, Team>(&query)
            .bind(token)
            .fetch_one(&mut *conn)
            .await?;

        Ok(row)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::team::request_blocklist::BlockReason;
    use crate::team::team_models::{PropertyMatchingVersion, RealtimeCohortLevel};
    use crate::utils::test_utils::{
        insert_new_team_in_redis, setup_redis_client, setup_team_hypercache_reader, TestContext,
    };

    #[tokio::test]
    async fn test_fetch_team_from_hypercache() {
        let client = setup_redis_client(None).await;

        let team = insert_new_team_in_redis(client.clone())
            .await
            .expect("Failed to insert team in redis");

        // Verify we can fetch team from HyperCache using typed deserialization
        let team_hypercache_reader = setup_team_hypercache_reader(client.clone()).await;
        let key = common_hypercache::KeyType::string(&team.api_token);
        let (data, _source) = team_hypercache_reader
            .get_typed_with_source::<Team>(&key)
            .await
            .unwrap();

        let team_from_cache = data.expect("Expected team data, got sentinel");
        assert_eq!(team_from_cache.api_token, team.api_token);
        assert_eq!(team_from_cache.id, team.id);
    }

    #[tokio::test]
    async fn test_fetch_team_from_pg() {
        let context = TestContext::new(None).await;
        let team = context
            .insert_new_team(None)
            .await
            .expect("Failed to insert team in pg");

        let target_token = team.api_token;

        let team_from_pg = Team::from_pg(context.non_persons_reader.clone(), target_token.as_str())
            .await
            .expect("Failed to fetch team from pg");

        assert_eq!(team_from_pg.api_token, target_token);
        assert_eq!(team_from_pg.id, team.id);
        assert_eq!(team_from_pg.name, team.name);
    }

    #[tokio::test]
    async fn test_fetch_team_from_pg_with_invalid_token() {
        // TODO: Figure out a way such that `run_database_migrations` is called only once, and already called
        // before running these tests.

        let context = TestContext::new(None).await;
        let target_token = "xxxx".to_string();

        match Team::from_pg(context.non_persons_reader.clone(), target_token.as_str()).await {
            Err(FlagError::RowNotFound) => (),
            _ => panic!("Expected RowNotFound"),
        };
    }

    #[tokio::test]
    async fn test_fetch_team_with_null_array_elements_from_pg() {
        let context = TestContext::new(None).await;

        // Insert a team with NULL elements in the array
        let team = context
            .insert_new_team(None)
            .await
            .expect("Failed to insert team in pg");

        // Manually update the team to have NULL elements in session_recording_event_trigger_config
        let mut conn = get_connection_with_metrics(
            &context.non_persons_reader,
            "non_persons_reader",
            "test_update_team",
        )
        .await
        .expect("Failed to get connection");

        // Update with an array containing NULL elements: {NULL, 'valid_event', NULL, 'another_event'}
        sqlx::query(
            "UPDATE posthog_team SET session_recording_event_trigger_config = $1 WHERE id = $2",
        )
        .bind(vec![
            None,
            Some("valid_event".to_string()),
            None,
            Some("another_event".to_string()),
        ])
        .bind(team.id)
        .execute(&mut *conn)
        .await
        .expect("Failed to update team with NULL array elements");

        // Now fetch the team and verify it deserializes correctly
        let team_from_pg = Team::from_pg(context.non_persons_reader.clone(), &team.api_token)
            .await
            .expect("Failed to fetch team with NULL array elements from pg");

        // Verify the field was deserialized correctly
        assert!(team_from_pg
            .session_recording_event_trigger_config
            .is_some());
        let config = team_from_pg.session_recording_event_trigger_config.unwrap();
        assert_eq!(config.len(), 4);
        assert_eq!(config[0], None);
        assert_eq!(config[1], Some("valid_event".to_string()));
        assert_eq!(config[2], None);
        assert_eq!(config[3], Some("another_event".to_string()));
    }

    #[tokio::test]
    async fn test_fetch_team_with_extra_settings_from_pg() {
        let context = TestContext::new(None).await;

        let team = context
            .insert_new_team(None)
            .await
            .expect("Failed to insert team in pg");

        // Update the team with extra_settings containing recorder_script
        let mut conn = get_connection_with_metrics(
            &context.non_persons_reader,
            "non_persons_reader",
            "test_extra_settings",
        )
        .await
        .expect("Failed to get connection");

        let extra_settings = serde_json::json!({
            "recorder_script": "posthog-recorder",
            "something_else": 123
        });

        sqlx::query("UPDATE posthog_team SET extra_settings = $1 WHERE id = $2")
            .bind(&extra_settings)
            .bind(team.id)
            .execute(&mut *conn)
            .await
            .expect("Failed to update team with extra_settings");

        // Fetch the team and verify extra_settings deserializes correctly
        let team_from_pg = Team::from_pg(context.non_persons_reader.clone(), &team.api_token)
            .await
            .expect("Failed to fetch team with extra_settings from pg");

        assert!(team_from_pg.extra_settings.is_some());
        let config = team_from_pg.extra_settings.unwrap();
        assert_eq!(
            config.get("recorder_script").and_then(|v| v.as_str()),
            Some("posthog-recorder")
        );
    }

    #[tokio::test]
    async fn test_fetch_team_with_empty_recorder_script_from_pg() {
        let context = TestContext::new(None).await;

        let team = context
            .insert_new_team(None)
            .await
            .expect("Failed to insert team in pg");

        // Update the team with extra_settings containing empty recorder_script
        let mut conn = get_connection_with_metrics(
            &context.non_persons_reader,
            "non_persons_reader",
            "test_empty_recorder_script",
        )
        .await
        .expect("Failed to get connection");

        let extra_settings = serde_json::json!({
            "recorder_script": ""
        });

        sqlx::query("UPDATE posthog_team SET extra_settings = $1 WHERE id = $2")
            .bind(&extra_settings)
            .bind(team.id)
            .execute(&mut *conn)
            .await
            .expect("Failed to update team with empty recorder_script");

        // Fetch the team and verify empty string is handled correctly
        let team_from_pg = Team::from_pg(context.non_persons_reader.clone(), &team.api_token)
            .await
            .expect("Failed to fetch team with empty recorder_script from pg");

        assert!(team_from_pg.extra_settings.is_some());
        let config = team_from_pg.extra_settings.unwrap();
        let recorder_script = config.get("recorder_script").and_then(|v| v.as_str());
        assert_eq!(recorder_script, Some(""));
    }

    #[tokio::test]
    async fn test_fetch_team_defaults_feature_flags_config_without_config_row() {
        let context = TestContext::new(None).await;
        let team = context
            .insert_new_team(None)
            .await
            .expect("Failed to insert team in pg");

        let team_from_pg = Team::from_pg(context.non_persons_reader.clone(), &team.api_token)
            .await
            .expect("Failed to fetch team from pg");

        assert!(!team_from_pg.minimal_flag_called_events);
        assert_eq!(
            team_from_pg.property_matching_version,
            PropertyMatchingVersion::LEGACY
        );
    }

    #[tokio::test]
    async fn test_fetch_team_reflects_feature_flags_config() {
        let context = TestContext::new(None).await;
        let team = context
            .insert_new_team(None)
            .await
            .expect("Failed to insert team in pg");

        let mut conn = get_connection_with_metrics(
            &context.non_persons_reader,
            "non_persons_reader",
            "test_insert_team_feature_flags_config",
        )
        .await
        .expect("Failed to get connection");

        sqlx::query(
            "INSERT INTO feature_flags_teamfeatureflagsconfig \
             (team_id, minimal_flag_called_events, property_matching_version) \
             VALUES ($1, true, 2)",
        )
        .bind(team.id)
        .execute(&mut *conn)
        .await
        .expect("Failed to insert TeamFeatureFlagsConfig row");

        let team_from_pg = Team::from_pg(context.non_persons_reader.clone(), &team.api_token)
            .await
            .expect("Failed to fetch team from pg");

        assert!(team_from_pg.minimal_flag_called_events);
        assert_eq!(
            team_from_pg.property_matching_version,
            PropertyMatchingVersion::EXPLICIT
        );
    }

    #[tokio::test]
    async fn test_fetch_team_reflects_feature_flag_policy_blocklist() {
        let context = TestContext::new(None).await;
        let team = context
            .insert_new_team(None)
            .await
            .expect("Failed to insert team in pg");

        let mut conn = get_connection_with_metrics(
            &context.non_persons_reader,
            "non_persons_reader",
            "test_insert_team_feature_flag_policy_config",
        )
        .await
        .expect("Failed to get connection");

        sqlx::query(
            "INSERT INTO feature_flags_teamfeatureflagpolicyconfig \
             (team_id, require_tags, blocked_hosts, blocked_ips) \
             VALUES ($1, false, ARRAY['example.com'], ARRAY['203.0.113.0/24'])",
        )
        .bind(team.id)
        .execute(&mut *conn)
        .await
        .expect("Failed to insert TeamFeatureFlagPolicyConfig row");

        let by_token = Team::from_pg(context.non_persons_reader.clone(), &team.api_token)
            .await
            .expect("Failed to fetch team by token from pg");
        let by_id = Team::from_pg_by_id(context.non_persons_reader.clone(), team.id)
            .await
            .expect("Failed to fetch team by id from pg");

        for team_from_pg in [by_token, by_id] {
            assert_eq!(
                team_from_pg
                    .request_block_reason(Some("app.example.com"), ["192.0.2.1".parse().unwrap()]),
                Some(BlockReason::Host)
            );
            assert_eq!(
                team_from_pg.request_block_reason(None, ["203.0.113.9".parse().unwrap()]),
                Some(BlockReason::Ip)
            );
        }
    }

    #[tokio::test]
    async fn test_fetch_team_reads_the_realtime_cohort_access_level() {
        let context = TestContext::new(None).await;
        let team = context
            .insert_new_team(None)
            .await
            .expect("Failed to insert team in pg");
        let without_row = Team::from_pg(context.non_persons_reader.clone(), &team.api_token)
            .await
            .expect("Failed to fetch team from pg");

        let mut conn = get_connection_with_metrics(
            &context.non_persons_reader,
            "non_persons_reader",
            "test_insert_realtime_cohort_team_access",
        )
        .await
        .expect("Failed to get connection");
        sqlx::query(
            "INSERT INTO cohort_realtime_team_access \
             (team_id, level, purpose, save_triggers_backfill, processing_since, changed_at) \
             VALUES ($1, 'serving', 'pilot', false, now(), now())",
        )
        .bind(team.id)
        .execute(&mut *conn)
        .await
        .expect("Failed to insert the team access row");
        let by_token = Team::from_pg(context.non_persons_reader.clone(), &team.api_token).await;
        let by_id = Team::from_pg_by_id(context.non_persons_reader.clone(), team.id).await;
        // Delete before asserting, so a failed assertion leaves no row behind.
        sqlx::query("DELETE FROM cohort_realtime_team_access WHERE team_id = $1")
            .bind(team.id)
            .execute(&mut *conn)
            .await
            .expect("Failed to delete the team access row");

        assert_eq!(without_row.realtime_cohort_level, RealtimeCohortLevel::Off);
        for team_from_pg in [by_token, by_id] {
            assert_eq!(
                team_from_pg
                    .expect("Failed to fetch team from pg")
                    .realtime_cohort_level,
                RealtimeCohortLevel::Serving
            );
        }
    }
}