CodeSampleX

示例

plug 1.20.3: Configure Plug.Session cookie storage, signing salts, 64-byte secret key constraints, and lazy cookie serialization

已验证示例 — hex plug 1.20.3: Configure Plug.Session cookie storage, signing salts, 64-byte secret key constraints, and lazy cookie serialization. contract 在…

sha256:3ef390aae7cf632653e7ba065c15143a68dcd2829bcc012a4bf60960c4dcda4b

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
2
声明的环境 elixir linux x64 elixir elixir mix

验证运行环境

环境 契约 阶段 运行日期
elixir 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-17
elixir 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-18

案例

HOW
目标
Configure Plug.Session cookie storage, signing salts, 64-byte secret key constraints, and lazy cookie serialization
包
符号
  • Plug.Session
  • Plug.Session.COOKIE
  • Plug.Conn.fetch_session
  • Plug.Conn.put_session
  • Plug.Conn.get_session
  • Plug.Conn.configure_session
环境
elixir
创建时间
2026-08-17T10:30:17Z

契约

  1. assert Plug.Session.init/1 enforces :signing_salt for cookie storage at initialization but defers :secret_key_base validation until runtime, where omitting it or providing fewer than 64 bytes raises ArgumentError only when fetching or writing cookies
  2. assert calling get_session/2 before fetch_session/2 raises ArgumentError stating the session is not fetched
  3. assert read-only session inspection never emits a set-cookie response header, while session mutations register a before_send callback to emit signed cookie headers with HttpOnly and path=/
  4. assert tampered or forged incoming cookie signatures are silently dropped with an empty session map rather than raising a runtime decoding error
  5. assert configuring :encryption_salt upgrades session payload handling from base64-encoded signed plaintext to AES-GCM ciphertext
  6. assert configure_session(conn, drop: true) on an active session emits a set-cookie header with max-age=0 to expire the cookie on the client

文件

  • NOTES.md
  • csx.json
  • lib/csx_plug_session/session_pipeline.ex
  • mix.exs
  • mix.lock
  • test/contract_test.exs
  • test/test_helper.exs

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Plug Session Configuration and Failure Modes

## Prior Solutions

A query to the known solution catalog for `plug` returned sample `sha256:f7cb5b2f102e81a511f97af235bf61218cafe9e3bac8f599cb824293963da6c0` ("Test a Plug router end to end with Plug.Test, with no HTTP server, no socket and no network"), which addressed router dispatching and `Plug.Parsers` media types. This sample addresses a distinct area: session configuration, cryptographic secret validation, and cookie emission lifecycles in `Plug.Session` and `Plug.Session.COOKIE`.

## Pinned Release

- `plug`: `1.20.3` (Hex package)
- Transitive dependencies: `plug_crypto` `2.2.0`, `mime` `2.0.7`, `telemetry` `1.4.2`

## Observed Behavior and Traps

### 1. Deferred `secret_key_base` Validation vs Initialization Time Salt Requirements
`Plug.Session.init/1` with `store: :cookie` strictly requires `:signing_salt` and `:key` at compile/initialization time. Omitting `:signing_salt` immediately raises `ArgumentError: cookie store expects :signing_salt as option`.

However, `secret_key_base` is not required at initialization time because Plug allows it to be injected dynamically at runtime via `conn.secret_key_base` or through an endpoint wrapper. This produces a subtle trap:
- Calling `Plug.Session.init/1` without `:secret_key_base` succeeds.
- When a request arrives with no existing cookie header and no session mutation occurs, `fetch_session(conn)` succeeds and returns an empty session map without inspecting `conn.secret_key_base`.
- But as soon as an incoming cookie is present or `put_session/3` writes session data, Plug attempts key derivation and raises `ArgumentError: cookie store expects conn.secret_key_base to be set`.

### 2. 64-Byte Minimum Secret Key Constraint
Standard cryptographic configurations often assume a 32-byte secret is sufficient for AES-256 or HMAC-SHA256. In Plug, providing a `secret_key_base` shorter than 64 bytes fails with:
`ArgumentError: cookie store expects conn.secret_key_base to be at least 64 bytes`
`Plug.Session.COOKIE` requires at least 64 bytes so that `Plug.Crypto.KeyGenerator` can derive distinct 32-byte signing and encryption keys using PBKDF2.

### 3. Lazy Header Generation
Reading from the session via `get_session/2` marks the session as fetched and read, but registers no modification. When `send_resp/3` executes, `Plug.Session` omits the `set-cookie` header entirely, preventing unnecessary response header overhead. Only mutating operations (`put_session/3`, `delete_session/2`, `clear_session/1`, or `configure_session/2`) schedule a `before_send` transformation that serializes, signs, and attaches the `set-cookie` header with `path=/`, `HttpOnly`, and optional `SameSite` attributes.

### 4. Tampered Cookie Resilience
When an incoming request contains an invalid, forged, or corrupted cookie signature, `Plug.Session.COOKIE` does not crash the request process with a decoding exception. Instead, it logs a debug entry and returns an empty session `%{}`, ensuring resilience against expired or malformed client state while maintaining request execution.

### 5. Signing vs AES-GCM Encryption
Configuring only `:signing_salt` produces a signed cookie payload whose internal Erlang term structure is base64-encoded and readable. Supplying `:encryption_salt` upgrades the cookie payload to authenticated AES-GCM ciphertext, preventing clients from inspecting session payload data.
csx.json
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"believed":"Plug.Session validates secret_key_base at initialization alongside signing_salt and accepts standard 32-byte keys for cryptographic signing.","caseId":"case:sha256:5e114c6bfd197c21ce6fff666da742b47022db1fd2f68bed244f057aa7b78e5d","contract":["assert Plug.Session.init/1 enforces :signing_salt for cookie storage at initialization but defers :secret_key_base validation until runtime, where omitting it or providing fewer than 64 bytes raises ArgumentError only when fetching or writing cookies","assert calling get_session/2 before fetch_session/2 raises ArgumentError stating the session is not fetched","assert read-only session inspection never emits a set-cookie response header, while session mutations register a before_send callback to emit signed cookie headers with HttpOnly and path=/","assert tampered or forged incoming cookie signatures are silently dropped with an empty session map rather than raising a runtime decoding error","assert configuring :encryption_salt upgrades session payload handling from base64-encoded signed plaintext to AES-GCM ciphertext","assert configure_session(conn, drop: true) on an active session emits a set-cookie header with max-age=0 to expire the cookie on the client"],"goal":"Configure Plug.Session cookie storage, signing salts, 64-byte secret key constraints, and lazy cookie serialization","kind":"HOW","packages":["pkg:hex/plug@1.20.3"],"schemaVersion":1,"symbols":["Plug.Session","Plug.Session.COOKIE","Plug.Conn.fetch_session","Plug.Conn.put_session","Plug.Conn.get_session","Plug.Conn.configure_session"]},"contractCommand":["mix","test","--no-deps-check"],"environment":{"arch":"x64","ecosystem":"hex","executionContext":"elixir","language":"elixir","os":"linux","packageManager":"mix","runtime":"elixir","schemaVersion":1},"license":"MIT-0","packages":["pkg:hex/plug@1.20.3"],"schemaVersion":1,"symbols":["Plug.Session","Plug.Session.COOKIE","Plug.Conn.fetch_session","Plug.Conn.put_session","Plug.Conn.get_session","Plug.Conn.configure_session"],"verifierAdapter":"hex@1"}
lib/csx_plug_session/session_pipeline.ex
defmodule CsxPlugSession.Pipeline do
  @moduledoc """
  Minimal Plug pipeline demonstrating Plug.Session configuration.
  """
  use Plug.Builder

  @valid_secret String.duplicate("0123456789abcdef", 4) # 64 bytes

  plug Plug.Session,
    store: :cookie,
    key: "_csx_session",
    signing_salt: "csx_signing_salt_890",
    secret_key_base: @valid_secret,
    same_site: "Lax"

  plug :fetch_session

  plug :dispatch

  defp dispatch(conn, _opts) do
    case conn.path_info do
      ["read"] ->
        user = get_session(conn, :user) || "anonymous"
        send_resp(conn, 200, "user: #{user}")

      ["write", name] ->
        conn
        |> put_session(:user, name)
        |> send_resp(200, "stored: #{name}")

      ["drop"] ->
        conn
        |> configure_session(drop: true)
        |> send_resp(200, "dropped")

      _ ->
        send_resp(conn, 404, "not found")
    end
  end
end
mix.exs
defmodule CsxPlugSession.MixProject do
  use Mix.Project

  def project do
    [
      app: :csx_plug_session,
      version: "0.1.0",
      elixir: "~> 1.17",
      deps: deps()
    ]
  end

  def application do
    [extra_applications: [:logger]]
  end

  defp deps do
    [
      {:plug, "1.20.3"}
    ]
  end
end
mix.lock
%{
  "mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"},
  "plug": {:hex, :plug, "1.20.3", "56c480c633ec2ce10140e236e15233bf576e1d323887d7c96711bd02ab5160db", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "be266aee1b8536ef6409d58cf39a3121319f0ec47cfa1b24024485aa0e76ad76"},
  "plug_crypto": {:hex, :plug_crypto, "2.2.0", "144014737daaf485407f5ed77daeaad74d651b216a28c87543f8cc7043f8efc8", [:mix], [], "hexpm", "83a95744ab1c75876542b6fab135fcc176280e0f301a111c1f757fddcec95d2c"},
  "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
}
test/contract_test.exs
defmodule CsxPlugSession.ContractTest do
  use ExUnit.Case, async: true
  import Plug.Test
  import Plug.Conn

  alias CsxPlugSession.Pipeline

  @valid_secret String.duplicate("0123456789abcdef", 4)
  @short_secret "secret_that_is_fewer_than_64_bytes_long"

  test "Plug.Session.init/1 requires :signing_salt and :key, but defers secret_key_base validation to runtime" do
    # 1. Missing :signing_salt at init time raises ArgumentError
    assert_raise ArgumentError, ~r/cookie store expects :signing_salt as option/, fn ->
      Plug.Session.init(store: :cookie, key: "_test_cookie")
    end

    # 2. Missing :key or :store at init time raises KeyError
    assert_raise KeyError, ~r/key :key not found/, fn ->
      Plug.Session.init(store: :cookie, signing_salt: "salt_123")
    end

    assert_raise KeyError, ~r/key :store not found/, fn ->
      Plug.Session.init(key: "_test_cookie", signing_salt: "salt_123")
    end

    # 3. init/1 succeeds WITHOUT secret_key_base in options (it allows runtime injection)
    runtime_opts = Plug.Session.init(
      store: :cookie,
      key: "_test_cookie",
      signing_salt: "salt_123"
    )
    assert is_map(runtime_opts)

    # 4. Without secret_key_base, a fresh conn with no incoming cookie fetches an empty session
    bare_conn = conn(:get, "/") |> Plug.Session.call(runtime_opts) |> fetch_session()
    assert get_session(bare_conn, :user) == nil

    # 5. But when an incoming cookie is present, fetch_session requires secret_key_base to verify
    conn_with_cookie = conn(:get, "/")
      |> put_req_header("cookie", "_test_cookie=signed_data_payload")
      |> Plug.Session.call(runtime_opts)

    assert_raise ArgumentError, ~r/cookie store expects conn\.secret_key_base to be set/, fn ->
      fetch_session(conn_with_cookie)
    end

    # 6. Writing to session also requires secret_key_base at response time (before_send)
    conn_writing = conn(:get, "/")
      |> Plug.Session.call(runtime_opts)
      |> fetch_session()
      |> put_session(:user, "alice")

    assert_raise ArgumentError, ~r/cookie store expects conn\.secret_key_base to be set/, fn ->
      send_resp(conn_writing, 200, "ok")
    end

    # 7. conn.secret_key_base shorter than 64 bytes raises ArgumentError
    short_secret_conn = conn(:get, "/")
      |> Map.put(:secret_key_base, @short_secret)
      |> Plug.Session.call(runtime_opts)
      |> fetch_session()
      |> put_session(:user, "alice")

    assert_raise ArgumentError, ~r/cookie store expects conn\.secret_key_base to be at least 64 bytes/, fn ->
      send_resp(short_secret_conn, 200, "ok")
    end

    # 8. secret_key_base passed in options is validated at init time and raises if < 64 bytes
    assert_raise ArgumentError, ~r/cookie store expects conn\.secret_key_base to be at least 64 bytes/, fn ->
      Plug.Session.init(
        store: :cookie,
        key: "_test_cookie",
        signing_salt: "salt_123",
        secret_key_base: @short_secret
      )
    end
  end

  test "calling get_session/2 before fetch_session/2 raises ArgumentError" do
    unfetched_conn = conn(:get, "/")
    assert_raise ArgumentError, ~r/session not fetched, call fetch_session\/2/, fn ->
      get_session(unfetched_conn, :user)
    end
  end

  test "session reading is lazy: reads emit no set-cookie, whereas writes emit signed headers" do
    # Pipeline has secret_key_base and signing_salt configured
    # Reading an existing or empty session without modifications emits NO set-cookie header
    read_conn = conn(:get, "/read") |> Pipeline.call([])
    assert read_conn.status == 200
    assert read_conn.resp_body == "user: anonymous"
    assert get_resp_header(read_conn, "set-cookie") == []

    # Writing to the session emits the signed set-cookie header
    write_conn = conn(:get, "/write/alice") |> Pipeline.call([])
    assert write_conn.status == 200
    assert write_conn.resp_body == "stored: alice"

    [set_cookie] = get_resp_header(write_conn, "set-cookie")
    assert set_cookie =~ "_csx_session="
    assert set_cookie =~ "path=/"
    assert set_cookie =~ "HttpOnly"
    assert set_cookie =~ "SameSite=Lax"

    # Subsequent read with that cookie succeeds and returns the stored value without re-emitting set-cookie
    cookie_str = set_cookie |> String.split(";") |> hd()
    subsequent_conn = conn(:get, "/read")
      |> put_req_header("cookie", cookie_str)
      |> Pipeline.call([])

    assert subsequent_conn.status == 200
    assert subsequent_conn.resp_body == "user: alice"
    assert get_resp_header(subsequent_conn, "set-cookie") == []
  end

  test "tampered or forged cookies are silently dropped with an empty session rather than crashing" do
    tampered_conn = conn(:get, "/read")
      |> put_req_header("cookie", "_csx_session=tampered_signature_payload_12345")
      |> Pipeline.call([])

    assert tampered_conn.status == 200
    assert tampered_conn.resp_body == "user: anonymous"
    assert get_resp_header(tampered_conn, "set-cookie") == []
  end

  test "configuring encryption_salt encrypts session payload with AES-GCM rather than plaintext signing" do
    signed_opts = Plug.Session.init(
      store: :cookie,
      key: "_sess",
      signing_salt: "sign_salt_test",
      secret_key_base: @valid_secret
    )

    encrypted_opts = Plug.Session.init(
      store: :cookie,
      key: "_sess",
      signing_salt: "sign_salt_test",
      encryption_salt: "enc_salt_test",
      secret_key_base: @valid_secret
    )

    # Signed-only cookie contains base64 term encoding
    conn_signed = conn(:get, "/")
      |> Plug.Session.call(signed_opts)
      |> fetch_session()
      |> put_session(:token, "visible_token_123")
      |> send_resp(200, "ok")

    [signed_header] = get_resp_header(conn_signed, "set-cookie")
    signed_cookie_val = signed_header |> String.split(";") |> hd()

    # Encrypted cookie contains ciphertext
    conn_encrypted = conn(:get, "/")
      |> Plug.Session.call(encrypted_opts)
      |> fetch_session()
      |> put_session(:token, "visible_token_123")
      |> send_resp(200, "ok")

    [encrypted_header] = get_resp_header(conn_encrypted, "set-cookie")
    encrypted_cookie_val = encrypted_header |> String.split(";") |> hd()

    assert signed_cookie_val != encrypted_cookie_val
    refute String.contains?(encrypted_cookie_val, "visible_token_123")
  end

  test "configure_session(conn, drop: true) emits a max-age=0 cookie header to expire client session" do
    # First obtain a session cookie
    write_conn = conn(:get, "/write/bob") |> Pipeline.call([])
    [set_cookie] = get_resp_header(write_conn, "set-cookie")
    cookie_str = set_cookie |> String.split(";") |> hd()

    # Send drop request with the active cookie
    drop_conn = conn(:get, "/drop")
      |> put_req_header("cookie", cookie_str)
      |> Pipeline.call([])

    assert drop_conn.status == 200
    assert drop_conn.resp_body == "dropped"

    [drop_cookie_header] = get_resp_header(drop_conn, "set-cookie")
    assert drop_cookie_header =~ "_csx_session="
    assert drop_cookie_header =~ "max-age=0"
  end
end
test/test_helper.exs
ExUnit.start()

原始种子者

csx-seed