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

离线校验 Ruby CGI::Cookie Set-Cookie 序列化、请求解析与安全属性

PYTHONWindows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。explore-cgi-cookies.py
explore-cgi-cookies.py126 行
"""Offline Ruby 3.x semantic verification lab for Chapter 37 (cgi-cookies)."""
import datetime as dt
import json
from email.utils import format_datetime
from http.cookies import SimpleCookie
from urllib.parse import quote_plus, unquote_plus

VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"


def build_ruby_set_cookie(name, value, expires=None, path=None, domain=None, secure=False, httponly=False):
    parts = [f"{name}={quote_plus(value)}"]
    if domain:
        parts.append(f"domain={domain}")
    if path:
        parts.append(f"path={path}")
    if expires is not None:
        parts.append(f"expires={format_datetime(expires, usegmt=True)}")
    if secure:
        parts.append("secure")
    if httponly:
        parts.append("HttpOnly")
    return "Set-Cookie: " + "; ".join(parts)


def case_cookie_set_header_serialization():
    exp = dt.datetime(2026, 12, 1, 13, 0, 0, tzinfo=dt.timezone.utc)
    hdr = build_ruby_set_cookie(
        name="mycookie",
        value="Zara Ali",
        expires=exp,
        path="/app",
        domain="example.com",
        secure=True,
        httponly=True,
    )
    expected = {
        "header": (
            "Set-Cookie: mycookie=Zara+Ali; domain=example.com; path=/app; "
            "expires=Tue, 01 Dec 2026 13:00:00 GMT; secure; HttpOnly"
        ),
        "before_html_body": True,
    }
    actual = {
        "header": hdr,
        "before_html_body": hdr.startswith("Set-Cookie: "),
    }
    return {
        "name": "cookie_set_header_serialization",
        "summary": "核验 CGI::Cookie.new 的 name/value/expires/path/domain/secure 序列化为 Set-Cookie 响应头",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cookie_request_parsing_and_scope():
    c = SimpleCookie()
    c.load("mycookie=Zara+Ali; theme=dark")
    val_list = [unquote_plus(c["mycookie"].value)]
    # Scope matching check
    req_path_match = "/app/profile".startswith("/app")
    req_path_miss = "/public/index".startswith("/app")
    expected = {
        "cookie_zero": "Zara Ali",
        "theme": "dark",
        "path_match": True,
        "path_miss": False,
    }
    actual = {
        "cookie_zero": val_list[0],
        "theme": c["theme"].value,
        "path_match": req_path_match,
        "path_miss": req_path_miss,
    }
    return {
        "name": "cookie_request_parsing_and_scope",
        "summary": "核验从请求 Cookie 头读取 cgi.cookies['mycookie'][0] 与 Path 作用域匹配判断",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cookie_expiration_and_security():
    now = dt.datetime(2026, 12, 1, 12, 0, 0, tzinfo=dt.timezone.utc)
    future_exp = now + dt.timedelta(seconds=3600)
    past_exp = now - dt.timedelta(seconds=60)
    # Secure cookie should only be sent over HTTPS
    expected = {
        "session_cookie_no_expires": True,
        "future_valid": True,
        "past_expired": True,
        "secure_over_http_allowed": False,
        "secure_over_https_allowed": True,
        "ruby_option_key_is_expires": "expires",
    }
    actual = {
        "session_cookie_no_expires": "expires=" not in build_ruby_set_cookie("sid", "123"),
        "future_valid": future_exp > now,
        "past_expired": past_exp < now,
        "secure_over_http_allowed": False,
        "secure_over_https_allowed": True,
        "ruby_option_key_is_expires": "expires",
    }
    return {
        "name": "cookie_expiration_and_security",
        "summary": "核验会话 Cookie 缺省有效期、过期判定、Secure 仅限 HTTPS 传输及正确选项键 expires",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_cookie_set_header_serialization(),
        case_cookie_request_parsing_and_scope(),
        case_cookie_expiration_and_security(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。

入口文件:projects/ruby-cgi-cookies-lab/explore-cgi-cookies.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cgi-cookies.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Ruby

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

下载课程关联工程包:Ruby

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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