蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

验证目录边界、配置优先级和参数传递

PYTHONWindows、Python 3.12。各实验所需工具和版本见下载包 README。bounded_run.py
bounded_run.py93 行
"""Exercise application-level input and output boundaries in an isolated workspace."""
import argparse
import json
import os
from pathlib import Path,PureWindowsPath
import subprocess
import sys

VARIABLE="MB_SKILLS_DEMO_KEY"
HERE=Path(__file__).resolve().parent


class Denied(ValueError):
    pass


def confined(root, supplied, existing):
    root=root.resolve(strict=True)
    if not root.is_dir():
        raise Denied("ROOT")
    requested=Path(supplied)
    if (requested.anchor or not requested.parts or ".." in requested.parts or
            any(":" in part or PureWindowsPath(part).is_reserved() for part in requested.parts)):
        raise Denied("PATH")
    candidate=(root/requested).resolve(strict=existing)
    if candidate==root or not candidate.is_relative_to(root):
        raise Denied("OUTSIDE")
    return candidate


def choose_secret(private_file):
    value=os.environ.get(VARIABLE,"").strip()
    if value:
        return value,"environment"
    if private_file is not None and private_file.is_file():
        config=json.loads(private_file.read_bytes())
        value=config.get("token","")
        if isinstance(value,str) and value.strip():
            return value.strip(),"private_file"
    raise Denied("NO_SECRET")


def run_worker(label):
    env={key:value for key,value in os.environ.items() if key.upper()!=VARIABLE}
    command=[sys.executable,"-I","-B","-X","utf8",str(HERE/"worker.py"),label]
    result=subprocess.run(command,env=env,check=True,encoding="utf-8",capture_output=True,timeout=6)
    return json.loads(result.stdout)


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input-root",required=True,type=Path)
    parser.add_argument("--output-root",required=True,type=Path)
    parser.add_argument("--input",required=True)
    parser.add_argument("--output",required=True)
    parser.add_argument("--label",default="warehouse")
    parser.add_argument("--private-config",type=Path)
    args=parser.parse_args()
    try:
        inbound=args.input_root.resolve(strict=True)
        outbound=args.output_root.resolve(strict=True)
        if inbound.is_relative_to(outbound) or outbound.is_relative_to(inbound):
            raise Denied("OVERLAP")
        source=confined(inbound,args.input,existing=True)
        target=confined(outbound,args.output,existing=False)
        if not source.is_file():
            raise Denied("INPUT_TYPE")
        _,origin=choose_secret(args.private_config)
        contents=source.read_text(encoding="utf-8")
        worker=run_worker(args.label)
        result={"rows":len(contents.splitlines()),"label":worker["label"],"secret_source":origin,
                "worker_received_secret":worker["secret_present"]}
        with target.open("x",encoding="utf-8",newline="\n") as handle:
            json.dump(result,handle,ensure_ascii=False)
    except Denied as error:
        print(json.dumps({"ok":False,"code":str(error)}))
        return 2
    except FileNotFoundError:
        print(json.dumps({"ok":False,"code":"MISSING_PATH"}))
        return 2
    except FileExistsError:
        print(json.dumps({"ok":False,"code":"TARGET_EXISTS"}))
        return 2
    except (OSError,ValueError,subprocess.SubprocessError):
        print(json.dumps({"ok":False,"code":"PROCESSING_FAILED"}))
        return 2
    print(json.dumps({"ok":True,**result},ensure_ascii=False))
    return 0


if __name__=="__main__":
    raise SystemExit(main())
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。

入口文件:projects/skills-security/bounded_run.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 bounded_run.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Skills(技能)

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a331.zip

下载课程关联工程包:Skills(技能)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a353.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习