Interceptors
An interceptor is the part of an extension that changes a call Alien's controllers make to a cloud or to Kubernetes, and its response. It reaches what a setup template doesn't create: live resources.
This one turns on IAM authentication for every RDS cluster Alien creates or modifies:
use alien_extension_sdk::prelude::*;
pub struct Rds;
impl AwsInterceptor for Rds {
/// The calls this interceptor sees.
fn matches(&self, call: &AwsCall) -> bool {
call.service() == "rds"
&& matches!(call.operation(), "CreateDBCluster" | "ModifyDBCluster")
}
/// Runs before Alien signs the request.
fn modify_request(&self, request: &mut AwsRequest) -> Result<()> {
request.set("EnableIAMDatabaseAuthentication", true);
Ok(())
}
/// Runs when the response arrives, before Alien reads it. Optional.
fn modify_response(&self, _response: &mut AwsResponse) -> Result<()> {
Ok(())
}
}Register it in your hooks crate, next to the extension's other hooks:
fn register(ext: &mut Extension) {
ext.aws_interceptor(postgres_iam_auth::Rds);
}Unit test
An interceptor is plain Rust code over a request, so a unit test builds a request and checks the result. The prelude brings json!:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_iam_auth() {
let mut request = AwsRequest::new("rds", "CreateDBCluster", json!({ "DBClusterIdentifier": "db" }));
Rds.modify_request(&mut request).unwrap();
assert_eq!(request.param("EnableIAMDatabaseAuthentication"), Some("true"));
}
}alien extensions test runs it natively and again inside the WebAssembly module Alien loads. Testing covers the rest.
Processes
An interceptor runs inside whichever Alien process runs the deployment's controllers:
- the Alien manager, in a push deployment
- the Operator, in a pull deployment
The setup CLI doesn't run interceptors. It signs Alien's calls with the admin's own credentials, which reach beyond the deployment, so it refuses a release whose extensions ship interceptors, naming them. Set such a deployment up from its setup template, or let the Alien manager or the Operator set it up. Deleting a deployment with the setup CLI still works, without the interceptors.
alien dev runs your stack on local stand-ins and makes no cloud calls, so interceptors don't run there.
Each deployment gets only its own extensions' interceptors. Every call runs in a fresh sandbox, with no network, no files, and no state kept from the call before.
One trait per cloud
Each cloud has its own trait, and every trait has the same methods:
| Trait | Register with | matches gets |
|---|---|---|
AwsInterceptor | ext.aws_interceptor | The service and the operation, such as rds and CreateDBCluster |
GcpInterceptor | ext.gcp_interceptor | Alien's service key and the route, such as cloudsql and POST projects/*/instances |
AzureInterceptor | ext.azure_interceptor | The resource provider, the resource type, and the HTTP method, such as Microsoft.DBforPostgreSQL, flexibleServers, and PUT |
KubernetesInterceptor | ext.kubernetes_interceptor | The object's kind and the verb, such as Pod and create |
modify_request changes the request, and modify_response is optional:
pub trait GcpInterceptor {
fn matches(&self, call: &GcpCall) -> bool;
fn modify_request(&self, request: &mut GcpRequest) -> Result<()>;
fn modify_response(&self, _response: &mut GcpResponse) -> Result<()> { Ok(()) }
}
pub trait AzureInterceptor {
fn matches(&self, call: &AzureCall) -> bool;
fn modify_request(&self, request: &mut AzureRequest) -> Result<()>;
fn modify_response(&self, _response: &mut AzureResponse) -> Result<()> { Ok(()) }
}
pub trait KubernetesInterceptor {
fn matches(&self, call: &KubernetesCall) -> bool;
/// The request is the object Alien sends, such as a pod.
fn modify_request(&self, object: &mut KubernetesObject) -> Result<()>;
fn modify_response(&self, _object: &mut KubernetesObject) -> Result<()> { Ok(()) }
}A KubernetesInterceptor reaches objects the Operator creates, and may only add labels to them, such as a team label on every object. The Operator's calls reach what every deployment on the cluster shares, ingress hosts, runtime classes and nodes among them, so any other change to a Kubernetes request, and any change to its response, fails the call. A label may not have a prefix (such as alien.dev/ or kubernetes.io/) or be managed-by, and the labels Alien set stay as they were: Alien and the cluster select objects by them.
The request
Your interceptor gets the request in the form the API receives it, through a typed view for each kind of API:
| API | Examples | What you edit |
|---|---|---|
| AWS query APIs | RDS, EC2, SQS | Flat form keys, such as Tags.Tag.1.Key, with AwsRequest::param, set, and remove. The Action key names the operation |
| AWS JSON APIs | DynamoDB, KMS, ECR, Secrets Manager | The JSON body. set sets a top-level field, and body_mut() reaches nested ones |
| AWS REST APIs | Lambda, S3, EKS, API Gateway | The values of the query's parameters, and the body |
| Google Cloud | Cloud SQL and every other service | The query and JSON body |
| Azure Resource Manager | Flexible Server and every other provider | The api-version and JSON body |
| Kubernetes | Pods, service accounts | Labels added to the object's metadata.labels, as a KubernetesObject |
set("EnableIAMDatabaseAuthentication", true) works on query and JSON APIs alike. On RDS it becomes the form value true.
Responses come the same way. On AWS query APIs and S3 the response is XML, which AwsResponse reads and changes with its XML helpers. Everywhere else it's JSON, and on Kubernetes it's the object the API returns.
Interceptors see text bodies only. Binary bodies include an S3 object upload, a Lambda invocation, and a Cloud Storage upload. If your interceptor would see a call like that, the call fails with an error that names your extension.
Allowed changes
An interceptor changes what a call says about the deployment's own resources:
- parameters, body fields, headers other than those listed under Refused changes, and the query. On AWS that's the value of a query parameter the call already has
- the response, including 4xx and 5xx error responses, so
modify_responsecan turn a cloud error into a success
On Kubernetes an interceptor may only add labels to the object, and may not change the response.
After your change, Alien recomputes the body's digest and length headers, so the request still signs correctly.
Refused changes
An interceptor can't change where the call goes, which operation it runs, who it acts as, or how it's signed:
- the scheme, host, and port, and the cloud and service the call is signed for
- the HTTP method and the path
- the operation, such as the
Actionkey on a query API or theX-Amz-Targetheader - the identities the call names: a service account, a role, a managed identity, or a pod's service account
- a container image in a cloud registry (Amazon ECR, Artifact Registry and Container Registry on Google Cloud, including any image on
gcr.io, or Azure Container Registry): an interceptor can't add one or change one the call names. An image from a public registry, such as a sidecar from Docker Hub or GitHub Container Registry, is fine - the signing headers (
Host,Authorization,X-Amz-Date,X-Amz-Security-Token, andProxy-Authorization), andX-Amz-Copy-Source, which picks the object an S3 copy reads - the headers that pick the method or how the body is read (
Content-Type,X-HTTP-Method-Override,X-HTTP-Method), the project billed or an API key on Google Cloud (X-Goog-User-Project,X-Goog-Api-Key), Azure'sX-Ms-Authorization-Auxiliary, and Kubernetes'Impersonate-*headers - on AWS, which query parameters the call has: a parameter such as S3's
?loggingor API Gateway's?mode=importis the operation - on Google Cloud, the query parameters that pick the project billed, a credential, or the body's or response's format:
userProject,key,access_token,oauth_token,bearer_token,alt, and any system parameter written with$, such as$ct - the body's format: a JSON body stays JSON, a body that isn't JSON doesn't become JSON, and a call Alien sends without a body doesn't get one
It also can't turn a call into a policy or IAM call: by its path, query or operation, and on AWS by a Policy or ResourcePolicy field in the body or the query, an API Gateway policy, or an S3 ACL header. It can't make storage or a network public, or touch any setting that decides who can reach a resource, on any cloud and whatever the value:
- adding, removing, or changing a public access, network rule, firewall, source range, ingress, ACL, or access policy field, such as
PubliclyAccessible,publicNetworkAccess,networkAcls,sourceRanges,authorizedNetworks,accessPolicies, or an S3 public access block - opening a resource to the internet that the call Alien built didn't open: a source of
0.0.0.0/0,::/0,*,Internet, orAny,allUsersorallAuthenticatedUserson Google Cloud, or a public access protection turned off
A call Alien itself builds with one of these, such as a container Alien makes public on purpose, keeps it. A change to any of the settings above fails the call, and nothing is sent.
Alien never offers an interceptor its IAM calls, role assignments and managed identities, its policy reads and writes, Kubernetes Secrets and service account tokens, or calls that create resources of any type or carry other requests, such as CloudFormation, ARM deployments or batch calls. Your interceptor doesn't see them, even one that matches every call. Every call still goes to the cloud's own API, so an interceptor can't point Alien's requests at another host.
An interceptor never sees the credentials Alien signs with. The request it gets has no Authorization header and no token.
It does see the bodies of the calls it matches, and of their responses, and some carry secrets, such as a database password Alien sets, a secret value it writes, or a storage account's access keys. Installing an extension with interceptors trusts it with what the calls it matches carry. It runs with no network, a change it makes can't send a call to another host, cloud or service, and Alien keeps an interceptor's error text out of the deployment's errors. It can still change a call's query and body, which Alien signs and sends, so review an interceptor's code like any code that handles your customer's data.
On Azure, Alien follows URLs a response names, such as an operation's status URL or the next page of a list. A client with interceptors signs only for its own endpoint. If a response is rewritten to point one of those URLs at another host, the next call fails and that host never gets the token.
Calls it sees
An interceptor runs on every call it matches, including refreshes, updates, and deletes. It acts only on calls Alien already makes. Alien doesn't send a call because your extension changed.
Existing resources
A setting you add to an interceptor reaches an existing resource the next time Alien sends that resource a matching call. Alien doesn't notice if someone removes the setting by hand.
How soon that happens depends on the resource. For a live Postgres, Alien sends its update call only for these changes:
| Cloud | Update call | When Alien sends it |
|---|---|---|
| AWS | ModifyDBCluster | It adopts an existing cluster, or changes its capacity |
| Google Cloud | instances.patch | The tier, high availability, or disk changes |
| Azure | Server PATCH | The SKU, storage, or high availability changes |
A release that changes nothing on that list sends no update call, so it carries no setting. A database a setup template creates never gets a matching call. It needs a template modifier, applied when the admin reruns initial setup.
If Alien sends a field on an update call too, match that call as well, or the update puts Alien's value back. Alien sends CopyTagsToSnapshot=true on every ModifyDBCluster, for example.
During an update
While a deployment moves to a new release, the new release's interceptors apply to every create and update. Deleting a resource the new release removes uses the current release's interceptors.
Failures
An interceptor fails when it returns an error, panics, or goes over a limit:
| Limit | Value |
|---|---|
| Time per call | 100 ms |
| Memory | 64 MiB |
| Output | 16 MiB |
A failing modify_request stops the call before anything is sent. A failing modify_response fails the call after the response arrives, before Alien reads it. Either way, the resource fails with an error that names the extension, and the deployment shows it like any other resource failure.
A failed modify_response is final, since the cloud already acted on the call, and Alien never sends that call again. A failed matches or modify_request stops the step, and the step is tried again only when the hook was stopped at its time limit or its error says another try may pass; any other failure would fail the same way.
The resource's error names the extension, the hook and its error code, never the hook's own message: the hook saw the call's request and response.
What isn't intercepted
- Calls to Azure Key Vault, Service Bus, and Table Storage. On Azure, interceptors see Azure Resource Manager calls only.
- Reads Alien makes outside its controllers, such as the preflight checks that decide whether a deployment can start, and quota and environment lookups.
- Calls your application makes at runtime, and the calls Alien makes to get credentials.
Several extensions
Interceptors run in the order your stack lists extensions in .extensions([...]). Each one gets the request as the previous one left it, so a later extension can change a value an earlier one set.
Next
- Template modifiers: the same setting for resources initial setup creates
- Testing: test interceptors natively and in the module Alien loads
- Your own tags: an interceptor that tags the resources Alien's controllers create