Skip to content
Open
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
23 changes: 23 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
[workspace]
resolver = "2"
members = [
"components/authorization-injector-core",
"components/authorization-injector",
"components/client",
"components/gate",
"components/gate-client",
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ A collection of utility components that remix wasi:http types and interfaces.

## Components

- [`authorization-injector`](./components/authorization-injector/): adds an `authorization` header to requests sent with `wasi:http/client`, by origin, with every standard method except TRACE, `authorization-injector-core` with [`authorization-injector-method-config`](./components/authorization-injector-method-config/)
- [`authorization-injector-core`](./components/authorization-injector-core/): adds an `authorization` header to requests sent with `wasi:http/client`, by origin and method, configured with `wasi:config/store`
- [`client`](./components/client/): a higher-level HTTP client that delegates to `wasi:http/client`
- [`status-codes`](./components/status-codes/): constants for HTTP status codes

Expand Down
19 changes: 19 additions & 0 deletions components/authorization-injector-core/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "authorization-injector-core"
version = "0.1.0"
edition = "2024"
license = "Apache-2.0"

[lib]
crate-type = ["cdylib"]

[dependencies]
http-utils = { workspace = true }
# spawn forwards the result of transmitting the request with the authorization header
wit-bindgen = { workspace = true, features = ["async-spawn"] }

[dev-dependencies]
http = { workspace = true }
test-harness = { workspace = true }
tokio = { workspace = true }
wasmtime = { workspace = true }
64 changes: 64 additions & 0 deletions components/authorization-injector-core/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# `authorization-injector-core`

Adds an `authorization` header to requests sent with `wasi:http/client` that don't already have one, by the request's origin and method.

A request that already has an `authorization` header, whose method isn't allowed, or whose origin no key matches, is sent unchanged. [`authorization-injector`](../authorization-injector/) is this component with a method config that allows every standard method except TRACE.

## Credentials

The value for each origin is read from `wasi:config/store`. The key is the origin, `scheme://host[:port]`, and the value is the `authorization` header to send.

```properties
https://api.example.com=Bearer 0123456789abcdef
https://*.example.com=Basic dXNlcjpwYXNz
http://localhost:*=Bearer dev-token
https://public.example.com=
```

- Without a port, a key matches the scheme's default port, e.g. `https://example.com` matches `https://example.com:443` but not `https://example.com:8443`.
- A host starting with `*.` matches the domain and every subdomain, e.g. `*.example.com` matches `example.com`, `foo.example.com` and `a.b.example.com`, but not `notexample.com`. `*` is only allowed as the first label of the host.
- A port of `*` matches any port, including the default.
- Schemes and hosts match case-insensitively. Userinfo in the request authority is ignored.
- When several keys match, the most specific one is used: an exact host before a wildcard host, a longer wildcard domain before a shorter one, then an exact port before `*`.
- An empty value sends no `authorization` header, e.g. to exclude `public.example.com` from `*.example.com` above.

## Methods

Whether the authorization is added to a request with each method is read from the `methods` import, a `wasi:config/store`. The key is the lowercase method, e.g. `get` or `post`, the value is `deferred` or `denied`. A method without a key uses the `*` key, and is denied without it, so without a method config no authorization is added.

```properties
get=deferred
post=deferred
trace=denied
*=denied
```

Deny `trace`: the response to a TRACE request echoes the request back, an added header would reveal the credential to the caller.

## Invalid config

Every credential key must be a valid origin, no two keys may match the same origins, e.g. `https://example.com` and `https://example.com:443`, and every credential must be a valid header value. Every method value must be `deferred`, an empty value, or `denied`. Otherwise the cause is logged at the `critical` level and every request fails with `internal-error`, so a typo is noticed rather than ignored. A credential is never logged:

```
Invalid config COMPONENT=authorization-injector-core CONFIG=credentials KEY=api.example.com ERROR=expected 'scheme://host[:port]'
Invalid config COMPONENT=authorization-injector-core CONFIG=methods KEY=post VALUE=allowed ERROR=expected one of: 'deferred', 'denied'
```

> [!CAUTION]
> The configured values are credentials. Any request the wrapped component sends to a matching origin with an allowed method carries the credential, whatever its path. Configure the narrowest keys and methods you can, and prefer `https`.

The headers of a `wasi:http` request are immutable, so a request that gets an `authorization` header is sent as a new request, with a copy of its headers, the same method, target and options, and its body and trailers. The result of transmitting the new request is forwarded to the original request.

## Interfaces

Imports:

- `wasi:config/store@0.2.0-rc.1`: the authorization for each origin
- `methods: wasi:config/store@0.2.0-rc.1`: whether the authorization is added for each method
- `wasi:logging/logging@0.1.0-draft`: logs an invalid config
- `wasi:http/types@0.3.0`: the requests being sent
- `wasi:http/client@0.3.0`: the client the authorization injector wraps

Exports:

- `wasi:http/client@0.3.0`: client that adds the configured authorization
137 changes: 137 additions & 0 deletions components/authorization-injector-core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
mod rules;

use crate::{
exports::wasi::http::client::{Guest, Request, Response},
rules::{MethodRules, Origin, Rules},
wasi::{
config::store,
http::{
client,
types::{ErrorCode, Scheme},
},
logging::logging::{Level, log},
},
};

const COMPONENT_NAME: &str = "authorization-injector-core";

const LOG_CONTEXT: &str = "componentized-authorization-injector";

const AUTHORIZATION: &str = "authorization";

struct AuthorizationInjector {}

impl Guest for AuthorizationInjector {
#[doc = "/ This function may be used to either send an outgoing request over the"]
#[doc = "/ network or to forward it to another component."]
#[allow(async_fn_in_trait)]
async fn send(request: Request) -> Result<Response, ErrorCode> {
match authorization(&request)? {
Some(authorization) => client::send(with_authorization(request, &authorization)?).await,
None => client::send(request).await,
}
}
}

/// The authorization to add to the request, `None` when the request already has an authorization
/// header, its method is not allowed, or none is configured for its origin.
fn authorization(request: &Request) -> Result<Option<String>, ErrorCode> {
if request.get_headers().has(AUTHORIZATION) {
return Ok(None);
}
let methods = load_config(
"methods",
methods::get_all().map_err(|err| match err {
methods::Error::Upstream(message) => format!("ERROR=upstream: {message}"),
methods::Error::Io(message) => format!("ERROR=io: {message}"),
}),
MethodRules::parse,
)?;
let method = http_utils::format_http_method!(wasi::http::types::Method, request.get_method());
if !methods.allows(&method) {
return Ok(None);
}
let rules = load_config(
"credentials",
store::get_all().map_err(|err| match err {
store::Error::Upstream(message) => format!("ERROR=upstream: {message}"),
store::Error::Io(message) => format!("ERROR=io: {message}"),
}),
Rules::parse,
)?;
let (Some(scheme), Some(authority)) = (request.get_scheme(), request.get_authority()) else {
return Ok(None);
};
let scheme = http_utils::format_http_scheme!(Scheme, &scheme);
Ok(Origin::new(&scheme, &authority)
.and_then(|origin| rules.authorization(&origin).map(str::to_string)))
}

/// Parse the entries of a config, `credentials` for `wasi:config/store` or `methods` for the
/// `methods` import. An invalid config fails every request, so a typo is noticed rather than
/// ignored.
fn load_config<T>(
config: &str,
entries: Result<Vec<(String, String)>, String>,
parse: impl FnOnce(Vec<(String, String)>) -> Result<T, String>,
) -> Result<T, ErrorCode> {
entries.and_then(parse).map_err(|message| {
log(
Level::Critical,
LOG_CONTEXT,
&format!("Invalid config COMPONENT={COMPONENT_NAME} CONFIG={config} {message}"),
);
ErrorCode::InternalError(Some(format!("invalid-config<{COMPONENT_NAME}>")))
})
}

/// The request with the authorization header added.
///
/// The headers of a request are immutable, so a new request is made with a copy of the headers,
/// the same method, target and options, and the body and trailers of the original request. The
/// result of transmitting the new request is forwarded to the original request.
fn with_authorization(request: Request, authorization: &str) -> Result<Request, ErrorCode> {
let headers = request.get_headers().clone();
headers
.set(AUTHORIZATION, &[authorization.as_bytes().to_vec()])
.map_err(|err| internal_error(format!("failed to set the authorization header: {err:?}")))?;
// a child of the request, dropped before the request is consumed
let options = request.get_options().map(|options| options.clone());
let method = request.get_method();
let scheme = request.get_scheme();
let authority = request.get_authority();
let path_with_query = request.get_path_with_query();

let (res_tx, res_rx) = wit_future::new(|| Ok(()));
let (contents, trailers) = Request::consume_body(request, res_rx);
let (request, transmitted) = Request::new(headers, Some(contents), trailers, options);
wit_bindgen::spawn_local(async move {
let _ = res_tx.write(transmitted.await).await;
});

let invalid = |part: &str| internal_error(format!("failed to copy the request {part}"));
request.set_method(&method).map_err(|()| invalid("method"))?;
request
.set_scheme(scheme.as_ref())
.map_err(|()| invalid("scheme"))?;
request
.set_authority(authority.as_deref())
.map_err(|()| invalid("authority"))?;
request
.set_path_with_query(path_with_query.as_deref())
.map_err(|()| invalid("path with query"))?;
Ok(request)
}

fn internal_error(message: String) -> ErrorCode {
log(Level::Error, LOG_CONTEXT, &message);
ErrorCode::InternalError(Some(message))
}

wit_bindgen::generate!({
path: "../wit",
world: "authorization-injector",
generate_all
});

export!(AuthorizationInjector);
Loading
Loading