Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions documentation/components/adapters/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,24 @@ http_pagination_last_record_cursor('data.*.id', http_request_option_query('since
stop_when: http_stop_when_flag_false('has_more'));
```

### Sensitive headers

`http_pagination_next_url` and `http_pagination_link_header` follow a URL from the response. When that URL changes
the host, or goes from `https` to `http`, the headers of `SensitiveHeaders` are removed from the next request.

```php
use Flow\ETL\Adapter\Http\IO\Extractor\Pagination\SensitiveHeaders;

// add a header to the defaults
http_pagination_next_url('next', sensitive_headers: [...SensitiveHeaders::toArray(), 'X-Tenant-Secret']);

// keep one of the defaults
http_pagination_link_header('next', sensitive_headers: array_diff(
SensitiveHeaders::toArray(),
[SensitiveHeaders::Cookie->value],
));
```

### Injection - where the token goes (`http_request_option_*`)

```php
Expand Down
1 change: 1 addition & 0 deletions mago.toml
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ disallowed-functions = { enabled = true, level = "error", functions = [{ name =

[formatter]
excludes = ["web/landing/content/examples/**"]
preserve-redundant-logical-binary-expression-parentheses = true

[guard]
excludes = ["src/**/tests/**", "web/landing/content/examples/**"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,28 +141,40 @@ function http_pagination_cursor(
);
}

/**
* @param null|array<string> $sensitive_headers headers removed when the next URL changes the host or goes from https to http, null for SensitiveHeaders::toArray()
*/
#[DocumentationDSL(module: Module::HTTP, type: Type::HELPER)]
function http_pagination_next_url(
string $path,
bool $stop_on_client_error = true,
?StopWhen $stop_when = null,
?array $sensitive_headers = null,
): Paginator {
$default = new PathMissing($path);

return new Paginator(
new NextUrlFromBody($path),
new NextUrlFromBody($path, $sensitive_headers),
$stop_when === null ? $default : new AnyOf($default, $stop_when),
$stop_on_client_error,
);
}

/**
* @param null|array<string> $sensitive_headers headers removed when the next URL changes the host or goes from https to http, null for SensitiveHeaders::toArray()
*/
#[DocumentationDSL(module: Module::HTTP, type: Type::HELPER)]
function http_pagination_link_header(
string $rel = 'next',
bool $stop_on_client_error = true,
?StopWhen $stop_when = null,
?array $sensitive_headers = null,
): Paginator {
return new Paginator(new LinkHeader($rel), $stop_when ?? new NeverStop(), $stop_on_client_error);
return new Paginator(
new LinkHeader($rel, $sensitive_headers),
$stop_when ?? new NeverStop(),
$stop_on_client_error,
);
}

#[DocumentationDSL(module: Module::HTTP, type: Type::HELPER)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Flow\ETL\Foundation\Exception\RuntimeException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UriInterface;

use function Flow\ArrayDot\array_dot_set;
use function Flow\Types\DSL\type_array;
Expand All @@ -17,10 +18,14 @@

final class RequestOption
{
/**
* @param null|array<string> $sensitiveHeaders
*/
private function __construct(
public readonly InjectInto $into,
public readonly string $name,
private readonly ?StreamFactoryInterface $streamFactory = null,
private readonly ?array $sensitiveHeaders = null,
) {}

public static function bodyPath(string $path, StreamFactoryInterface $streamFactory): self
Expand All @@ -38,9 +43,12 @@ public static function queryParam(string $name): self
return new self(InjectInto::QueryParam, $name);
}

public static function replaceUri(): self
/**
* @param null|array<string> $sensitiveHeaders headers removed when the host changes or https becomes http, null for SensitiveHeaders::toArray()
*/
public static function replaceUri(?array $sensitiveHeaders = null): self
{
return new self(InjectInto::ReplaceUri, '');
return new self(InjectInto::ReplaceUri, '', sensitiveHeaders: $sensitiveHeaders);
}

public function apply(RequestInterface $base, mixed $value): RequestInterface
Expand All @@ -49,7 +57,7 @@ public function apply(RequestInterface $base, mixed $value): RequestInterface
InjectInto::QueryParam => $this->applyQueryParam($base, $value),
InjectInto::Header => $base->withHeader($this->name, (string) $value),
InjectInto::BodyPath => $this->applyBodyPath($base, $value),
InjectInto::ReplaceUri => $base->withUri((new RelativeUriResolver())->resolve(
InjectInto::ReplaceUri => $this->removeSensitiveHeaders($base, (new RelativeUriResolver())->resolve(
$base->getUri(),
(string) $value,
)),
Expand All @@ -65,6 +73,22 @@ private function applyQueryParam(RequestInterface $base, mixed $value): RequestI
return $base->withUri($base->getUri()->withQuery(http_build_query($query)));
}

private function removeSensitiveHeaders(RequestInterface $base, UriInterface $newUri): RequestInterface
{
$oldUri = $base->getUri();

if (
$oldUri->getHost() !== $newUri->getHost()
|| ($oldUri->getScheme() === 'https' && $newUri->getScheme() === 'http')
) {
foreach ($this->sensitiveHeaders ?? SensitiveHeaders::toArray() as $sensitiveHeader) {
$base = $base->withoutHeader($sensitiveHeader);
}
}

return $base->withUri($newUri);
}

private function applyBodyPath(RequestInterface $base, mixed $value): RequestInterface
{
if ($this->streamFactory === null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace Flow\ETL\Adapter\Http\IO\Extractor\Pagination;

enum SensitiveHeaders: string
{
case ApiKey = 'Api-Key';
case Authorization = 'Authorization';
case Cookie = 'Cookie';
case DatadogApiKey = 'DD-API-KEY';
case DatadogApplicationKey = 'DD-APPLICATION-KEY';
case GitlabJobToken = 'JOB-TOKEN';
case GitlabPrivateToken = 'PRIVATE-TOKEN';
case OcpApimSubscriptionKey = 'Ocp-Apim-Subscription-Key';
case ProxyAuthorization = 'Proxy-Authorization';
case XAccessToken = 'X-Access-Token';
case XAmzSecurityToken = 'X-Amz-Security-Token';
case XApiKey = 'X-Api-Key';
case XApiToken = 'X-Api-Token';
case XAuthEmail = 'X-Auth-Email';
case XAuthKey = 'X-Auth-Key';
case XAuthToken = 'X-Auth-Token';
case XCsrfToken = 'X-CSRF-Token';
case XFunctionsKey = 'X-Functions-Key';
case XGoogApiKey = 'X-Goog-Api-Key';
case XShopifyAccessToken = 'X-Shopify-Access-Token';
case XVaultToken = 'X-Vault-Token';
case XXsrfToken = 'X-XSRF-Token';

/**
* @return list<string>
*/
public static function toArray(): array
{
return array_map(static fn(self $header): string => $header->value, self::cases());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@ final class LinkHeader implements PaginationStrategy
{
private LinkHeaderParser $parser;

/**
* @param null|array<string> $sensitiveHeaders
*/
public function __construct(
private readonly string $rel = 'next',
private readonly ?array $sensitiveHeaders = null,
) {
$this->parser = new LinkHeaderParser();
}
Expand All @@ -34,6 +38,6 @@ public function nextRequest(RequestInterface $base, DecodedResponse $previous, P
return null;
}

return RequestOption::replaceUri()->apply($base, $url);
return RequestOption::replaceUri($this->sensitiveHeaders)->apply($base, $url);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@

final class NextUrlFromBody implements PaginationStrategy
{
/**
* @param null|array<string> $sensitiveHeaders
*/
public function __construct(
private readonly string $path,
private readonly ?array $sensitiveHeaders = null,
) {}

public function initialRequest(RequestInterface $base): RequestInterface
Expand All @@ -40,6 +44,6 @@ public function nextRequest(RequestInterface $base, DecodedResponse $previous, P
return null;
}

return RequestOption::replaceUri()->apply($base, $url);
return RequestOption::replaceUri($this->sensitiveHeaders)->apply($base, $url);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Flow\ETL\Adapter\Http\Tests\Unit\IO\Extractor\Pagination;

use Flow\ETL\Adapter\Http\IO\Extractor\Pagination\RequestOption;
use Flow\ETL\Adapter\Http\IO\Extractor\Pagination\SensitiveHeaders;
use Flow\ETL\Tests\FlowTestCase;
use Nyholm\Psr7\Factory\Psr17Factory;

Expand Down Expand Up @@ -58,6 +59,134 @@ public function test_query_param_overrides_same_name(): void
static::assertSame(['page' => '7', 'per_page' => '50'], $query);
}

public function test_replace_uri_keeps_sensitive_headers_on_same_host(): void
{
$request = (new Psr17Factory())
->createRequest('GET', 'https://api.example.com/items?page=1')
->withHeader('Authorization', 'Bearer secret')
->withHeader('Cookie', 'session=abc');

$result = RequestOption::replaceUri()->apply($request, '/items?page=2');

static::assertSame(['Bearer secret'], $result->getHeader('Authorization'));
static::assertSame(['session=abc'], $result->getHeader('Cookie'));
}

public function test_replace_uri_removes_sensitive_headers_on_cross_host(): void
{
$request = (new Psr17Factory())
->createRequest('GET', 'https://api.example.com/items?page=1')
->withHeader('Authorization', 'Bearer secret')
->withHeader('Proxy-Authorization', 'Basic secret')
->withHeader('Cookie', 'session=abc')
->withHeader('Accept', 'application/json');

$result = RequestOption::replaceUri()->apply($request, 'https://evil.example.org/items?page=2');

static::assertSame('evil.example.org', $result->getUri()->getHost());
static::assertFalse($result->hasHeader('Authorization'));
static::assertFalse($result->hasHeader('Proxy-Authorization'));
static::assertFalse($result->hasHeader('Cookie'));
static::assertSame(['application/json'], $result->getHeader('Accept'));
}

public function test_replace_uri_on_cross_host_without_sensitive_headers(): void
{
$request = (new Psr17Factory())->createRequest('GET', 'https://api.example.com/items?page=1');

$result = RequestOption::replaceUri()->apply($request, 'https://other.example.org/items?page=2');

static::assertSame('https://other.example.org/items?page=2', (string) $result->getUri());
static::assertFalse($result->hasHeader('Authorization'));
static::assertFalse($result->hasHeader('Cookie'));
}

public function test_replace_uri_removes_custom_sensitive_headers_on_cross_host(): void
{
$request = (new Psr17Factory())
->createRequest('GET', 'https://api.example.com/items?page=1')
->withHeader('Authorization', 'Bearer secret')
->withHeader('X-Tenant-Secret', 'key')
->withHeader('Accept', 'application/json');

$result = RequestOption::replaceUri([...SensitiveHeaders::toArray(), 'x-tenant-secret'])->apply(
$request,
'https://evil.example.org/items?page=2',
);

static::assertFalse($result->hasHeader('Authorization'));
static::assertFalse($result->hasHeader('X-Tenant-Secret'));
static::assertSame(['application/json'], $result->getHeader('Accept'));
}

public function test_replace_uri_keeps_a_header_taken_out_of_the_sensitive_headers_on_cross_host(): void
{
$request = (new Psr17Factory())
->createRequest('GET', 'https://api.example.com/items?page=1')
->withHeader('Authorization', 'Bearer secret')
->withHeader('Cookie', 'session=abc');

$result = RequestOption::replaceUri(array_diff(SensitiveHeaders::toArray(), [
SensitiveHeaders::Cookie->value,
]))->apply($request, 'https://other.example.org/items?page=2');

static::assertFalse($result->hasHeader('Authorization'));
static::assertSame(['session=abc'], $result->getHeader('Cookie'));
}

public function test_replace_uri_removes_every_default_sensitive_header_on_cross_host(): void
{
$request = (new Psr17Factory())->createRequest('GET', 'https://api.example.com/items?page=1');

foreach (SensitiveHeaders::toArray() as $header) {
$request = $request->withHeader($header, 'secret');
}

static::assertSame(
['Host' => ['evil.example.org']],
RequestOption::replaceUri()->apply($request, 'https://evil.example.org/items?page=2')->getHeaders(),
);
}

public function test_replace_uri_keeps_custom_sensitive_headers_on_same_host(): void
{
$request = (new Psr17Factory())
->createRequest('GET', 'https://api.example.com/items?page=1')
->withHeader('X-Api-Key', 'key');

$result = RequestOption::replaceUri(['X-Api-Key'])->apply($request, '/items?page=2');

static::assertSame(['key'], $result->getHeader('X-Api-Key'));
}

public function test_replace_uri_removes_sensitive_headers_on_scheme_downgrade(): void
{
$request = (new Psr17Factory())
->createRequest('GET', 'https://api.example.com/items?page=1')
->withHeader('Authorization', 'Bearer secret')
->withHeader('Cookie', 'session=abc');

$result = RequestOption::replaceUri()->apply($request, 'http://api.example.com/items?page=2');

static::assertSame('http', $result->getUri()->getScheme());
static::assertFalse($result->hasHeader('Authorization'));
static::assertFalse($result->hasHeader('Cookie'));
}

public function test_replace_uri_keeps_sensitive_headers_on_scheme_upgrade(): void
{
$request = (new Psr17Factory())
->createRequest('GET', 'http://api.example.com/items?page=1')
->withHeader('Authorization', 'Bearer secret')
->withHeader('Cookie', 'session=abc');

$result = RequestOption::replaceUri()->apply($request, 'https://api.example.com/items?page=2');

static::assertSame('https', $result->getUri()->getScheme());
static::assertSame(['Bearer secret'], $result->getHeader('Authorization'));
static::assertSame(['session=abc'], $result->getHeader('Cookie'));
}

public function test_replace_uri_resolves_relative_reference_against_base(): void
{
$request = (new Psr17Factory())->createRequest('GET', 'https://api.example.com/v2/items?page=1');
Expand Down
Loading
Loading