权限名称存在,理由也写了一个资源引用,检查是否就能通过?把资源名改成不存在的值,就能构造一个很小却有区分度的实验:JSON5仍然可解析,权限声明仍然存在,真正断开的却是声明与说明文字之间的关系。发布配置审计这一节通过受控用例,检查权限、基础资源和使用组件是否对得上。

权限理由与场景审计封面

一、实验先限定输入范围

沿用上一节的audit.mjs、release-policy.json与AuditIssue协议,Node开发机运行,JSON5依赖仍固定为2.2.3。应用包名、模块名、版本及设备规则继续执行。本节增加entry模块的requestPermissions和基础string.json,不启动应用,也不申请设备权限。检查目标是源码声明关系,不是运行时授权状态。

官方声明权限指南指出,user_grant与manual_settings权限需要填写理由与使用场景;理由采用字符串资源引用,并需要多语种适配。这里先覆盖基础资源解析以及usedScene中的组件名称与时机,语言目录、资源合并和不同产品配置留给后续扩展。这个范围决定了实验结论不能扩大成完整的上架合规结论。

权限类型不能靠名称猜测。项目基线新增permissionChecks数组,记录已经根据目标SDK资料核对过的权限与是否需要理由。它是项目审查口径,不是平台权限全集。源码新增一个基线中没有的权限时,报告需要补充审查口径;这不等于断言该权限不存在,更不会自动把它当成无需说明的类型。

以直接使用相机能力的声明作为实验对象,基础资源保存一条拍摄用途文案。示例只关注声明结构,不实现相机功能;如果业务使用系统CameraPicker,应另外核对其免申请相机权限的接入路径,不能为了通过审计就增加业务并不需要的权限。

二、先建立能通过的对照组

工程根目录的release-policy.json更新为下面内容。原版本和设备目标不变,新增字段明确声明哪些权限需要理由检查。基线错误属于输入错误,返回2,不让一个缺失的口径文件悄悄变成“无权限问题”。

{
  "versionCode": 1000200,
  "versionName": "1.2.0",
  "deviceTypes": ["phone", "tablet"],
  "permissionChecks": [
    { "name": "ohos.permission.CAMERA", "requiresReason": true },
    { "name": "ohos.permission.INTERNET", "requiresReason": false }
  ]
}

在现有module节点中加入以下requestPermissions,并保证同一模块声明了EntryAbility。保留工程其他必需配置。这份相机声明用于测试理由与组件关系,不能代替实际能力调用前的权限检查与用户授权流程。

{
  "requestPermissions": [{
    "name": "ohos.permission.CAMERA",
    "reason": "$string:camera_reason",
    "usedScene": { "abilities": ["EntryAbility"], "when": "inuse" }
  }]
}

在entry/src/main/resources/base/element/string.json的string数组中补入对应资源,名称和引用严格匹配。把中文文字直接写进reason字段并不是同一种配置方式,审计会把它视为引用格式不符。

{ "string": [{ "name": "camera_reason", "value": "用于应用内自定义相机取景拍摄" }] }

对照组需要同时满足三条关系:权限在已审查基线中,理由引用能找到非空基础文本,usedScene列出的组件在当前模块声明中存在。组件集合同时读取abilities与extensionAbilities,调用时机只接受inuse或always。这里不从组件名称推断它是否真的调用了相机,那需要代码与业务路径证据。

权限声明与资源关系的实验对照

三、同一入口增加关系检查

下面完整代码替换tools/release-audit/audit.mjs。安装与执行方式不变:在该工具目录使用npm安装json5 2.2.3,再执行node audit.mjs ../..。新增基础string.json是显式输入,缺失文件或非法资源结构会进入input_error;权限条目能读出但关系不符则返回具体AuditIssue。

import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import JSON5 from 'json5';

/** @typedef {{ruleId:string,path:string,message:string,severity:'error'|'warning'}} AuditIssue */
/** @typedef {{versionCode:number,versionName:string,deviceTypes:readonly string[],permissionChecks:ReadonlyArray<{name:string,requiresReason:boolean}>}} ReleasePolicy */
/** @typedef {{bundleName:unknown,moduleName:unknown,versionCode:unknown,versionName:unknown,deviceTypes:unknown,policy:ReleasePolicy,permissions:unknown,reasons:Map<string,unknown>,declaredAbilities:string[]}} AuditSnapshot */
/** @typedef {(snapshot:AuditSnapshot)=>AuditIssue[]} AuditRule */

function objectNode(value, label) {
  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
    throw new Error(label + '应为对象');
  }
  return value;
}

function readDocument(root, relative) {
  const text = readFileSync(resolve(root, relative), 'utf8');
  return objectNode(JSON5.parse(text), relative);
}

function readSection(root, relative, section) {
  return objectNode(readDocument(root, relative)[section], relative + ':' + section);
}

function textValue(value) {
  return typeof value === 'string' && value.trim() !== '';
}

function codeValue(value) {
  return typeof value === 'number' && Number.isInteger(value) && value > 0 && value < 2147483648;
}

function deviceList(value) {
  return Array.isArray(value) && value.length > 0 &&
    value.every(item => textValue(item) && item === item.trim()) &&
    new Set(value).size === value.length;
}

function readPolicy(root) {
  const p = readDocument(root, 'release-policy.json');
  if (!codeValue(p.versionCode) || !textValue(p.versionName) || !deviceList(p.deviceTypes)) {
    throw new Error('release-policy.json的版本或设备基线格式错误');
  }
  const permissionChecks = p.permissionChecks;
  if (!Array.isArray(permissionChecks) || permissionChecks.some(item =>
    !item || typeof item !== 'object' || !textValue(item.name) || typeof item.requiresReason !== 'boolean') ||
    new Set(permissionChecks.map(item => item.name)).size !== permissionChecks.length) {
    throw new Error('permissionChecks应为无重复的权限审查口径数组');
  }
  return Object.freeze({ permissionChecks: Object.freeze(permissionChecks.map(item =>
    Object.freeze({ name: item.name, requiresReason: item.requiresReason }))),
    versionCode: p.versionCode, versionName: p.versionName,
    deviceTypes: Object.freeze([...p.deviceTypes]) });
}

function readSnapshot(root) {
  const app = readSection(root, 'AppScope/app.json5', 'app');
  const mod = readSection(root, 'entry/src/main/module.json5', 'module');
  const policy = readPolicy(root);
  const strings = readDocument(root, 'entry/src/main/resources/base/element/string.json');
  if (!Array.isArray(strings.string)) throw new Error('string.json:string应为数组');
  const reasons = new Map();
  for (const entry of strings.string) {
    if (!entry || !textValue(entry.name) || reasons.has(entry.name)) {
      throw new Error('string资源名称缺失或重复');
    }
    reasons.set(entry.name, entry.value);
  }
  const declaredAbilities = [...(Array.isArray(mod.abilities) ? mod.abilities : []),
    ...(Array.isArray(mod.extensionAbilities) ? mod.extensionAbilities : [])]
    .filter(item => item && textValue(item.name)).map(item => item.name);
  return Object.freeze({ bundleName: app.bundleName, moduleName: mod.name,
    versionCode: app.versionCode, versionName: app.versionName,
    deviceTypes: Array.isArray(mod.deviceTypes) ? Object.freeze([...mod.deviceTypes]) : mod.deviceTypes,
    policy, permissions: mod.requestPermissions === undefined ? [] : mod.requestPermissions,
    reasons, declaredAbilities });
}

function issue(ruleId, path, message) {
  return { ruleId, path, message, severity: 'error' };
}

/** @type {AuditRule} */
function checkBundleName(s) {
  return textValue(s.bundleName) ? [] : [issue('identity.bundle',
    'AppScope/app.json5:app.bundleName', '应用包名应为非空字符串')];
}

/** @type {AuditRule} */
function checkModuleName(s) {
  return textValue(s.moduleName) ? [] : [issue('identity.module',
    'entry/src/main/module.json5:module.name', '模块名应为非空字符串')];
}

/** @type {AuditRule} */
function checkVersion(s) {
  const issues = [];
  if (!codeValue(s.versionCode) || s.versionCode !== s.policy.versionCode) {
    issues.push(issue('release.versionCode', 'AppScope/app.json5:app.versionCode',
      'versionCode应与发布基线一致:' + s.policy.versionCode));
  }
  if (!textValue(s.versionName) || s.versionName !== s.policy.versionName) {
    issues.push(issue('release.versionName', 'AppScope/app.json5:app.versionName',
      'versionName应与发布基线一致:' + s.policy.versionName));
  }
  return issues;
}

/** @type {AuditRule} */
function checkDevices(s) {
  const path = 'entry/src/main/module.json5:module.deviceTypes';
  if (!deviceList(s.deviceTypes)) {
    return [issue('release.devices.format', path, '设备列表应为非空、无重复且无首尾空白的字符串数组')];
  }
  const actual = new Set(s.deviceTypes);
  const expected = new Set(s.policy.deviceTypes);
  const missing = [...expected].filter(item => !actual.has(item)).sort();
  const extra = [...actual].filter(item => !expected.has(item)).sort();
  return missing.length || extra.length ? [issue('release.devices.set', path,
    '缺少设备:' + JSON.stringify(missing) + ';额外设备:' + JSON.stringify(extra))] : [];
}


/** @type {AuditRule} */
function checkPermissions(s) {
  const path = 'entry/src/main/module.json5:module.requestPermissions';
  if (!Array.isArray(s.permissions)) return [issue('permission.array', path, '权限声明应为数组')];
  const issues = [];
  const seen = new Set();
  for (const [index, permission] of s.permissions.entries()) {
    const at = path + '[' + index + ']';
    if (!permission || typeof permission !== 'object' || !textValue(permission.name)) {
      issues.push(issue('permission.name', at, '权限名称缺失')); continue;
    }
    if (seen.has(permission.name)) issues.push(issue('permission.duplicate', at, '权限重复声明'));
    seen.add(permission.name);
    const rule = s.policy.permissionChecks.find(item => item.name === permission.name);
    if (!rule) { issues.push(issue('permission.policy', at, '缺少该权限的项目审查口径')); continue; }
    if (!rule.requiresReason) continue;
    const match = typeof permission.reason === 'string' ? /^\$string:([A-Za-z_][A-Za-z0-9_]*)$/.exec(permission.reason) : null;
    if (!match || !textValue(s.reasons.get(match[1]))) {
      issues.push(issue('permission.reason', at + '.reason', '理由引用缺失或基础资源文本为空'));
    }
    const scene = permission.usedScene;
    if (!scene || !Array.isArray(scene.abilities) || scene.abilities.length === 0 ||
      scene.abilities.some(name => !s.declaredAbilities.includes(name)) ||
      !['inuse', 'always'].includes(scene.when)) {
      issues.push(issue('permission.scene', at + '.usedScene', '使用组件或调用时机不符合约定'));
    }
  }
  return issues;
}

function main() {
  try {
    if (process.argv.length !== 3) throw new Error('用法:node audit.mjs <工程根目录>');
    const snapshot = readSnapshot(resolve(process.argv[2]));
    /** @type {AuditRule[]} */
    const rules = [checkBundleName, checkModuleName, checkVersion, checkDevices, checkPermissions];
    const issues = rules.flatMap(rule => rule(snapshot));
    issues.sort((a, b) => {
      const left = a.path + ':' + a.ruleId;
      const right = b.path + ':' + b.ruleId;
      return left < right ? -1 : left > right ? 1 : 0;
    });
    console.log(JSON.stringify({ status: 'audited', issues }, null, 2));
    process.exitCode = issues.some(item => item.severity === 'error') ? 1 : 0;
  } catch (error) {
    const message = error instanceof Error ? error.message : '未知输入错误';
    console.log(JSON.stringify({ status: 'input_error', message, issues: [] }, null, 2));
    process.exitCode = 2;
  }
}

main();

读取层准备资源Map和组件集合,规则层只消费快照,不在循环里反复读文件。问题路径保留权限数组下标,再附上reason或usedScene,便于定位。稳定排序仍由入口统一处理,没有为权限检查单独创造一套报告格式。

规则先检查条目形状,再按名称找到审查口径。需要理由的权限才执行理由与场景检查;无需理由的权限不会因缺少reason被误报。这个条件来自基线,因此基线变更也必须评审。把requiresReason随手改成false只是在修改检查依据,不是在修复应用声明。

资源正则采用本工具约定的简单名称子集。真实项目若采用更复杂的资源命名,应对照目标SDK扩展解析与用例,不应在检查失败时直接跳过资源解析。基础文案通过非空检查,也不说明文案已准确描述全部用途,语义审查仍需要业务人员确认。

四、一次只改变一个条件

在Node.js v24.22.1与json5 2.2.3下执行配置夹具,先让对照组返回0,再只改变一个字段。把camera_reason改成missing,得到permission.reason;把EntryAbility改成未声明的GhostAbility,得到permission.scene;保留引用但把文本清空,同样得到理由问题。解析没有失败,规则出口应为1。

另设无需理由的网络权限条目,不提供reason与usedScene,项目规则返回0。这个用例专门防止把所有权限都强制套用同一要求。再删除基线中的permissionChecks,返回2,验证输入错误没有被混进普通权限差异。

这里比较的是用例结果与规则标识,不采集耗时、内存或通过率。样本数量很小,足以区分这些逻辑分支,却不能据此推断大型多模块工程的性能。需要性能研究时,应另外固定文件规模、运行环境与测量方法。

实际用例结果与预期出口核对

还应增加重复权限、非法数组、未知权限口径与重复资源名用例。重复资源名直接使输入失去明确解释,本实现停止审计而不是任取其中一条文案。多语言缺失则需要新的输入目录和规则,不能从基础中文存在推出其他语言已经适配。

五、从结构关系走向发布门禁

实验还应防止多个变量同时变化。若同时删除理由资源、修改组件名并调整基线,得到两条错误并不能说明每个分支都有效。每次从对照组复制输入,只改变一个条件,再记录规则标识与退出码,才能把差异归因到具体规则。修复后还要重新跑对照组,确认规则没有因处理异常而破坏原本合法的输入。

静态规则也无法判断理由文案是否足够具体。“用于提供更好的体验”即使不是空字符串,也未必能解释敏感能力的用途。本实现只检查文本存在,后续可以增加项目文案规范,但不能用字符串长度阈值代替人工业务审查。敏感权限的必要性需要沿真实功能入口追溯。

资源解析还存在配置限定条件。基础资源中的名称可能在其他语言或设备目录里有不同内容,最终选择取决于资源匹配机制。本节没有遍历这些目录,因此报告应保留“基础资源”这一准确范围。继续扩展时,需要显式列出目标语言与输入目录,而不是碰到任意一个同名字符串就认为所有语言都齐全。

权限声明重复与权限跨模块生效也要分开理解。当前重复检查只针对同一个数组中的相同名称,防止本模块配置出现重复条目;它不把其他HAP中的相同声明直接判为本数组重复。把模块内去重和应用范围一致性分成两类规则,后续报告才不会让开发者删除本来需要保留的配置。

当前只读entry源码,不能代表全部HAP。官方指南说明多HAP权限生效与理由一致性有对应要求,扩展时应按应用范围汇总声明并核对用途,不要在每个模块机械复制相同条目。构建钩子可能修改有效配置,最终检查位置仍需结合工程构建链确定。

这次实验验证了三个可观察边界:引用必须能解析,场景必须能定位,基线必须可解释。它没有证明用户已授权,也没有证明功能一定需要该权限。最后一节把这些稳定规则接入发布门禁,并处理规则组织与失败报告,让检查结果真正影响后续流程。

参考资料:声明权限、权限组与相机权限、网络能力权限声明示例、CameraPicker。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐