Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

42.8 KB
Raw Blame
#!/bin/bash
# shellcheck disable=SC2317  # cleanup() is invoked via trap, not direct call

# Featured Streams (mini-directory) Test
#
# This test verifies the Owncast-to-Owncast "featured streams" federation
# flow end to end. It is the only test in this directory that runs TWO
# Owncast instances, because the federated-servers directory is an
# Owncast-to-Owncast feature: one instance follows another, the follow is
# accepted, and the followed server then shows up in the follower's
# directory listing.
#
# Flow:
# 1. Build Owncast once, start two instances (owncast.local, owncast2.local)
#    behind the shared HTTPS proxy, both with federation enabled and public.
# 2. Instance 1 adds Instance 2 via POST /api/admin/federation/servers.
# 3. Verify Instance 2 immediately appears in Instance 1's directory listing
#    as a pending follow (regression guard: the record must be persisted).
# 4. Verify a featured-streams follow is NOT auto-accepted even on a public
#    server. Stop the requesting instance before approval so the Accept fails,
#    verify the durable delivery is scheduled for retry, restart the instance,
#    and verify the retry completes the handshake.
# 5. Verify the accepted record is actually populated with the remote server's
#    name, display name and logo (regression guard: a green "accepted" with a
#    blank, image-less row is the broken state users hit).
# 6. Verify the listing exposes the documented field names the web consumes
#    (regression guard: the API and web previously drifted onto different
#    field names and the feature shipped broken but green).
# 7. Verify the listing is readable on the PUBLIC (unauthenticated) endpoint.
# 8. Verify the reverse direction (Instance 2 adds Instance 1) also works.
# 9. Stream a real test video into the selected instance and verify its entry
#    in the other instance's directory flips live with the stream title, then
#    back offline after stopping. Interactive runs choose 0 (skip), 1, or 2
#    and pause for browser inspection while live. CI defaults to instance 2.
# 10. Verify a server that features another (by following it) does NOT show up
#     in the followee's followers list or count -- a featured-streams follow is
#     a directory relationship, not a fan follow.
#
# Requirements:
# - Go, C compiler (for building Owncast)
# - Caddy, mkcert
# - curl, jq
# - ffmpeg and a Sans font (for the live-status test stream; the Docker image
#   installs both, see run.sh)

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(git rev-parse --show-toplevel)"

# Configuration
PROXY_PORT="${PROXY_PORT:-8443}"

OWNCAST_PORT="${OWNCAST_PORT:-8080}"
OWNCAST_HOSTNAME="owncast.local"
OWNCAST_FED_USERNAME="streamerone"

OWNCAST2_PORT="${OWNCAST2_PORT:-8081}"
OWNCAST2_HOSTNAME="owncast2.local"
OWNCAST2_FED_USERNAME="streamertwo"

# RTMP ports must differ so both instances can bind their stream servers.
OWNCAST_RTMP_PORT="${OWNCAST_RTMP_PORT:-1935}"
OWNCAST2_RTMP_PORT="${OWNCAST2_RTMP_PORT:-1936}"

# snac2 isn't used by this test, but the shared Caddyfile references
# SNAC_PORT, so give it a value to keep the config valid.
SNAC_PORT="${SNAC_PORT:-9080}"

ADMIN_USER="admin"
ADMIN_PASS="abc123"
# Default stream key for a fresh Owncast instance (config/defaults.go).
STREAM_KEY="${STREAM_KEY:-abc123}"
CI="${CI:-false}"

# URLs (HTTPS via proxy)
OWNCAST_URL="https://${OWNCAST_HOSTNAME}:${PROXY_PORT}"
OWNCAST2_URL="https://${OWNCAST2_HOSTNAME}:${PROXY_PORT}"

# Directories and state
TEMP_DIR=""
OWNCAST_BIN=""
PROXY_PID=""
OC1_PID=""
OC2_PID=""
OC_LAST_PID=""
TEST_STREAM_PID=""
STREAM_INSTANCE="${STREAM_INSTANCE:-}"
STREAM_PORT="${OWNCAST2_PORT}"
STREAM_RTMP_PORT="${OWNCAST2_RTMP_PORT}"
STREAM_URL="${OWNCAST2_URL}"
OBSERVER_INSTANCE=1
OBSERVER_PORT="${OWNCAST_PORT}"
OBSERVER_URL="${OWNCAST_URL}"
OBSERVER_USERNAME="${OWNCAST_FED_USERNAME}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_test() { echo -e "${CYAN}[TEST]${NC} $1"; }

select_stream_instance() {
    if [[ -z "${STREAM_INSTANCE}" && "${CI}" != "true" ]]; then
        read -r -p "Which instance should stream? [0=don't stream, 1=owncast.local, 2=owncast2.local] (default 2): " STREAM_INSTANCE
    fi
    STREAM_INSTANCE="${STREAM_INSTANCE:-2}"
    case "${STREAM_INSTANCE}" in
        0)
            log_info "Streaming disabled; skipping the live-stream tests."
            return 0
            ;;
        1)
            STREAM_PORT="${OWNCAST_PORT}"
            STREAM_RTMP_PORT="${OWNCAST_RTMP_PORT}"
            STREAM_URL="${OWNCAST_URL}"
            OBSERVER_INSTANCE=2
            OBSERVER_PORT="${OWNCAST2_PORT}"
            OBSERVER_URL="${OWNCAST2_URL}"
            OBSERVER_USERNAME="${OWNCAST2_FED_USERNAME}"
            ;;
        2)
            STREAM_PORT="${OWNCAST2_PORT}"
            STREAM_RTMP_PORT="${OWNCAST2_RTMP_PORT}"
            STREAM_URL="${OWNCAST2_URL}"
            OBSERVER_INSTANCE=1
            OBSERVER_PORT="${OWNCAST_PORT}"
            OBSERVER_URL="${OWNCAST_URL}"
            OBSERVER_USERNAME="${OWNCAST_FED_USERNAME}"
            ;;
        *)
            log_error "STREAM_INSTANCE must be 0, 1, or 2"
            return 1
            ;;
    esac
    log_info "Instance ${STREAM_INSTANCE} streams; instance ${OBSERVER_INSTANCE} observes."
    log_info "Recommendation page while streaming: ${OBSERVER_URL}/"
}

# shellcheck disable=SC2329  # invoked via trap, not called directly
cleanup() {
    log_info "Cleaning up..."

    # Stop any test stream first so ffmpeg releases the RTMP connection before
    # the Owncast instances are torn down. Kill the ffmpeg child directly too,
    # since the ocTestStream wrapper does not forward signals to it.
    stop_test_stream

    for pid_var in PROXY_PID OC2_PID OC1_PID; do
        local pid="${!pid_var}"
        if [[ -n "${pid}" ]] && kill -0 "${pid}" 2>/dev/null; then
            kill "${pid}" 2>/dev/null || true
            wait "${pid}" 2>/dev/null || true
        fi
    done

    if [[ -n "${TEMP_DIR}" ]] && [[ -d "${TEMP_DIR}" ]]; then
        rm -rf "${TEMP_DIR}"
    fi

    log_info "Cleanup complete."
}

trap cleanup EXIT

# ==========================
# Setup
# ==========================

setup_temp_dir() {
    TEMP_DIR=$(mktemp -d)
    log_info "Temp directory: ${TEMP_DIR}"
}

check_hosts_entry() {
    local missing=0
    for host in "${OWNCAST_HOSTNAME}" "${OWNCAST2_HOSTNAME}"; do
        if ! grep -q "${host}" /etc/hosts 2>/dev/null; then
            log_error "Missing /etc/hosts entry for ${host}"
            missing=1
        fi
    done
    if [[ ${missing} -ne 0 ]]; then
        log_error "Please add: 127.0.0.1 ${OWNCAST_HOSTNAME} ${OWNCAST2_HOSTNAME}"
        exit 1
    fi
    log_info "Hosts entries verified"
}

check_certs() {
    CERT_DIR="${CERT_DIR:-${SCRIPT_DIR}/certs}"
    if [[ ! -f "${CERT_DIR}/cert.pem" ]] || [[ ! -f "${CERT_DIR}/key.pem" ]]; then
        log_error "Certificates not found in ${CERT_DIR}"
        exit 1
    fi
    log_info "Using certificates from ${CERT_DIR}"
}

start_proxy() {
    log_info "Starting HTTPS reverse proxy (Caddy)..."

    if ! command -v caddy &> /dev/null; then
        log_error "Caddy is not installed."
        return 1
    fi

    export PROXY_PORT="${PROXY_PORT}"
    export OWNCAST_PORT="${OWNCAST_PORT}"
    export OWNCAST2_PORT="${OWNCAST2_PORT}"
    export SNAC_PORT="${SNAC_PORT}"
    export CERT_FILE="${CERT_DIR}/cert.pem"
    export KEY_FILE="${CERT_DIR}/key.pem"

    local caddy_log="${TEMP_DIR}/caddy.log"
    caddy run --config "${SCRIPT_DIR}/Caddyfile" --adapter caddyfile > "${caddy_log}" 2>&1 &
    PROXY_PID=$!

    log_info "Caddy started with PID ${PROXY_PID}"
    sleep 2

    if ! kill -0 "${PROXY_PID}" 2>/dev/null; then
        log_error "Caddy failed to start. Check ${caddy_log}"
        cat "${caddy_log}"
        return 1
    fi

    local max_attempts=10
    local attempt=0
    while [[ ${attempt} -lt ${max_attempts} ]]; do
        if curl -sk "https://127.0.0.1:${PROXY_PORT}/" > /dev/null 2>&1; then
            log_info "Caddy proxy is ready"
            return 0
        fi
        attempt=$((attempt + 1))
        sleep 1
    done

    log_error "Caddy proxy did not become ready"
    return 1
}

build_owncast() {
    log_info "Building web assets..."
    # Ensure npm is available via nvm if not already on PATH.
    if ! command -v npm &>/dev/null && [[ -s "${HOME}/.nvm/nvm.sh" ]]; then
        # shellcheck disable=SC1091
        source "${HOME}/.nvm/nvm.sh"
        nvm use 24 &>/dev/null || nvm use 24.9.0 &>/dev/null || true
    fi
    pushd "${REPO_ROOT}" > /dev/null
    build/web/bundleWeb.sh --offline
    popd > /dev/null

    log_info "Building Owncast..."
    OWNCAST_BIN="${TEMP_DIR}/owncast"
    pushd "${REPO_ROOT}" > /dev/null
    CGO_ENABLED=1 go build -o "${OWNCAST_BIN}" main.go
    popd > /dev/null
    log_info "Owncast built: ${OWNCAST_BIN}"
}

# start_owncast_instance LABEL WEB_PORT RTMP_PORT
#
# Each instance runs from its own working directory so it gets a private
# ./data directory (the data dir path is a compile-time constant relative to
# the process CWD and can't be overridden by a flag). The database is kept in
# the shared temp dir and selected explicitly. The resulting PID is returned
# in the global OC_LAST_PID.
start_owncast_instance() {
    local label=$1
    local web_port=$2
    local rtmp_port=$3
    local workdir="${TEMP_DIR}/${label}"
    local db="${TEMP_DIR}/${label}.db"
    local log="${TEMP_DIR}/${label}.log"

    mkdir -p "${workdir}"

    log_info "Starting Owncast '${label}' (web ${web_port}, rtmp ${rtmp_port})..."
    (
        cd "${workdir}" || exit 1
        exec env \
            OWNCAST_ALLOW_INTERNAL_FEDERATION=true \
            OWNCAST_INSECURE_SKIP_VERIFY=true \
            "${OWNCAST_BIN}" \
            -database "${db}" \
            -webserverport "${web_port}" \
            -rtmpport "${rtmp_port}" \
            -enableVerboseLogging
    ) > "${log}" 2>&1 &
    OC_LAST_PID=$!
    log_info "Owncast '${label}' PID ${OC_LAST_PID} (log: ${log})"

    local max_attempts=30
    local attempt=0
    while [[ ${attempt} -lt ${max_attempts} ]]; do
        if curl -s "http://localhost:${web_port}/api/status" > /dev/null 2>&1; then
            log_info "Owncast '${label}' is ready"
            return 0
        fi
        if ! kill -0 "${OC_LAST_PID}" 2>/dev/null; then
            log_error "Owncast '${label}' exited early. Log:"
            cat "${log}"
            return 1
        fi
        attempt=$((attempt + 1))
        sleep 1
    done

    log_error "Owncast '${label}' did not become ready. Log tail:"
    tail -50 "${log}"
    return 1
}

# stop_owncast_instance LABEL PID
stop_owncast_instance() {
    local label=$1
    local pid=$2

    if [[ -z "${pid}" ]] || ! kill -0 "${pid}" 2>/dev/null; then
        return 0
    fi

    log_info "Stopping Owncast '${label}' (PID ${pid})..."
    kill "${pid}"
    wait "${pid}" 2>/dev/null || true
    log_info "Owncast '${label}' stopped"
}

get_admin_auth() {
    echo -n "${ADMIN_USER}:${ADMIN_PASS}" | base64
}

# configure_owncast WEB_PORT SERVER_URL FED_USERNAME
configure_owncast() {
    local web_port=$1
    local server_url=$2
    local fed_username=$3
    local base_url="http://localhost:${web_port}"
    local auth
    auth=$(get_admin_auth)

    log_info "Configuring Owncast at ${base_url} as ${server_url}"

    curl -s -X POST "${base_url}/api/admin/config/serverurl" \
        -H "Authorization: Basic ${auth}" -H "Content-Type: application/json" \
        -d "{\"value\": \"${server_url}\"}" > /dev/null

    curl -s -X POST "${base_url}/api/admin/config/federation/username" \
        -H "Authorization: Basic ${auth}" -H "Content-Type: application/json" \
        -d "{\"value\": \"${fed_username}\"}" > /dev/null

    curl -s -X POST "${base_url}/api/admin/config/federation/enable" \
        -H "Authorization: Basic ${auth}" -H "Content-Type: application/json" \
        -d '{"value": true}' > /dev/null

    # Public federation: regular (fan) follows auto-accept. Featured-streams
    # follows still require explicit approval regardless of this setting, which
    # this test exercises below.
    curl -s -X POST "${base_url}/api/admin/config/federation/private" \
        -H "Authorization: Basic ${auth}" -H "Content-Type: application/json" \
        -d '{"value": false}' > /dev/null
}

# ==========================
# API helpers
# ==========================

# add_featured_server WEB_PORT TARGET_URL -> prints JSON response body
add_featured_server() {
    local web_port=$1
    local target_url=$2
    local auth
    auth=$(get_admin_auth)

    curl -s -X POST "http://localhost:${web_port}/api/admin/federation/servers" \
        -H "Authorization: Basic ${auth}" \
        -H "Content-Type: application/json" \
        -d "{\"url\": \"${target_url}\"}"
}

# approve_featured_request WEB_PORT ACTOR_IRI -> approves a pending request from
# another Owncast server to feature this one (reuses the follower-approval API,
# which records the approval and returns the ActivityPub Accept).
approve_featured_request() {
    local web_port=$1
    local actor_iri=$2
    local auth
    auth=$(get_admin_auth)

    curl -s -X POST "http://localhost:${web_port}/api/admin/followers/approve" \
        -H "Authorization: Basic ${auth}" \
        -H "Content-Type: application/json" \
        -d "{\"actorIRI\": \"${actor_iri}\", \"approved\": true}"
}

# get_featured_servers WEB_PORT [auth] -> prints JSON body
# When the second argument is "admin" it hits the authenticated admin endpoint,
# which returns the full list including servers whose follow is still pending
# approval. Otherwise it hits the public, unauthenticated endpoint, which is
# filtered to accepted servers only.
get_featured_servers() {
    local web_port=$1
    local mode="${2:-public}"

    if [[ "${mode}" == "admin" ]]; then
        local auth
        auth=$(get_admin_auth)
        curl -s "http://localhost:${web_port}/api/admin/federation/servers" \
            -H "Authorization: Basic ${auth}"
    else
        curl -s "http://localhost:${web_port}/api/federation/servers"
    fi
}

# server_has_iri JSON IRI -> exit 0 if a server with that iri is present
server_has_iri() {
    echo "$1" | jq -e --arg iri "$2" '.servers[]? | select(.iri == $iri)' > /dev/null 2>&1
}

# server_follow_status JSON IRI -> prints followStatus (or empty)
server_follow_status() {
    echo "$1" | jq -r --arg iri "$2" '.servers[]? | select(.iri == $iri) | .followStatus' 2>/dev/null
}

# server_object JSON IRI -> prints the compact server object (or empty)
server_object() {
    echo "$1" | jq -c --arg iri "$2" '.servers[]? | select(.iri == $iri)' 2>/dev/null
}

# server_id JSON IRI -> prints the numeric id of the server with that iri
server_id() {
    echo "$1" | jq -r --arg iri "$2" '.servers[]? | select(.iri == $iri) | .id' 2>/dev/null
}

# remove_featured_server WEB_PORT ID -> unfeatures (and unfollows) a server
remove_featured_server() {
    local web_port=$1 id=$2 auth
    auth=$(get_admin_auth)
    curl -s -X DELETE "http://localhost:${web_port}/api/admin/federation/servers/${id}" \
        -H "Authorization: Basic ${auth}"
}

# server_field JSON IRI FIELD -> prints the value of FIELD (or empty).
# Note: we deliberately avoid `// empty` here because jq treats a literal
# false as "absent", which would turn isOnline=false into an empty string and
# make an offline server indistinguishable from a missing field. Map only
# null/missing to empty, preserving false/true and string values.
server_field() {
    echo "$1" | jq -r --arg iri "$2" --arg field "$3" \
        '.servers[]? | select(.iri == $iri) | .[$field] | if . == null then empty else . end' 2>/dev/null
}

# wait_for_follow_status WEB_PORT IRI EXPECTED_STATUS TIMEOUT_SECONDS
wait_for_follow_status() {
    local web_port=$1
    local iri=$2
    local expected=$3
    local timeout=${4:-30}
    local waited=0

    while [[ ${waited} -lt ${timeout} ]]; do
        local json status
        json=$(get_featured_servers "${web_port}" admin)
        status=$(server_follow_status "${json}" "${iri}")
        if [[ "${status}" == "${expected}" ]]; then
            return 0
        fi
        sleep 2
        waited=$((waited + 2))
    done
    return 1
}

# wait_for_failed_delivery DB COALESCE_KEY TIMEOUT_SECONDS
wait_for_failed_delivery() {
    local db=$1
    local coalesce_key=$2
    local timeout=${3:-20}
    local waited=0

    while [[ ${waited} -lt ${timeout} ]]; do
        local attempts
        attempts=$(sqlite3 -cmd ".timeout 5000" "${db}" \
            "SELECT COALESCE(MAX(attempts), 0) FROM ap_delivery_queue WHERE coalesce_key = '${coalesce_key}' AND last_error IS NOT NULL AND failed_at IS NULL;")
        if [[ "${attempts}" -ge 1 ]]; then
            echo "${attempts}"
            return 0
        fi
        sleep 1
        waited=$((waited + 1))
    done
    return 1
}

# expedite_delivery_retry DB COALESCE_KEY
expedite_delivery_retry() {
    local db=$1
    local coalesce_key=$2

    sqlite3 -cmd ".timeout 5000" "${db}" \
        "UPDATE ap_delivery_queue SET next_attempt_at = '2000-01-01T00:00:00Z', claimed_until = NULL WHERE coalesce_key = '${coalesce_key}' AND failed_at IS NULL;"
}

# wait_for_delivery_completion DB COALESCE_KEY TIMEOUT_SECONDS
wait_for_delivery_completion() {
    local db=$1
    local coalesce_key=$2
    local timeout=${3:-20}
    local waited=0

    while [[ ${waited} -lt ${timeout} ]]; do
        local remaining
        remaining=$(sqlite3 -cmd ".timeout 5000" "${db}" \
            "SELECT count(*) FROM ap_delivery_queue WHERE coalesce_key = '${coalesce_key}';")
        if [[ "${remaining}" -eq 0 ]]; then
            return 0
        fi
        sleep 1
        waited=$((waited + 1))
    done
    return 1
}

# ==========================
# Test scenarios
# ==========================

test_add_persists_pending_record() {
    log_test "TEST 1: Adding a featured server persists a directory record"

    local response success message
    response=$(add_featured_server "${OWNCAST_PORT}" "${OWNCAST2_URL}")
    log_info "Add response: ${response}"

    success=$(echo "${response}" | jq -r '.success // false' 2>/dev/null)
    if [[ "${success}" != "true" ]]; then
        message=$(echo "${response}" | jq -r '.message // ""' 2>/dev/null)
        log_error "TEST 1 FAILED: add request was not accepted: ${message}"
        return 1
    fi

    # The record must exist in the listing immediately, before any Accept
    # round-trips back. This is the core regression guard: previously nothing
    # was ever written to the federated_servers table, so the listing stayed
    # empty even though the Follow had been sent.
    local json
    json=$(get_featured_servers "${OWNCAST_PORT}" admin)
    if ! server_has_iri "${json}" "${OWNCAST2_URL}"; then
        log_error "TEST 1 FAILED: ${OWNCAST2_URL} not present in directory after add"
        log_error "Listing: ${json}"
        return 1
    fi

    log_test "TEST 1 PASSED: directory record persisted for ${OWNCAST2_URL}"
    return 0
}

test_follow_is_accepted() {
    log_test "TEST 2: Failed Accept delivery retries and completes approval"

    local instance1_actor="${OWNCAST_URL}/federation/user/${OWNCAST_FED_USERNAME}"
    local delivery_db="${TEMP_DIR}/owncast2.db"
    local delivery_key="follow-response:${instance1_actor}"

    # Both instances are public, so a regular fan follow would auto-accept. A
    # featured-streams follow must stay pending until instance 2 approves it.
    sleep 8
    local status
    status=$(server_follow_status "$(get_featured_servers "${OWNCAST_PORT}" admin)" "${OWNCAST2_URL}")
    if [[ "${status}" == "accepted" ]]; then
        log_error "TEST 2 FAILED: featured follow auto-accepted without approval (status=accepted)"
        return 1
    fi
    log_info "Featured follow is correctly awaiting approval (status=${status})"

    local feature_requests
    feature_requests=$(curl -s -H "Authorization: Basic $(get_admin_auth)" \
        "http://localhost:${OWNCAST2_PORT}/api/admin/federation/feature-requests")
    if ! echo "${feature_requests}" | jq -e --arg iri "${instance1_actor}" '.requests[]? | select(.link == $iri)' > /dev/null 2>&1; then
        log_error "TEST 2 FAILED: instance 1's request is not listed in instance 2's feature requests"
        log_error "Feature requests: ${feature_requests}"
        return 1
    fi
    log_info "Feature request from instance 1 is listed for approval"

    # Make the Accept fail exactly like a temporarily unavailable remote
    # instance. Caddy remains reachable but returns a retryable 502 because its
    # Owncast upstream is stopped.
    stop_owncast_instance "owncast1" "${OC1_PID}"
    OC1_PID=""

    local approval_response approval_success retry_attempts
    approval_response=$(approve_featured_request "${OWNCAST2_PORT}" "${instance1_actor}")
    approval_success=$(echo "${approval_response}" | jq -r '.success // false' 2>/dev/null)

    local retry_observed=true
    if [[ "${approval_success}" != "true" ]]; then
        log_error "TEST 2 FAILED: approval request failed: ${approval_response}"
        retry_observed=false
    elif retry_attempts=$(wait_for_failed_delivery "${delivery_db}" "${delivery_key}" 20); then
        local delivery_error
        delivery_error=$(sqlite3 "${delivery_db}" \
            "SELECT last_error FROM ap_delivery_queue WHERE coalesce_key = '${delivery_key}' LIMIT 1;")
        log_info "Observed failed Accept attempt ${retry_attempts}: ${delivery_error}"
    else
        log_error "TEST 2 FAILED: Accept delivery was not retained for retry"
        retry_observed=false
    fi

    # Always bring instance 1 back so later scenarios do not fail as collateral
    # damage if the retry assertion above fails.
    if ! start_owncast_instance "owncast1" "${OWNCAST_PORT}" "${OWNCAST_RTMP_PORT}"; then
        log_error "TEST 2 FAILED: instance 1 did not restart"
        return 1
    fi
    OC1_PID="${OC_LAST_PID}"

    if [[ "${retry_observed}" != "true" ]]; then
        return 1
    fi

    # The production delay starts at one minute. Make the retained row due now
    # so the live test exercises the retry without sleeping for the backoff.
    expedite_delivery_retry "${delivery_db}" "${delivery_key}"

    if ! wait_for_follow_status "${OWNCAST_PORT}" "${OWNCAST2_URL}" "accepted" 40; then
        local json
        json=$(get_featured_servers "${OWNCAST_PORT}" admin)
        status=$(server_follow_status "${json}" "${OWNCAST2_URL}")
        log_error "TEST 2 FAILED: follow status is '${status}' after retry, expected 'accepted'"
        log_error "Listing: ${json}"
        return 1
    fi

    if ! wait_for_delivery_completion "${delivery_db}" "${delivery_key}" 20; then
        log_error "TEST 2 FAILED: successful Accept remained in the delivery queue"
        return 1
    fi

    log_test "TEST 2 PASSED: failed Accept was retained, retried, and delivered after restart"
    return 0
}

test_metadata_is_populated() {
    log_test "TEST 3: Remote server metadata (name/logo) is populated after accept"

    # Once the Accept comes back, the follower resolves the remote actor and
    # stores its username, display name and logo. If this step is skipped the
    # directory entry is a blank row with no name and no image -- exactly the
    # broken state users reported. A green "follow accepted" is not enough;
    # the row has to actually carry the data the UI renders.
    local json name displayName logoUrl
    json=$(get_featured_servers "${OWNCAST_PORT}" admin)

    name=$(server_field "${json}" "${OWNCAST2_URL}" name)
    displayName=$(server_field "${json}" "${OWNCAST2_URL}" displayName)
    logoUrl=$(server_field "${json}" "${OWNCAST2_URL}" logoUrl)

    local failed=0
    if [[ -z "${name}" ]]; then
        log_error "TEST 3 FAILED: 'name' is empty; the Accept handler did not store the remote username"
        failed=1
    fi
    if [[ -z "${displayName}" ]]; then
        log_error "TEST 3 FAILED: 'displayName' is empty; the remote server's display name was not stored"
        failed=1
    fi
    if [[ -z "${logoUrl}" ]]; then
        log_error "TEST 3 FAILED: 'logoUrl' is empty; the featured stream would render with no image"
        failed=1
    fi

    if [[ ${failed} -ne 0 ]]; then
        log_error "Server record: $(server_object "${json}" "${OWNCAST2_URL}")"
        return 1
    fi

    log_test "TEST 3 PASSED: name='${name}', displayName='${displayName}', logoUrl='${logoUrl}'"
    return 0
}

test_listing_field_contract() {
    log_test "TEST 4: Directory listing exposes the documented field contract"

    # Public viewer fields must remain usable without exposing admin state.
    local json server
    json=$(get_featured_servers "${OWNCAST_PORT}" public)
    server=$(server_object "${json}" "${OWNCAST2_URL}")

    if [[ -z "${server}" ]]; then
        log_error "TEST 4 FAILED: ${OWNCAST2_URL} not present in public listing"
        log_error "Listing: ${json}"
        return 1
    fi

    local failed=0 field
    local required=(id iri name displayName logoUrl isOnline)
    for field in "${required[@]}"; do
        if ! echo "${server}" | jq -e "has(\"${field}\")" > /dev/null 2>&1; then
            log_error "TEST 4 FAILED: response is missing documented field '${field}'"
            failed=1
        fi
    done

    local forbidden=(addedAt followStatus priority lastStatusUpdate username pending url logo thumbnail lastChecked)
    for field in "${forbidden[@]}"; do
        if echo "${server}" | jq -e "has(\"${field}\")" > /dev/null 2>&1; then
            log_error "TEST 4 FAILED: public response contains non-public or legacy field '${field}'"
            failed=1
        fi
    done

    if [[ ${failed} -ne 0 ]]; then
        log_error "Server object: ${server}"
        return 1
    fi

    log_test "TEST 4 PASSED: listing exposes the documented field contract"
    return 0
}

test_public_listing_is_readable() {
    log_test "TEST 5: Directory listing is readable without admin auth"

    # The public watch page fetches this endpoint on load; it must not be
    # gated behind admin basic auth.
    local code
    code=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:${OWNCAST_PORT}/api/federation/servers")
    if [[ "${code}" != "200" ]]; then
        log_error "TEST 5 FAILED: public listing returned HTTP ${code}, expected 200"
        return 1
    fi

    local json
    json=$(get_featured_servers "${OWNCAST_PORT}" public)
    if ! server_has_iri "${json}" "${OWNCAST2_URL}"; then
        log_error "TEST 5 FAILED: ${OWNCAST2_URL} not present in public listing"
        log_error "Listing: ${json}"
        return 1
    fi

    log_test "TEST 5 PASSED: public listing returns the featured server"
    return 0
}

test_reverse_direction() {
    log_test "TEST 6: Reverse direction (instance 2 adds instance 1)"

    local response success message
    response=$(add_featured_server "${OWNCAST2_PORT}" "${OWNCAST_URL}")
    log_info "Add response: ${response}"

    success=$(echo "${response}" | jq -r '.success // false' 2>/dev/null)
    if [[ "${success}" != "true" ]]; then
        message=$(echo "${response}" | jq -r '.message // ""' 2>/dev/null)
        log_error "TEST 6 FAILED: add request was not accepted: ${message}"
        return 1
    fi

    # Instance 1 must approve being featured by instance 2.
    local instance2_actor="${OWNCAST2_URL}/federation/user/${OWNCAST2_FED_USERNAME}"
    log_info "Approving the feature request on instance 1..."
    approve_featured_request "${OWNCAST_PORT}" "${instance2_actor}" > /dev/null

    if wait_for_follow_status "${OWNCAST2_PORT}" "${OWNCAST_URL}" "accepted" 40; then
        log_test "TEST 6 PASSED: instance 2 featured instance 1; instance 1 approved and the follow was accepted"
        return 0
    fi

    local json status
    json=$(get_featured_servers "${OWNCAST2_PORT}" admin)
    status=$(server_follow_status "${json}" "${OWNCAST_URL}")
    log_error "TEST 6 FAILED: follow status is '${status}', expected 'accepted'"
    log_error "Listing: ${json}"
    return 1
}

# stop_test_stream stops the running test stream, if any.
#
# ocTestStream.sh runs ffmpeg in the foreground without forwarding signals or
# trapping EXIT (for the internal test-pattern path), so killing the wrapper
# alone orphans ffmpeg and the RTMP stream keeps running -- which would leave
# the source server live and no Leave would ever be sent. Kill the ffmpeg
# pushing to the selected instance's RTMP endpoint directly as well.
stop_test_stream() {
    if [[ -n "${TEST_STREAM_PID}" ]]; then
        pkill -f "rtmp://127.0.0.1:${STREAM_RTMP_PORT}/live/" 2>/dev/null || true
    fi
    if [[ -n "${TEST_STREAM_PID}" ]] && kill -0 "${TEST_STREAM_PID}" 2>/dev/null; then
        kill "${TEST_STREAM_PID}" 2>/dev/null || true
        wait "${TEST_STREAM_PID}" 2>/dev/null || true
    fi
    TEST_STREAM_PID=""
}

test_live_status_flip() {
    log_test "TEST 7: Featured stream flips to live when the remote goes online"
    if [[ "${STREAM_INSTANCE}" == "0" ]]; then
        log_warn "TEST 7 SKIPPED: streaming disabled"
        return 0
    fi

    # Both follow directions are accepted by TEST 6. The selected source
    # sends an Offer on connect and a Leave on disconnect to the observer.
    if [[ "${CI}" != "true" ]]; then
        echo ""
        read -r -p "Start a test stream on instance ${STREAM_INSTANCE}, observed by instance ${OBSERVER_INSTANCE}? [Y/n] "
        echo ""
        if [[ "${REPLY}" =~ ^[Nn]$ ]]; then
            log_warn "TEST 7 SKIPPED: declined to start a test stream"
            return 0
        fi
    fi

    if [[ ! -x "${REPO_ROOT}/test/ocTestStream.sh" ]]; then
        log_error "TEST 7 FAILED: ${REPO_ROOT}/test/ocTestStream.sh not found or not executable"
        return 1
    fi

    # Assert stream metadata propagates as well as the live-status boolean.
    local expected_title="Featured Streams Live Test"
    local auth
    auth=$(get_admin_auth)
    curl -s -X POST "http://localhost:${STREAM_PORT}/api/admin/config/streamtitle" \
        -H "Authorization: Basic ${auth}" -H "Content-Type: application/json" \
        -d "{\"value\": \"${expected_title}\"}" > /dev/null

    log_info "Starting test stream into instance ${STREAM_INSTANCE} (rtmp port ${STREAM_RTMP_PORT})..."
    "${REPO_ROOT}/test/ocTestStream.sh" "rtmp://127.0.0.1:${STREAM_RTMP_PORT}/live/${STREAM_KEY}" \
        > "${TEMP_DIR}/teststream.log" 2>&1 &
    TEST_STREAM_PID=$!

    # Allow time for ffmpeg startup and Offer delivery to the observer.
    local timeout=90 waited=0 online="" json
    while [[ ${waited} -lt ${timeout} ]]; do
        if ! kill -0 "${TEST_STREAM_PID}" 2>/dev/null; then
            log_error "TEST 7 FAILED: test stream process exited early. ffmpeg log:"
            cat "${TEMP_DIR}/teststream.log"
            TEST_STREAM_PID=""
            return 1
        fi
        json=$(get_featured_servers "${OBSERVER_PORT}" admin)
        online=$(server_field "${json}" "${STREAM_URL}" isOnline)
        if [[ "${online}" == "true" ]]; then
            break
        fi
        sleep 3
        waited=$((waited + 3))
    done

    if [[ "${online}" != "true" ]]; then
        log_error "TEST 7 FAILED: instance ${STREAM_INSTANCE} never showed as online on instance ${OBSERVER_INSTANCE} within ${timeout}s"
        log_error "Server record: $(server_object "${json}" "${STREAM_URL}")"
        stop_test_stream
        return 1
    fi

    # The Offer carries stream metadata; the title we set must have propagated.
    local title
    title=$(server_field "$(get_featured_servers "${OBSERVER_PORT}" admin)" "${STREAM_URL}" streamTitle)
    if [[ "${title}" != "${expected_title}" ]]; then
        log_error "TEST 7 FAILED: streamTitle is '${title}', expected '${expected_title}'"
        stop_test_stream
        return 1
    fi

    log_info "Instance ${STREAM_INSTANCE} is live on instance ${OBSERVER_INSTANCE} with title '${title}'."
    if [[ "${CI}" != "true" ]]; then
        read -r -p "Inspect ${OBSERVER_URL}/ for the recommendation; press Enter to stop the stream and continue. "
    fi
    log_info "Stopping the stream..."
    stop_test_stream

    # The Leave must flip the observer's entry offline before the staleness
    # sweep. Allow time for the source to detect its RTMP disconnect.
    local offline_timeout=180 offline_waited=0
    online="true"
    while [[ ${offline_waited} -lt ${offline_timeout} ]]; do
        json=$(get_featured_servers "${OBSERVER_PORT}" admin)
        online=$(server_field "${json}" "${STREAM_URL}" isOnline)
        if [[ "${online}" == "false" ]]; then
            break
        fi
        sleep 3
        offline_waited=$((offline_waited + 3))
    done

    if [[ "${online}" != "false" ]]; then
        log_error "TEST 7 FAILED: instance ${STREAM_INSTANCE} still shows online on instance ${OBSERVER_INSTANCE} ${offline_timeout}s after the stream stopped"
        log_error "Server record: $(server_object "${json}" "${STREAM_URL}")"

        local source_status
        source_status=$(curl -s "http://localhost:${STREAM_PORT}/api/status" 2>/dev/null | jq -c '{online}' 2>/dev/null)
        log_error "Instance ${STREAM_INSTANCE} self-reported status: ${source_status:-<none>}"
        log_error "--- source log (disconnect / leave / ping) ---"
        grep -iE "disconnect|leave|offer|ping|offline|transcoder complet|federat" "${TEMP_DIR}/owncast${STREAM_INSTANCE}.log" 2>/dev/null | tail -25 >&2 || true
        log_error "--- observer log (inbox / leave) ---"
        grep -iE "leave|offer|offline|federated server|inbox" "${TEMP_DIR}/owncast${OBSERVER_INSTANCE}.log" 2>/dev/null | tail -25 >&2 || true
        return 1
    fi

    log_test "TEST 7 PASSED: went live with title '${title}', then back offline ~${offline_waited}s after the stream ended"
    return 0
}

test_featuring_server_hidden_from_followers() {
    log_test "TEST 8: A server that features us is not shown as a follower"

    # Instance 1 featured instance 2 by following it (TEST 1-2), so instance 1
    # is technically a follower of instance 2. Because that is an
    # Owncast-server (featured-streams) follow, it must NOT appear in instance
    # 2's public followers list or follower count -- it's a directory
    # relationship, not a fan. (Both instances only ever feature each other in
    # this test, so the visible follower count should be zero.)
    local actor_iri followers total failed=0
    actor_iri="${OWNCAST_URL}/federation/user/${OWNCAST_FED_USERNAME}"
    followers=$(curl -s "http://localhost:${OWNCAST2_PORT}/api/followers")
    total=$(echo "${followers}" | jq -r '.total // 0' 2>/dev/null)

    if echo "${followers}" | jq -e --arg iri "${actor_iri}" '.results[]? | select(.link == $iri)' > /dev/null 2>&1; then
        log_error "TEST 8 FAILED: featuring server ${actor_iri} appears in instance 2's followers list"
        failed=1
    fi

    if [[ "${total}" != "0" ]]; then
        log_error "TEST 8 FAILED: instance 2 follower count is ${total}, expected 0 (its only follow is a featured-streams follow)"
        failed=1
    fi

    if [[ ${failed} -ne 0 ]]; then
        log_error "Followers response: ${followers}"
        return 1
    fi

    log_test "TEST 8 PASSED: the featuring server is hidden from instance 2's followers (count=${total})"
    return 0
}

test_feature_while_already_live() {
    log_test "TEST 9: Featuring a server that is already live shows it live promptly"
    if [[ "${STREAM_INSTANCE}" == "0" ]]; then
        log_warn "TEST 9 SKIPPED: streaming disabled"
        return 0
    fi

    if [[ "${CI}" != "true" ]]; then
        echo ""
        read -r -p "Run 'feature while already live' with instance ${STREAM_INSTANCE} streaming and instance ${OBSERVER_INSTANCE} observing? [Y/n] "
        echo ""
        if [[ "${REPLY}" =~ ^[Nn]$ ]]; then
            log_warn "TEST 9 SKIPPED: declined to start a test stream"
            return 0
        fi
    fi

    local observer_actor="${OBSERVER_URL}/federation/user/${OBSERVER_USERNAME}"

    # Unfeature the source so its go-live ping cannot mask the Accept's
    # carried live status when the observer re-features it.
    local id
    id=$(server_id "$(get_featured_servers "${OBSERVER_PORT}" admin)" "${STREAM_URL}")
    if [[ -z "${id}" || "${id}" == "null" ]]; then
        log_error "TEST 9 FAILED: could not find instance ${STREAM_INSTANCE}'s id to unfeature"
        return 1
    fi
    log_info "Unfeaturing instance ${STREAM_INSTANCE} (id ${id}); waiting for the Undo to propagate..."
    remove_featured_server "${OBSERVER_PORT}" "${id}" > /dev/null
    sleep 12

    # Start the source streaming while the observer is not following it.
    local expected_title="Already Live Test"
    local auth
    auth=$(get_admin_auth)
    curl -s -X POST "http://localhost:${STREAM_PORT}/api/admin/config/streamtitle" \
        -H "Authorization: Basic ${auth}" -H "Content-Type: application/json" \
        -d "{\"value\": \"${expected_title}\"}" > /dev/null

    log_info "Starting test stream into instance ${STREAM_INSTANCE}..."
    "${REPO_ROOT}/test/ocTestStream.sh" "rtmp://127.0.0.1:${STREAM_RTMP_PORT}/live/${STREAM_KEY}" \
        > "${TEMP_DIR}/teststream-live.log" 2>&1 &
    TEST_STREAM_PID=$!

    local waited=0
    while [[ ${waited} -lt 90 ]]; do
        if [[ "$(curl -s "http://localhost:${STREAM_PORT}/api/status" | jq -r '.online // false' 2>/dev/null)" == "true" ]]; then
            break
        fi
        if ! kill -0 "${TEST_STREAM_PID}" 2>/dev/null; then
            log_error "TEST 9 FAILED: test stream exited early. ffmpeg log:"
            cat "${TEMP_DIR}/teststream-live.log"
            TEST_STREAM_PID=""
            return 1
        fi
        sleep 3
        waited=$((waited + 3))
    done
    if [[ "$(curl -s "http://localhost:${STREAM_PORT}/api/status" | jq -r '.online // false' 2>/dev/null)" != "true" ]]; then
        log_error "TEST 9 FAILED: instance ${STREAM_INSTANCE} did not go live"
        stop_test_stream
        return 1
    fi

    # Re-feature the source while it is already live, then approve.
    local response success
    response=$(add_featured_server "${OBSERVER_PORT}" "${STREAM_URL}")
    success=$(echo "${response}" | jq -r '.success // false' 2>/dev/null)
    if [[ "${success}" != "true" ]]; then
        log_error "TEST 9 FAILED: re-feature add not accepted: $(echo "${response}" | jq -r '.message // ""')"
        stop_test_stream
        return 1
    fi
    log_info "Approving the re-feature request on instance ${STREAM_INSTANCE}..."
    approve_featured_request "${STREAM_PORT}" "${observer_actor}" > /dev/null
    if ! wait_for_follow_status "${OBSERVER_PORT}" "${STREAM_URL}" "accepted" 40; then
        log_error "TEST 9 FAILED: re-feature follow not accepted (the unfeature Undo may not have cleared the prior follower)"
        stop_test_stream
        return 1
    fi

    # Live status must come from the Accept; the next periodic ping is
    # minutes away.
    local online="" json
    waited=0
    while [[ ${waited} -lt 30 ]]; do
        json=$(get_featured_servers "${OBSERVER_PORT}" admin)
        online=$(server_field "${json}" "${STREAM_URL}" isOnline)
        if [[ "${online}" == "true" ]]; then
            break
        fi
        sleep 3
        waited=$((waited + 3))
    done

    if [[ "${online}" != "true" ]]; then
        log_error "TEST 9 FAILED: instance ${STREAM_INSTANCE} not shown live on instance ${OBSERVER_INSTANCE} within 30s of acceptance"
        log_error "Server record: $(server_object "${json}" "${STREAM_URL}")"
        stop_test_stream
        return 1
    fi

    local title
    title=$(server_field "$(get_featured_servers "${OBSERVER_PORT}" admin)" "${STREAM_URL}" streamTitle)
    stop_test_stream
    log_test "TEST 9 PASSED: featured-while-live shown online ~${waited}s after accept (title='${title}')"
    return 0
}

# ==========================
# Results
# ==========================

print_results() {
    local passed=$1
    local failed=$2
    local total=$((passed + failed))

    echo ""
    echo "========================================"
    echo "Featured Streams Test Results"
    echo "========================================"
    echo "Tests Run:    ${total}"
    echo "Tests Passed: ${passed}"
    echo "Tests Failed: ${failed}"
    echo ""

    if [[ "${failed}" -eq 0 ]]; then
        echo -e "${GREEN}ALL TESTS PASSED${NC}"
    else
        echo -e "${RED}${failed} TEST(S) FAILED${NC}"
    fi
    echo "========================================"
}

# ==========================
# Main
# ==========================

main() {
    echo ""
    echo "========================================"
    echo "Featured Streams (mini-directory) Test"
    echo "========================================"
    echo "Verifies the Owncast-to-Owncast featured"
    echo "streams directory flow across two servers."
    echo ""

    local passed=0
    local failed=0

    echo "----------------------------------------"
    echo "STEP 1: Setup proxy and certificates"
    echo "----------------------------------------"
    setup_temp_dir
    check_hosts_entry
    check_certs
    start_proxy
    echo ""

    echo "----------------------------------------"
    echo "STEP 2: Build and start two Owncast instances"
    echo "----------------------------------------"
    build_owncast

    # OC1_PID/OC2_PID are read indirectly in cleanup() via ${!pid_var},
    # which shellcheck cannot trace, hence the SC2034 suppressions.
    start_owncast_instance "owncast1" "${OWNCAST_PORT}" "${OWNCAST_RTMP_PORT}"
    # shellcheck disable=SC2034
    OC1_PID="${OC_LAST_PID}"
    start_owncast_instance "owncast2" "${OWNCAST2_PORT}" "${OWNCAST2_RTMP_PORT}"
    # shellcheck disable=SC2034
    OC2_PID="${OC_LAST_PID}"

    configure_owncast "${OWNCAST_PORT}" "${OWNCAST_URL}" "${OWNCAST_FED_USERNAME}"
    configure_owncast "${OWNCAST2_PORT}" "${OWNCAST2_URL}" "${OWNCAST2_FED_USERNAME}"
    sleep 2
    echo ""

    echo "----------------------------------------"
    echo "STEP 3: Run test scenarios"
    echo "----------------------------------------"

    if test_add_persists_pending_record; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
    echo ""
    if test_follow_is_accepted; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
    echo ""
    if test_metadata_is_populated; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
    echo ""
    if test_listing_field_contract; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
    echo ""
    if test_public_listing_is_readable; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
    echo ""
    if test_reverse_direction; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
    echo ""
    select_stream_instance
    if test_live_status_flip; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
    echo ""
    if test_featuring_server_hidden_from_followers; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
    echo ""
    if test_feature_while_already_live; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
    echo ""

    print_results "${passed}" "${failed}"

    if [[ "${KEEP_RUNNING:-}" == "true" ]]; then
        log_info "Keeping servers running (Ctrl+C to stop)..."
        log_info "  Owncast 1: http://localhost:${OWNCAST_PORT} (${OWNCAST_URL})"
        log_info "  Owncast 2: http://localhost:${OWNCAST2_PORT} (${OWNCAST2_URL})"
        wait
    fi

    if [[ "${failed}" -gt 0 ]]; then
        exit 1
    fi

    exit 0
}

main "$@"