# Azure Functions

`azure-functions` 插件将由 HTTP 触发的 [Azure Function](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger) 作为路由实际使用的上游。它转发客户端的请求方法、请求头、查询参数和请求体，然后将函数的状态码、响应头和响应体返回给客户端。

该插件可以提供 Azure Functions 访问密钥，而不向调用方暴露密钥。一条路由调用一个函数时，请使用该函数专用的密钥，并通过适当的客户端身份认证和授权保护路由。

## 示例[​](#examples "示例的直接链接")

以下示例展示如何调用受密钥保护的 HTTP 触发器，以及如何在调用函数时保留路由匹配的子路径。

配置网关之前，请先准备一个由 HTTP 触发的函数：

1. 按照 Microsoft 的 [HTTP 端点指南](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-http-endpoint)创建 Function App，以及名为 `HttpExample` 的 HTTP 触发器。如果门户不支持编辑所选运行时，请在本地开发函数并发布到 Function App。
2. 将触发器的授权级别设为 **函数**，而不是 **匿名**。
3. 实现函数，使其读取 `name` 查询参数并返回 `Hello, <name>!`，以便示例产生可预期的结果。
4. 在函数的 **函数密钥** 页面中复制该函数专用的密钥。避免使用 host 密钥和 master 密钥，因为它们授予的访问权限超出了此函数的范围。
5. 选择 **获取函数 URL** 并复制 URL。移除 `?code=...` 查询参数，因为插件会通过 `x-functions-key` 请求头发送密钥。

导出函数端点、Function App 的 API 基础地址和密钥。将示例主机替换为复制的函数 URL 中的主机名：

```
export AZURE_FUNCTION_URI="https://your-function-host/api/HttpExample"

export AZURE_FUNCTION_BASE_URI="https://your-function-host/api"

export AZURE_FUNCTION_KEY="replace-with-function-key"
```

网关必须能够解析并访问函数主机名。如果 Function App 使用访问限制或私有网络，请允许每个网关实例的流量。

### 调用受密钥保护的函数[​](#invoke-a-key-protected-function "调用受密钥保护的函数的直接链接")

配置一条路由，调用 HTTP 触发器并添加该函数专用的访问密钥。

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes/azure-functions-route" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -H "Content-Type: application/json" \

  -d @- <<EOF

{

  "uri": "/azure",

  "plugins": {

    "azure-functions": {

      "function_uri": "${AZURE_FUNCTION_URI}",

      "authorization": {

        "apikey": "${AZURE_FUNCTION_KEY}"

      }

    }

  },

  "upstream": {

    "type": "roundrobin",

    "nodes": {

      "httpbin.org:80": 1

    }

  }

}

EOF
```

adc.yaml

```
services:

  - name: azure-functions-service

    labels:

      docs-example: azure-functions

    routes:

      - name: azure-functions-route

        uris:

          - /azure

        plugins:

          azure-functions:

            function_uri: "${AZURE_FUNCTION_URI}"

            authorization:

              apikey: "${AZURE_FUNCTION_KEY}"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览指定范围内的变更：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=azure-functions
```

检查 `diff.yaml`，然后同步带有该标签的服务：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=azure-functions
```

继续之前，请在 `aic` 命名空间中[设置 Ingress Controller 和网关](https://docs.apiseven.com/ingress-controller/set-up-ingress-controller-and-gateway.md)。无论使用哪份清单，都请替换其中的函数主机名和访问密钥。

* Gateway API
* APISIX CRD

azure-functions-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: azure-functions-route

spec:

  plugins:

    - name: azure-functions

      config:

        function_uri: https://your-function-host/api/HttpExample

        authorization:

          apikey: replace-with-function-key

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: azure-functions-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /azure

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: azure-functions-route

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

azure-functions-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v2

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: azure-functions-route

spec:

  ingressClassName: apisix

  plugins:

    - name: azure-functions

      enable: true

      config:

        function_uri: https://your-function-host/api/HttpExample

        authorization:

          apikey: replace-with-function-key

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: azure-functions-route

spec:

  ingressClassName: apisix

  http:

    - name: azure-functions-route

      match:

        paths:

          - /azure

      backends:

        - serviceName: httpbin-external-domain

          servicePort: 80

      plugin_config_name: azure-functions-route
```

应用配置：

```
kubectl apply -f azure-functions-ic.yaml
```

上述配置包含一个常规的备用后端。当 `azure-functions` 处理请求时，网关不会访问该后端；请验证 Azure Function 的响应，不要将后端响应视为插件已运行的证明。

发送包含姓名的请求：

```
curl --include "http://127.0.0.1:9080/azure?name=API7"
```

网关返回函数的响应：

```
HTTP/1.1 200 OK

...

Hello, API7!
```

### 保留路由匹配的子路径[​](#preserve-a-matched-route-sub-path "保留路由匹配的子路径的直接链接")

更新同一条路由，使其匹配子路径并使用 Function App 的 API 基础地址。插件会将 `*` 匹配的路径追加到配置的函数 URI。

* Admin API
* ADC
* Ingress Controller

更新路由路径：

```
curl "http://127.0.0.1:9180/apisix/admin/routes/azure-functions-route" -X PATCH \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -H "Content-Type: application/json" \

  -d '{"uri":"/azure/*"}'
```

替换插件配置，改用 Function App 的 API 基础地址：

```
curl "http://127.0.0.1:9180/apisix/admin/routes/azure-functions-route/plugins/azure-functions" -X PATCH \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -H "Content-Type: application/json" \

  -d @- <<EOF

{

  "function_uri": "${AZURE_FUNCTION_BASE_URI}",

  "authorization": {

    "apikey": "${AZURE_FUNCTION_KEY}"

  }

}

EOF
```

在 `adc.yaml` 中替换路由 URI 和插件配置：

adc.yaml（路由片段）

```
uris:

  - /azure/*

plugins:

  azure-functions:

    function_uri: "${AZURE_FUNCTION_BASE_URI}"

    authorization:

      apikey: "${AZURE_FUNCTION_KEY}"
```

预览更新后的服务：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=azure-functions
```

检查 `diff.yaml`，然后同步带有该标签的服务：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=azure-functions
```

使用部署所采用的 Kubernetes API 更新插件和路由：

* Gateway API
* APISIX CRD

azure-functions-ic.yaml

```
apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: azure-functions-route

spec:

  plugins:

    - name: azure-functions

      config:

        function_uri: https://your-function-host/api

        authorization:

          apikey: replace-with-function-key

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: azure-functions-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: PathPrefix

            value: /azure/

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: azure-functions-route

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

azure-functions-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: azure-functions-route

spec:

  ingressClassName: apisix

  plugins:

    - name: azure-functions

      enable: true

      config:

        function_uri: https://your-function-host/api

        authorization:

          apikey: replace-with-function-key

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: azure-functions-route

spec:

  ingressClassName: apisix

  http:

    - name: azure-functions-route

      match:

        paths:

          - /azure/*

      backends:

        - serviceName: httpbin-external-domain

          servicePort: 80

      plugin_config_name: azure-functions-route
```

应用更新后的配置：

```
kubectl apply -f azure-functions-ic.yaml
```

发送一个通过路径后缀指定函数的请求：

```
curl --include "http://127.0.0.1:9080/azure/HttpExample?name=API7"
```

插件将 `/HttpExample` 追加到 Function App 的 API 基础地址，并返回函数响应：

```
HTTP/1.1 200 OK

...

Hello, API7!
```

## 保护函数密钥[​](#protect-function-keys "保护函数密钥的直接链接")

Azure Functions 访问密钥是共享机密。对于调用单个函数的路由，请优先使用该函数专用的密钥。host 密钥授予对 Function App 中所有函数的访问权限，而 master 密钥还授予对运行时管理端点的访问权限。

插件优先使用插件实例上配置的凭据，其次使用插件元数据。元数据为未配置 `authorization` 的实例提供默认值。如果入站请求包含 `x-functions-key` 或 `x-functions-clientid` 中的任意一个请求头，插件既不会注入实例配置中的凭据，也不会注入元数据中的凭据，而是原样转发客户端提供的值。当网关负责函数身份认证时，不要允许不可信客户端提供这些请求头。

通过 Function App 轮换密钥，并更新所有存储旧值的插件实例或元数据条目。函数端点应使用 HTTPS；部署有相应要求时，请使用 Azure 网络限制或私有网络。
