Cloud Custodian 实战:用 OCI `api-keys` 过滤器统计并治理 IAM 用户 API 密钥数量

原创2026-10-11 11:19:491,726 阅读
文章标签:云原生运维安全

Cloud Custodian 实战:用 OCI api-keys 过滤器统计并治理 IAM 用户 API 密钥数量

本篇技术指南以 docs/source/oci/examples/user_apikeycount_identity.rst 中的官方示例为主线,讲解如何在 Cloud Custodian 中针对 Oracle Cloud Infrastructure(OCI)的 IAM 用户编写策略:通过 api-keys 过滤器筛选出 API 密钥数量超过阈值的用户,并用 update 动作为其打上 freeform 标签。读完本文,你将掌握 OCI Identity 域下用户资源过滤器的完整用法、value_type: size 的底层求值机制,以及如何结合仓库源码与测试用例验证策略行为。

场景背景:为什么要统计用户的 API 密钥数量

在 OCI 的身份体系中,每个 IAM 用户都可以持有多个 API 密钥(API Key,即用于调用 OCI SDK/CLI 的密钥对)。从安全治理角度看,单个用户持有过多、过老的 API 密钥意味着更大的凭据泄露面与更复杂的轮换成本。Cloud Custodian 的 OCI Provider 在 oci.user 资源上提供了 api-keys 过滤器,可以直接把「查询用户」与「统计其名下 API 密钥数量」合并到一条 YAML 策略中,命中后还能自动打标签、发通知或执行后续治理动作。

该过滤器与 OCI Provider 中其余 Identity 凭据过滤器(auth-tokens、smtp-credentials、customer-secret-keys、db-credentials、o-auth2-client-credentials)共用同一套实现模式,本文以 api-keys 为切入点,其原理可推广到全部凭据类型。

官方示例策略:过滤并标记 API 密钥过多的用户

user_apikeycount_identity.rst 给出的完整策略如下:

policies:
- name: filter-tag-user-with-api-keys
  description: |
    Filter and tag users with more than 2 API keys
  resource: oci.user
  filters:
   - type: api-keys
     key: api_keys
     value_type: size
     op: greater-than
     value: 2
  actions:
   - type: update
     freeform_tags:
        TagName : TagValue

逐段拆解:

配置段 取值 含义
name filter-tag-user-with-api-keys 策略名,也是运行后输出目录名
description 策略说明 描述「过滤并标记 API 密钥数大于 2 的用户」
resource oci.user 目标资源类型为 OCI Identity 用户
filters[0].type api-keys 使用 UserApiKeysValueFilter 凭据过滤器
key api_keys 过滤器会把该用户的 API 密钥列表写入 api_keys 字段
value_type size 对列表求长度后再与 value 比较
op greater-than 比较运算符,等价于 gt,即「大于」
value 2 阈值:API 密钥数量超过 2 即命中
actions[0].type update 调用 OCI update_user 接口更新用户
freeform_tags TagName: TagValue 写入的自由格式标签键值对,实际使用时替换为真实标签名与值

参数详解:过滤器配置的取值与语义

op 支持的全部比较运算符

api-keys 继承自 Cloud Custodian 的 ValueFilter,其比较运算符定义在 c7n/filters/core.py 的 OPERATORS 表中,可按需选用:

  • 相等类:eq / equal、ne / not-equal
  • 大小类:gt / greater-than、ge / gte、lt / less-than、le / lte
  • 字符串类:glob、regex、regex-case
  • 集合类:in、ni / not-in、contains、difference、intersect
  • 其他:mod

value_type 支持的类型

VALUE_TYPES 定义于 c7n/filters/core.py,与 OCI 凭据过滤器相关的常用类型:

value_type 行为 典型用途
size 对目标值调用 len() 后比较(core.py#L802-L806) 统计凭据数量
unique_size 对目标集合去重后求长度 统计去重后的数量
age 以「当前时间 - value 天数」为基准反向比较日期字段 筛选创建时间超过 N 天的密钥
date 双方按日期解析后比较 按绝对日期过滤
integer / float 数值类型转换 数值字段比较
normalize 字符串去首尾空白并转小写 规范化比较

本文示例使用的 value_type: size 在 process_value_type 中实现为:把 api_keys 列表的长度作为实际比较值,再交给 op 与 value: 2 比较,因此 greater-than 命中的是「密钥数 ≥ 3」的用户(严格大于 2)。

源码级原理:UserApiKeysValueFilter 的执行路径

api-keys 过滤器注册在 tools/c7n_oci/c7n_oci/resources/identity.py,类名为 UserApiKeysValueFilter,注册代码为:

@User.filter_registry.register("api-keys")
class UserApiKeysValueFilter(ValueFilter):
    schema = type_schema("api-keys", rinherit=ValueFilter.schema)

    def process(self, resources, event):
        if "value_type" in self.data and self.data["value_type"] == "size":
            ...
        else:
            ...

其 process 方法存在两条分支,理解这一点对正确书写策略至关重要:

分支一:value_type: size(本文示例路径)

遍历每个用户资源:

  1. 若资源中已带有 api_keys 字段(例如上层查询已注入),直接复用,避免重复调用 API;
  2. 否则调用 OCI IdentityClient 的 list_api_keys(user_id=...) 拉取该用户全部 API 密钥;
  3. 用 oci.util.to_dict(api_keys) 把 SDK 响应序列化为字典列表,写入 res["api_keys"];
  4. 最后交给 ValueFilter.process,在 value_type: size 下对列表求长度并与阈值比较。

对应源码片段(identity.py#L761-L778):

def process(self, resources, event):
    if "value_type" in self.data and self.data["value_type"] == "size":
        result = []
        for resource in resources:
            params_dict = {}
            params_dict["user_id"] = resource["id"]
            res = resource
            if "api_keys" in resource:
                result.append(resource)
            else:
                response = self.manager.get_client().list_api_keys(
                    user_id=params_dict["user_id"],
                )
                api_keys = response.data
                if api_keys:
                    res["api_keys"] = oci.util.to_dict(api_keys)
                    result.append(res)
        return super().process(result)

分支二:非 size 模式(逐密钥展开)

当不使用 value_type: size 时,过滤器会把每个用户的每个 API 密钥展开为一条记录,并将密钥对象写入单数字段 api_key,随后对 api_key.<属性> 进行值过滤。典型用法参见 docs/source/oci/examples/user_apikeyage_identity.rst 中的按密钥年龄过滤示例:

filters:
 - type: api-keys
   key: api_key.time_created
   op: greater-than
   value_type: age
   value: 365

这里 value_type: age 的底层实现位于 c7n/filters/core.py#L816-L826:将 value: 365 解释为「365 天前的时间点」,随后反向比较(返回值顺序为 value, sentinel),从而筛出创建时间早于一年前的密钥。key: api_key.lifecycle_state 配合 value: 'INACTIVE' 则可筛出已停用的密钥(详见 identity.py#L744-L756 的类文档示例)。

动作层:update 如何给用户打标签

命中过滤器后,策略执行 type: update 动作,对应 UpdateUserAction(identity.py#L285-L325)。其 schema 为:

schema = type_schema(
    "update", **{"freeform_tags": {"type": "object"}, "defined_tags": {"type": "object"}}
)

即同时支持 freeform_tags(自由格式标签)与 defined_tags(命名空间定义标签)。执行时,动作类通过 extract_params 剥离 type 键,再调用 update_params 把策略中声明的标签与用户现有标签合并(去重逻辑见 actions/base.py#L66-L91),最后构造 oci.identity.models.UpdateUserDetails 并调用 client.update_user(user_id=..., update_user_details=...)。

因此示例中的 freeform_tags: {TagName: TagValue} 会以「合并写入」的方式打到用户上,不会覆盖用户已有的其他标签。若需要移除标签,OCI Provider 还提供了 remove-tag 动作(RemoveTagActionUser,identity.py#L328-L372)。

组合用法:将数量阈值与其他条件叠加

api-keys 过滤器只是 filters 列表中的一项,可与 value、query 等过滤器自由组合,实现更精细的治理策略。例如先锁定指定 compartment 的用户,再按密钥数量筛选:

policies:
- name: flag-users-with-excess-api-keys
  description: |
    Tag users in the tenancy who hold more than 2 active API keys
  resource: oci.user
  query:
    - lifecycle_state: ACTIVE
  filters:
    - type: api-keys
      key: api_keys
      value_type: size
      op: greater-than
      value: 2
  actions:
    - type: update
      freeform_tags:
        api_key_governance: review

其中 query 段的 lifecycle_state: ACTIVE 会透传给 list_users 查询参数(查询透传逻辑见 tools/c7n_oci/c7n_oci/query.py#L97-L106)。同目录下还有按 auth-tokens、db-credentials、customer-secret-keys、smtp-credentials、o-auth2-client-credentials 数量统计的兄弟示例(如 user_authtokencount_identity.rst、user_smtpcredcount_identity.rst),写法与本文完全一致,只需替换 type 与 key 为对应凭据名即可。

环境准备与运行策略

安装 OCI Provider

OCI Provider 是 Cloud Custodian 的可选插件包(Beta),需在安装基础 c7n 之后单独安装,官方步骤见 docs/source/oci/gettingstarted.rst 与 tools/c7n_oci/readme.md:

pip install c7n
pip install c7n-oci

或从本仓库源码安装:

git clone https://gitcode.com/gh_mirrors/cl/cloud-custodian
pip install -e ./cloud-custodian
pip install -e ./cloud-custodian/tools/c7n_oci

配置认证

Cloud Custodian 会隐式读取本机的 OCI 凭证。最直接的方式是用 OCI CLI 初始化:

oci setup config

若在 OCI 实例内运行,可启用实例主体验证:

export OCI_CLI_AUTH=instance_principal

控制扫描范围

默认情况下,OCI Provider 会扫描 tenancy 下所有 compartment。可以通过 OCI_COMPARTMENTS 环境变量用逗号分隔的 compartment OCID 列表收窄范围:

export OCI_COMPARTMENTS=ocid1.compartment.oc1..<unique_ID>_1,ocid1.compartment.oc1..<unique_ID>_2

是否设置该变量还会影响资源发现方式:设置后走 describe-native 源(直接调用 list_*),未设置时走 describe-search 源(先用 ResourceSearchClient 发现 compartment 再拉取资源),二者逻辑见 query.py#L224-L229。

运行与输出

custodian run --output-dir=. custodian.yml

运行成功后,--output-dir 下会生成以策略名命名的目录(本例为 filter-tag-user-with-api-keys),内含运行日志与 resources.json(命中的用户资源清单)。日志中会依次出现认证成功、资源统计(policy:... resource:oci.user ... count:N)以及动作执行的 PUT:update_user 状态信息。

测试验证:仓库中如何验证该过滤器

api-keys 过滤器的行为在 tools/c7n_oci/tests/test_identity.py 中有三组针对性测试,均通过 mock list_api_keys 返回值来验证:

  • test_apikeys_size_identity(test_identity.py#L700-L717):模拟用户无内嵌 api_keys 字段,验证 value_type: size 路径下过滤器会调用 list_api_keys 并正确命中;
  • test_apikeys_exists_identity(test_identity.py#L719-L743):模拟资源已携带 api_keys 字段,验证短路复用逻辑;
  • test_apikeys_filter_identity(test_identity.py#L745-L761):验证非 size 模式下按 api_key.lifecycle_state 进行值过滤。

此外,tests/terraform/identity_user/tf_resources.json 展示了 Terraform 搭建的测试用户及其凭据数据(含 oci_identity_auth_token 与用户能力位 can_use_api_keys),可作为理解 oci.user 资源字段结构的参考。若本地具备 OCI 环境,还可运行 pytest- terraform 驱动的功能测试(如 test_identity_user_cross_filter_size)做端到端验证。

注意事项与最佳实践

  1. greater-than 是严格大于:value: 2 命中的是密钥数 ≥ 3 的用户;若想「恰好 2 个」应改用 op: eq,「至少 2 个」应改用 op: ge(或 gte)。
  2. 合理搭配 value_type:统计数量用 size,按创建时间治理用 age,两者可分别对应「密钥过多」与「密钥过老」两类治理场景,同目录下的 user_apikeyage_identity.rst 即后者的官方示例。
  3. 善用缓存与范围控制:describe-native 源会按 compartment 缓存资源(query.py#L54-L76),重复运行同一策略可减少 API 调用;生产环境务必通过 OCI_COMPARTMENTS 明确扫描边界。
  4. 标签命名建议:示例中的 TagName: TagValue 为占位符,实际应使用具备语义的键值(如 api_key_governance: review),方便后续配合 value 过滤器做二次审计或触发 remove-tag 治理闭环。
  5. 策略可验证:在提交前可使用 Cloud Custodian 的 validate 能力对 YAML 做 schema 校验,避免 op、value_type 取值非法导致运行期报错。
登录后查看全文
cloud-custodian