Files

60 lines
2.2 KiB
PHP
Raw Permalink Normal View History

<?php
declare( strict_types=1 );
namespace StreamGoals\Update;
/**
* Pure decisions for redirects of token-bearing update requests. The access token may only ever travel to the pinned
* host over https; a redirect is followed (by Updater) only when it stays on that host, with a small hop limit.
*/
final class RedirectPolicy {
public const MAX_HOPS = 3;
/**
* @param string $current URL that answered with a 3xx.
* @param string $location Its Location header (absolute or relative).
* @param string $pinnedHost Configured update host (lower case).
* @param int $hop Redirects already followed (0 for the first 3xx).
* @return string|null Absolute URL to follow with the token, or null to stop and NOT follow.
*/
public static function nextUrl( string $current, string $location, string $pinnedHost, int $hop ): ?string {
if ( $hop >= self::MAX_HOPS || '' === trim( $location ) || preg_match( '/[\x00-\x1f\x7f]/', $location ) ) {
return null;
}
$abs = self::resolve( $current, trim( $location ) );
if ( null === $abs || ! ReleaseParser::isAllowedUrl( $abs, $pinnedHost ) ) {
return null;
}
$port = parse_url( $abs, PHP_URL_PORT );
return null === $port || 443 === (int) $port ? $abs : null;
}
/** Whether the token may be attached to a request for $url. */
public static function tokenAllowed( string $url, string $pinnedHost ): bool {
if ( ! ReleaseParser::isAllowedUrl( $url, $pinnedHost ) ) {
return false;
}
$port = parse_url( $url, PHP_URL_PORT );
return null === $port || 443 === (int) $port;
}
private static function resolve( string $base, string $loc ): ?string {
if ( 1 === preg_match( '#^[a-z][a-z0-9+.\-]*://#i', $loc ) ) {
return $loc;
}
$b = parse_url( $base );
if ( ! is_array( $b ) || ! isset( $b['scheme'], $b['host'] ) ) {
return null;
}
if ( str_starts_with( $loc, '//' ) ) {
return $b['scheme'] . ':' . $loc;
}
$origin = $b['scheme'] . '://' . $b['host'] . ( isset( $b['port'] ) ? ':' . $b['port'] : '' );
if ( str_starts_with( $loc, '/' ) ) {
return $origin . $loc;
}
$dir = preg_replace( '#/[^/]*$#', '/', (string) ( $b['path'] ?? '/' ) );
return $origin . $dir . $loc;
}
}