diff --git a/.env.example b/.env.example index 1c77f8f0..d18c7324 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,9 @@ # Twigpine node — environment variables # Copy to .env and fill in your values. # All variables are optional unless marked REQUIRED. +# +# These were named GITLAWB_* before the rename to Twigpine. The old names still +# work; when both are set and differ, the TWIGPINE_* value is used. # ── Node identity ───────────────────────────────────────────────────────── # Path to the node's Ed25519 keypair PEM file. Must name a key file, not a @@ -12,11 +15,12 @@ # sends them to different places. Bare `identity.pem` under the default # config dir is still legal. # Generate with: twigpine identity new -# Leaving it unset uses ~/.gitlawb/identity.pem, which is the shared default +# Leaving it unset uses ~/.twigpine/identity.pem (or ~/.gitlawb/identity.pem +# when that folder exists and ~/.twigpine does not), which is the shared default # for both `twigpine` and `git-remote-twigpine`. The bare-filename form is for the # node's own service config; client tooling should inherit the default or use # an absolute path. -GITLAWB_KEY=/data/keys/identity.pem +TWIGPINE_KEY=/data/keys/identity.pem # Path to the node's persistent libp2p identity key file. Must include a # directory, because the node will not keep its p2p identity key in the working @@ -41,24 +45,24 @@ GITLAWB_KEY=/data/keys/identity.pem # merely closed too far is refused, not tightened, and no key in it was ever # exposed. # Keep it on a persistent volume so the PeerId survives redeploys. -# Default: ~/.gitlawb/p2p.key -#GITLAWB_P2P_KEY=/data/keys/p2p.key +# Default: ~/.twigpine/p2p.key +#TWIGPINE_P2P_KEY=/data/keys/p2p.key # Publicly reachable URL of this node (used in peer announcements) -GITLAWB_PUBLIC_URL=https://your-node.example.com +TWIGPINE_PUBLIC_URL=https://your-node.example.com # Base URL for the web view of repos on this node (used by `twigpine` to print a # working View: link after repo creation). Omit for nodes with no web front-end. -# Distinct from GITLAWB_PUBLIC_URL: that is API reachability for peers; +# Distinct from TWIGPINE_PUBLIC_URL: that is API reachability for peers; # this is browser reachability for humans. -# GITLAWB_WEB_URL=https://gitlawb.com +# TWIGPINE_WEB_URL=https://gitlawb.com # ── Server ──────────────────────────────────────────────────────────────── -GITLAWB_HOST=0.0.0.0 -GITLAWB_PORT=7545 +TWIGPINE_HOST=0.0.0.0 +TWIGPINE_PORT=7545 # ── Storage ─────────────────────────────────────────────────────────────── -GITLAWB_REPOS_DIR=/data/repos +TWIGPINE_REPOS_DIR=/data/repos # PostgreSQL connection URL. Required. # When using the bundled docker-compose, this is wired automatically. @@ -68,15 +72,15 @@ DATABASE_URL=postgresql://gitlawb:changeme@localhost:5432/gitlawb # Maximum connections in the PostgreSQL pool. A cap, not a floor — # connections open lazily. Size against the DB server's max_connections, # remembering admin tooling opens its own pool. -GITLAWB_DB_MAX_CONNECTIONS=48 +TWIGPINE_DB_MAX_CONNECTIONS=48 # Maximum connections in the DEDICATED advisory-lock pool, separate from the # pool above. Every in-flight repo write pins one connection here for its whole # duration, so this is a hard ceiling on simultaneous writes node-wide: size it # to expected peak concurrent writers, not small. Keeping it separate is what # stops a push burst from starving ordinary request handlers. Budget -# (GITLAWB_DB_MAX_CONNECTIONS + this) per node against the server's +# (TWIGPINE_DB_MAX_CONNECTIONS + this) per node against the server's # max_connections, times node count, plus admin tooling. -GITLAWB_DB_LOCK_POOL_MAX_CONNECTIONS=40 +TWIGPINE_DB_LOCK_POOL_MAX_CONNECTIONS=40 # Upper bound, in seconds, on any object-storage transfer that runs while a # per-repo write lock is HELD (the archive download inside acquire_write and the # upload inside release). These were free before the lock's connection was @@ -85,36 +89,36 @@ GITLAWB_DB_LOCK_POOL_MAX_CONNECTIONS=40 # two (the acquire-side refresh, which covers the existence check and download # together, and the release-side upload), so worst-case slot occupancy is about # twice this value plus the git work between them. Read it together with the pool -# size above and with GITLAWB_GIT_SERVICE_TIMEOUT_SECS. -GITLAWB_LOCK_HELD_TRANSFER_TIMEOUT_SECS=300 +# size above and with TWIGPINE_GIT_SERVICE_TIMEOUT_SECS. +TWIGPINE_LOCK_HELD_TRANSFER_TIMEOUT_SECS=300 # Seconds a request waits for a pool connection before failing with 503. -GITLAWB_DB_ACQUIRE_TIMEOUT_SECS=5 +TWIGPINE_DB_ACQUIRE_TIMEOUT_SECS=5 # Upper bound on each startup connect+migrate attempt, in seconds. Keep it # generous enough for a peer instance to finish migrating (the migration # advisory lock is held across a deploy); on expiry the attempt is retried. -GITLAWB_DB_CONNECT_TIMEOUT_SECS=60 +TWIGPINE_DB_CONNECT_TIMEOUT_SECS=60 # Startup retry backoff while the database is unavailable: first delay and # ceiling, in seconds. The node stays up serving 503s (with a truthful # /ready) instead of crash-looping. -GITLAWB_DB_RETRY_INITIAL_SECS=5 -GITLAWB_DB_RETRY_MAX_SECS=60 +TWIGPINE_DB_RETRY_INITIAL_SECS=5 +TWIGPINE_DB_RETRY_MAX_SECS=60 # ── IPFS pinning (Pinata) ───────────────────────────────────────────────── # Get a JWT at https://app.pinata.cloud/developers/api-keys -GITLAWB_PINATA_JWT= -GITLAWB_PINATA_UPLOAD_URL=https://uploads.pinata.cloud/v3/files +TWIGPINE_PINATA_JWT= +TWIGPINE_PINATA_UPLOAD_URL=https://uploads.pinata.cloud/v3/files # ── Arweave permanent anchoring (Irys devnet) ───────────────────────────── # Leave empty to disable Arweave anchoring. -GITLAWB_IRYS_URL=https://devnet.irys.xyz +TWIGPINE_IRYS_URL=https://devnet.irys.xyz # ── Base L2 smart contracts ─────────────────────────────────────────────── -GITLAWB_CHAIN_RPC_URL=https://sepolia.base.org -GITLAWB_CONTRACT_DID_REGISTRY=0x8046284116C5ac6724adbBf860feBeA85692d574 -GITLAWB_CONTRACT_NAME_REGISTRY=0x73094B9DAb2421878A20Abed1497001fbD51302c +TWIGPINE_CHAIN_RPC_URL=https://sepolia.base.org +TWIGPINE_CONTRACT_DID_REGISTRY=0x8046284116C5ac6724adbBf860feBeA85692d574 +TWIGPINE_CONTRACT_NAME_REGISTRY=0x73094B9DAb2421878A20Abed1497001fbD51302c # $GITLAWB ERC20 token (Base mainnet). -GITLAWB_TOKEN=0x5F980Dcfc4c0fa3911554cf5ab288ed0eb13DBa3 +TWIGPINE_TOKEN=0x5F980Dcfc4c0fa3911554cf5ab288ed0eb13DBa3 # ── On-chain PoS (operators — required to earn rewards) ─────────────────── # Set both of the next two to enable Proof-of-Stake mode. With both set, the @@ -122,37 +126,37 @@ GITLAWB_TOKEN=0x5F980Dcfc4c0fa3911554cf5ab288ed0eb13DBa3 # Leave empty to run without on-chain PoS (local dev / pre-launch). # Deployed GitlawbNodeStaking contract address. -GITLAWB_CONTRACT_NODE_STAKING= +TWIGPINE_CONTRACT_NODE_STAKING= # Operator wallet private key (0x-prefixed hex). Used to sign heartbeats. # Use a dedicated wallet with only enough ETH for gas — not your treasury. -GITLAWB_OPERATOR_PRIVATE_KEY= +TWIGPINE_OPERATOR_PRIVATE_KEY= # If true, the node refuses to start unless registered and currently active. # Leave false while bootstrapping; flip to true once your stake is confirmed. -GITLAWB_OPERATOR_STRICT_MODE=false +TWIGPINE_OPERATOR_STRICT_MODE=false # Heartbeat cadence in hours. Must be < 24 with headroom. Default: 20. -GITLAWB_HEARTBEAT_INTERVAL_HOURS=20 +TWIGPINE_HEARTBEAT_INTERVAL_HOURS=20 # ── docker-compose Postgres password ────────────────────────────────────── # Only used when running via `docker compose up` with the bundled Postgres. POSTGRES_PASSWORD=changeme # ── P2P networking ──────────────────────────────────────────────────────── -GITLAWB_P2P_PORT=7546 +TWIGPINE_P2P_PORT=7546 # Comma-separated HTTP peer URLs to announce to on startup. # The binary also ships with bootstrap-peers.json; set -# GITLAWB_BOOTSTRAP_DISABLE_SEEDS=true for isolated dev/test networks. -GITLAWB_BOOTSTRAP_PEERS= -GITLAWB_BOOTSTRAP_DISABLE_SEEDS=false +# TWIGPINE_BOOTSTRAP_DISABLE_SEEDS=true for isolated dev/test networks. +TWIGPINE_BOOTSTRAP_PEERS= +TWIGPINE_BOOTSTRAP_DISABLE_SEEDS=false # Require a peer write to prove its DID on every transport: RFC 9421 signatures # on the announce/sync routes, and an Ed25519 payload signature on gossip # ref-update events. Keep false during rolling upgrades so existing live nodes # can still communicate. Upgrade every gossip-publishing peer to a build that # signs events before setting this true, or their updates are dropped on # arrival with no error visible on their side. -GITLAWB_REQUIRE_SIGNED_PEER_WRITES=false +TWIGPINE_REQUIRE_SIGNED_PEER_WRITES=false # Require the authenticated pusher to be the repo owner on git-receive-pack. # A valid did:key signature is authentication, not authorization: anyone can @@ -164,26 +168,26 @@ GITLAWB_REQUIRE_SIGNED_PEER_WRITES=false # repository can push while this is on — see docs/RUN-A-NODE.md for issuing and # importing one. A CI key with no such delegation counts as a non-owner and # cannot push. -GITLAWB_ENFORCE_OWNER_PUSH=true +TWIGPINE_ENFORCE_OWNER_PUSH=true # Require a `nonce` parameter on signatures that authorize a write. Without one # the replay ledger keys on the signing-string hash, which rejects a repeated # byte-identical mutation inside the same second. Keep false until every client -# signs a nonce; with this and GITLAWB_REQUIRE_SIGNED_PEER_WRITES both true, a +# signs a nonce; with this and TWIGPINE_REQUIRE_SIGNED_PEER_WRITES both true, a # peer still on a pre-nonce binary can no longer write to this node. -GITLAWB_REQUIRE_SIGNATURE_NONCE=false +TWIGPINE_REQUIRE_SIGNATURE_NONCE=false # Comma-separated libp2p multiaddrs. # Example: /ip4/1.2.3.4/udp/7546/quic-v1/p2p/12D3KooW... -GITLAWB_P2P_BOOTSTRAP= +TWIGPINE_P2P_BOOTSTRAP= # ── Access control ──────────────────────────────────────────────────────── # Reserved and currently inert. Repo reads are gated per repository by # is_public and path-scoped visibility rules; this flag changes nothing. -GITLAWB_PUBLIC_READ=true +TWIGPINE_PUBLIC_READ=true # Maximum git smart-HTTP pack request size, in bytes. -GITLAWB_MAX_PACK_BYTES=2147483648 +TWIGPINE_MAX_PACK_BYTES=2147483648 # Max seconds a served git upload-pack / receive-pack (clone / push) may run # before it is aborted with a 504. Bounds a hung git that would otherwise pin a @@ -197,42 +201,42 @@ GITLAWB_MAX_PACK_BYTES=2147483648 # need a higher value here than when each stage was budgeted separately. # Must be 1..=3153600000 (100 years): the node derives deadlines from this value, # and a larger one cannot be represented. Default 600. -GITLAWB_GIT_SERVICE_TIMEOUT_SECS=600 +TWIGPINE_GIT_SERVICE_TIMEOUT_SECS=600 # Max seconds the storage-ACQUISITION phase of a served git op may run before the # request is shed with a 503, separate from the git-run timeout above. A -# concurrency permit is taken before this phase and GITLAWB_GIT_SERVICE_TIMEOUT_SECS +# concurrency permit is taken before this phase and TWIGPINE_GIT_SERVICE_TIMEOUT_SECS # only starts once git spawns, so without this a stalled backend (a hung Tigris # HEAD/GET, or a hung pg advisory-lock iteration on push) pins the permit and drains # the pool until every later request 503s. On expiry the permit is released # (fail-closed). Kept separate because acquisition and git execution are distinct # cost centers. Must be positive; set very large to effectively disable. Default 30. -GITLAWB_GIT_ACQUIRE_TIMEOUT_SECS=30 +TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS=30 # Max concurrent git READ ops (upload-pack + the upload-pack info/refs # advertisement) served at once, a global pool separate from the push pool below. # The anon receive-pack info/refs advertisement has its OWN pool (see below), not # this one. Over-cap sheds a clean 503 + Retry-After. Anonymous reads draw from -# here, so pair it with GITLAWB_MAX_CONCURRENT_READS_PER_CALLER (below) so one +# here, so pair it with TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER (below) so one # caller cannot monopolize the pool. Default 128. -GITLAWB_MAX_CONCURRENT_GIT_OPS=128 +TWIGPINE_MAX_CONCURRENT_GIT_OPS=128 # Max concurrent git-receive-pack (push) POST operations, in a pool separate from -# the read pool (GITLAWB_MAX_CONCURRENT_GIT_OPS) so anonymous reads cannot shed an +# the read pool (TWIGPINE_MAX_CONCURRENT_GIT_OPS) so anonymous reads cannot shed an # authenticated push at admission. The anon receive-pack info/refs advertisement # runs in a SEPARATE pool of the same size (disjoint from this one), so an # advertisement flood cannot shed a push either. Over-cap sheds a 503 + # Retry-After. Default 32. -GITLAWB_MAX_CONCURRENT_GIT_PUSHES=32 +TWIGPINE_MAX_CONCURRENT_GIT_PUSHES=32 # Max pushes PARKED at once waiting for the per-repo write lease of the SAME repo. # A parked push holds its already-buffered pack body in memory, so this bounds that # memory for a hot repo. Past the cap the newest push sheds a clean 503 + # Retry-After ("repo is busy with another push") instead of joining the queue; a # push to a DIFFERENT repo is never affected. The lease holder is not counted. -# Raising GITLAWB_MAX_CONCURRENT_GIT_PUSHES does not raise this; set it explicitly. +# Raising TWIGPINE_MAX_CONCURRENT_GIT_PUSHES does not raise this; set it explicitly. # Default 8. -GITLAWB_REPO_LEASE_MAX_WAITERS=8 +TWIGPINE_REPO_LEASE_MAX_WAITERS=8 # Max concurrent post-push pin loops (IPFS + Pinata pin_new_objects) across all # repos. The per-repo encrypt-task set caps the pin-task COUNT; this caps how many @@ -242,21 +246,21 @@ GITLAWB_REPO_LEASE_MAX_WAITERS=8 # waiting for a permit still holds its full list, and how many park is capped only # per repo. Do not size memory from this knob alone. A loop DEFERS (waits) when the # pool is full, never drops a pin. Default 8. -GITLAWB_MAX_CONCURRENT_PIN_TASKS=8 +TWIGPINE_MAX_CONCURRENT_PIN_TASKS=8 # Max concurrent read ops (upload-pack + the upload-pack info/refs advertisement) # a single caller may hold, so one caller cannot monopolize the read pool. Keyed # on the resolved SOURCE IP, never the DID: a signature does not move a caller off -# this cap. The source-IP key is only as granular as GITLAWB_TRUSTED_PROXY below: +# this cap. The source-IP key is only as granular as TWIGPINE_TRUSTED_PROXY below: # left unset, a node behind an edge/NAT keys all callers on the edge IP and this -# collapses to one global cap. Set GITLAWB_TRUSTED_PROXY for per-client keying; a +# collapses to one global cap. Set TWIGPINE_TRUSTED_PROXY for per-client keying; a # high-fanout caller (CI behind one NAT) then needs the operator to raise this. # Default 16. -GITLAWB_MAX_CONCURRENT_READS_PER_CALLER=16 +TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER=16 # Two further per-source concurrency caps exist on the PUSH side but have NO # environment variable of their own: both are DERIVED as -# GITLAWB_MAX_CONCURRENT_GIT_PUSHES / 8, with a floor of 1. They are not settable +# TWIGPINE_MAX_CONCURRENT_GIT_PUSHES / 8, with a floor of 1. They are not settable # independently, so raising the push pool raises both proportionally, and the # default push pool of 32 gives each a cap of 4. # * The anon receive-pack info/refs advertisement cap: one source IP may hold at @@ -270,12 +274,12 @@ GITLAWB_MAX_CONCURRENT_READS_PER_CALLER=16 # rate, not in-flight concurrency, and owner enforcement can be turned off for # a rolling upgrade). # Keyed on the resolved source IP, never the DID, so a DID farm does not defeat -# them; keying granularity follows GITLAWB_TRUSTED_PROXY like the read cap above. +# them; keying granularity follows TWIGPINE_TRUSTED_PROXY like the read cap above. # ── Push rate limiting (git-receive-pack flood brake) ───────────────────── # Max receive-pack requests (info/refs advertisement + push POST) per client # IP per hour. 0 disables. Default 600. -GITLAWB_PUSH_RATE_LIMIT=600 +TWIGPINE_PUSH_RATE_LIMIT=600 # ── /ipfs/{cid} visibility-walk admission (#174) ────────────────────────── # GET /ipfs/{cid} runs a per-repo full-history git walk in a blocking thread to @@ -284,15 +288,15 @@ GITLAWB_PUSH_RATE_LIMIT=600 # concurrent walks and exhausting blocking-pool threads + PIDs. # Max concurrent /ipfs walks across all callers (a pool of its own, disjoint from # the served-git pools). Over-cap sheds a 503. Default 32. -GITLAWB_MAX_CONCURRENT_IPFS_WALKS=32 +TWIGPINE_MAX_CONCURRENT_IPFS_WALKS=32 # Max concurrent /ipfs walks a single SOURCE IP may hold (keyed like the git -# per-caller caps via GITLAWB_TRUSTED_PROXY; reject-before-insert bounded map). +# per-caller caps via TWIGPINE_TRUSTED_PROXY; reject-before-insert bounded map). # Default 4. -GITLAWB_IPFS_WALK_PER_SOURCE=4 +TWIGPINE_IPFS_WALK_PER_SOURCE=4 # Max legacy (NULL-provenance) repos probed per single /ipfs request, bounding the # scan-fallback fan-out (git cat-file per candidate repo) for an anonymous caller. A # truncated scan sheds a retryable 503, never a false 404. Default 256. -GITLAWB_IPFS_MAX_LEGACY_PROBES=256 +TWIGPINE_IPFS_MAX_LEGACY_PROBES=256 # Max repo ROWS one /ipfs request's legacy scan may read from the database. The probe # ceiling above only counts once a probe runs, and quarantined or private repos are # denied before that, so without this an all-denying inventory paged the whole repo @@ -302,33 +306,33 @@ GITLAWB_IPFS_MAX_LEGACY_PROBES=256 # the per-caller /ipfs work allowance, since each page is charged to it. Lowering it # sharpens a coarse oracle: laddering to the end reveals the node's total repo count to # within one ceiling. Default 2048. -GITLAWB_IPFS_MAX_LEGACY_SCAN_ROWS=2048 +TWIGPINE_IPFS_MAX_LEGACY_SCAN_ROWS=2048 # Max EXPENSIVE path-scope visibility walks per single /ipfs request (only a # blob in a path-scoped repo costs a full-history walk). Over-cap repos are # skipped without a verdict and the scan continues; if the object is then found # nowhere the request sheds a retryable 503 instead of a false 404. The effective # cap is the tighter of this value and the node's internal per-request ceiling of # 17, so values above 17 have no effect; lower values do tighten it. Default 64. -GITLAWB_IPFS_MAX_REPOS_WALKED=64 +TWIGPINE_IPFS_MAX_REPOS_WALKED=64 # Ceiling on repos one /ipfs request may VISIT past the visibility gate. Each # visit costs a repo acquire — on a Tigris cache miss a full archive download, # so this is also the worst-case object-store fetch count per request — plus a # cat-file probe. On exhaustion the scan stops and sheds a retryable 503. # Default 1024. -GITLAWB_IPFS_MAX_REPO_VISITS=1024 +TWIGPINE_IPFS_MAX_REPO_VISITS=1024 # Absolute wall-clock budget for one admitted /ipfs request's acquire+walk # lifetime (all stages of the whole scan). Per-stage clamps bound the acquire # and walk stages to the remaining budget, and no stage starts once it is # exhausted (the scan then sheds a retryable 503). The object-type probe and # content-read cat-file subprocesses are budget-checked before starting AND each -# run under their own deadline (the lesser of GITLAWB_GIT_SERVICE_TIMEOUT_SECS and +# run under their own deadline (the lesser of TWIGPINE_GIT_SERVICE_TIMEOUT_SECS and # the remaining budget), reaped via process-group teardown, so a hung cat-file # cannot hold the request's walk slot past it. One hang path is still unbounded: # the probe's object-store readability check is a plain filesystem sweep with # nothing to reap, so a wedged filesystem can hold the slot past the deadline. # Must be 1..=3153600000 (100 years): the node derives an Instant deadline from # this value, and a larger one cannot be represented. Default 600. -GITLAWB_IPFS_REQUEST_BUDGET_SECS=600 +TWIGPINE_IPFS_REQUEST_BUDGET_SECS=600 # Shorter budget (seconds) for the pre-walk CID resolve: the lookup that maps a # requested CID to its git oid(s), which runs while the scarce walk admission is # already held. A well-formed CID with no pin row does no probe and no walk work, @@ -337,10 +341,10 @@ GITLAWB_IPFS_REQUEST_BUDGET_SECS=600 # the remaining request budget; walk and probe work stay on the request budget, # so a slow but progressing scan is never shed by it. # Must be 1..=3153600000 (100 years). Default 10. -GITLAWB_IPFS_RESOLVE_BUDGET_SECS=10 +TWIGPINE_IPFS_RESOLVE_BUDGET_SECS=10 # Max /ipfs/{cid} requests per client IP per hour (route flood brake, distinct # from the concurrency caps above). 0 disables. Default 600. -GITLAWB_IPFS_RATE_LIMIT=600 +TWIGPINE_IPFS_RATE_LIMIT=600 # Per-client-IP rate limit for the anonymous task read routes # (GET /api/v1/tasks, GET /api/v1/tasks/{id}), in requests per hour. @@ -350,27 +354,27 @@ GITLAWB_IPFS_RATE_LIMIT=600 # the task is hidden or missing. These reads can require task, repository, # and visibility-rule queries even when no task is returned, so the brake # bounds the cost of anonymous probes. Keyed on the resolved client IP via -# GITLAWB_TRUSTED_PROXY. 0 disables. Default: 1200 (a list page +# TWIGPINE_TRUSTED_PROXY. 0 disables. Default: 1200 (a list page # followed by per-task reads is a normal client pattern, so this sits above # the /ipfs budget). The GraphQL/WS task-read brake shares this budget. -GITLAWB_TASK_READ_RATE_LIMIT=1200 +TWIGPINE_TASK_READ_RATE_LIMIT=1200 # ── Creation rate limiting (repo/agent/issue/PR flood brake) ────────────── # Max creation requests (POST /api/v1/repos, /api/register, fork, issues, # pulls) per client IP per hour, in addition to the per-DID limit. The per-DID # limit alone is bypassed by a did:key farm (one throwaway identity per repo), # which is how spam-repo floods slip past it and the iCaptcha gate; the per-IP -# brake caps a single-source flood. Uses GITLAWB_TRUSTED_PROXY below to resolve +# brake caps a single-source flood. Uses TWIGPINE_TRUSTED_PROXY below to resolve # the client IP. 0 disables. Default 120. -GITLAWB_CREATE_RATE_LIMIT=120 +TWIGPINE_CREATE_RATE_LIMIT=120 # Per-DID creation requests allowed inside the window below (repo create, # issue create, PR create, register, fork). 0 is rejected at startup: it would # silently disable the limiter. Default 10. -GITLAWB_RATE_LIMIT_MAX=10 +TWIGPINE_RATE_LIMIT_MAX=10 # Window the per-DID creation count above applies over, in seconds. 0 is # rejected at startup: every timestamp would prune immediately, disabling the # limiter. Default 3600. -GITLAWB_RATE_LIMIT_WINDOW_SECS=3600 +TWIGPINE_RATE_LIMIT_WINDOW_SECS=3600 # ── Write rate limiting (non-creation authenticated writes) ─────────────── # Max requests per client IP per hour on the shared write bucket. It is debited @@ -381,24 +385,24 @@ GITLAWB_RATE_LIMIT_WINDOW_SECS=3600 # consume this bucket too, not only mutations (GraphQL WebSocket subscriptions # are excluded). Issue comment and issue close debit it inside the handler, # after the read gate, rather than in router middleware. Issue close also draws -# on its own GITLAWB_CLOSE_ISSUE_RATE_LIMIT bucket, and a close refused by +# on its own TWIGPINE_CLOSE_ISSUE_RATE_LIMIT bucket, and a close refused by # either cap spends nothing from the other. Separate from the creation and push -# brakes. Uses GITLAWB_TRUSTED_PROXY to resolve the client IP. +# brakes. Uses TWIGPINE_TRUSTED_PROXY to resolve the client IP. # NOTE: this is a per-IP aggregate across ALL those write actions, so behind a -# shared NAT/egress IP (or with GITLAWB_TRUSTED_PROXY unset) many users collapse +# shared NAT/egress IP (or with TWIGPINE_TRUSTED_PROXY unset) many users collapse # onto one bucket — raise this for automation-heavy or multi-user single-IP # deployments. 0 disables. Default 600. -GITLAWB_WRITE_RATE_LIMIT=600 +TWIGPINE_WRITE_RATE_LIMIT=600 -# ── Peer-sync rate limiting (per client IP, uses GITLAWB_TRUSTED_PROXY below) ─ +# ── Peer-sync rate limiting (per client IP, uses TWIGPINE_TRUSTED_PROXY below) ─ # /api/v1/peers/announce and /api/v1/sync/notify accept unsigned requests from # known peers and run at higher frequency, so a generous bucket. Separate from # the trigger bucket so an unsigned notify flood can't drain trigger's quota. # 0 disables. Default 600. -GITLAWB_PEER_WRITE_RATE_LIMIT=600 +TWIGPINE_PEER_WRITE_RATE_LIMIT=600 # /api/v1/sync/trigger requires a signature and fans out to every peer per call, # so it gets a tight bucket. 0 disables. Default 60. -GITLAWB_SYNC_TRIGGER_RATE_LIMIT=60 +TWIGPINE_SYNC_TRIGGER_RATE_LIMIT=60 # Which forwarded header the edge is trusted to set, used to resolve the real # client IP for the push limiter. One of: @@ -408,27 +412,27 @@ GITLAWB_SYNC_TRIGGER_RATE_LIMIT=60 # rightmost X-Forwarded-For hop). # Only set this when a proxy you control actually fronts the node; trusting a # forwarded header on a directly-exposed node lets clients spoof the key. -GITLAWB_TRUSTED_PROXY= +TWIGPINE_TRUSTED_PROXY= # ── Sync ───────────────────────────────────────────────────────────────── # Enable automatic background sync from known peers -GITLAWB_AUTO_SYNC=false +TWIGPINE_AUTO_SYNC=false # ── External upstream mirroring ─────────────────────────────────────────── # Default-off scheduled fetch worker for repositories configured as INBOUND. -# Enabling requires GITLAWB_ENFORCE_OWNER_PUSH=true; the node refuses to start +# Enabling requires TWIGPINE_ENFORCE_OWNER_PUSH=true; the node refuses to start # otherwise. The worker updates branches and tags atomically while preserving # Gitlawb-owned review/internal refs. Enabling also requires Git >= 2.37 on # the host for http.curloptResolve DNS pinning; the node refuses to start # when the installed Git is older. -GITLAWB_UPSTREAM_MIRROR_ENABLED=false +TWIGPINE_UPSTREAM_MIRROR_ENABLED=false # Pause after each complete scan. Must be 5..=86400 seconds. -GITLAWB_UPSTREAM_MIRROR_INTERVAL_SECS=300 +TWIGPINE_UPSTREAM_MIRROR_INTERVAL_SECS=300 # Deadline for the external fetch child only; the preflight probes run on # their own short bound. Must be 1..=3153600000 seconds. -GITLAWB_UPSTREAM_MIRROR_FETCH_TIMEOUT_SECS=600 +TWIGPINE_UPSTREAM_MIRROR_FETCH_TIMEOUT_SECS=600 # Keyset page size; every page is processed before the next scan delay. -GITLAWB_UPSTREAM_MIRROR_PAGE_SIZE=100 +TWIGPINE_UPSTREAM_MIRROR_PAGE_SIZE=100 # ── Reconciliation sweep ───────────────────────────────────────────────── # Periodic durability sweep: re-derives the public pin set and the withheld-blob # recovery set each hour and fills gaps so a dropped replication job never means @@ -438,10 +442,10 @@ GITLAWB_UPSTREAM_MIRROR_PAGE_SIZE=100 # Phase-capability matrix: # - Public pin repair: IPFS-only, Pinata-only, or both (requires the # respective backend to be configured). -# - Encrypted recovery repair: requires local IPFS (GITLAWB_IPFS_API). +# - Encrypted recovery repair: requires local IPFS (TWIGPINE_IPFS_API). # Pinata-only nodes reconcile public pins only; encrypted recovery # reconciliation is not performed. -GITLAWB_RECONCILIATION_SWEEP=true +TWIGPINE_RECONCILIATION_SWEEP=true # ── iCaptcha proof-of-intelligence gate ─────────────────────────────────── # Optional gate on create_repo + register: require callers to present an diff --git a/Cargo.toml b/Cargo.toml index eed3caed..e7788486 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,7 @@ uuid = { version = "1", features = ["v4"] } reqwest = { version = "0.12", features = ["blocking", "json", "multipart", "rustls-tls"], default-features = false } # URL parsing (what reqwest::Url re-exports, so the shared redirect predicate can # take a parsed URL without pulling reqwest into twigpine-core; also used for the -# absolute-browser-url validation on GITLAWB_WEB_URL in the node and CLI) +# absolute-browser-url validation on TWIGPINE_WEB_URL in the node and CLI) url = "2" percent-encoding = "2" # HMAC diff --git a/Dockerfile b/Dockerfile index c246e74b..80cf8c42 100644 --- a/Dockerfile +++ b/Dockerfile @@ -86,7 +86,16 @@ RUN ln -s twigpine /usr/local/bin/twig \ USER gitlawb WORKDIR /data -ENV GITLAWB_REPOS_DIR=/data/repos \ +# Image defaults, kept under the settings' names from before the rename on +# purpose. A value the operator gives under either name must override them: +# TWIGPINE_* wins over GITLAWB_* when both are set, so defaults under the new +# names would silently beat an existing deployment's GITLAWB_PORT or +# GITLAWB_KEY. Under the old names, GITLAWB_* replaces them and TWIGPINE_* +# outranks them. They move to the new names when the old ones are dropped. +# TWIGPINE_CONTAINER_IMAGE tells the node these six came from the image, so it +# does not list them as old names the operator still uses. +ENV TWIGPINE_CONTAINER_IMAGE=1 \ + GITLAWB_REPOS_DIR=/data/repos \ GITLAWB_KEY=/data/keys/identity.pem \ GITLAWB_P2P_KEY=/data/keys/p2p.key \ GITLAWB_HOST=0.0.0.0 \ @@ -98,7 +107,7 @@ EXPOSE 7545 7546/udp VOLUME ["/data"] HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ - CMD curl -fsS http://127.0.0.1:${GITLAWB_PORT}/health || exit 1 + CMD curl -fsS http://127.0.0.1:${TWIGPINE_PORT:-${GITLAWB_PORT}}/health || exit 1 # Run under tini so the node is never PID 1. As PID 1 a process must reap # reparented orphans itself; the node does not, so git's reparented grandchildren diff --git a/README.md b/README.md index ae93b234..3c664c37 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ Good today: Known limitations: -- Repository write authorization is one switch: `GITLAWB_ENFORCE_OWNER_PUSH`, which defaults to `true`. With it off — rolling upgrades only — a valid HTTP Signature identifies a pusher but does not authorize one, so every signed caller may push everywhere. +- Repository write authorization is one switch: `TWIGPINE_ENFORCE_OWNER_PUSH`, which defaults to `true`. With it off — rolling upgrades only — a valid HTTP Signature identifies a pusher but does not authorize one, so every signed caller may push everywhere. - UCAN capabilities are consulted on the push path only. There, the chain's root issuer is anchored to the repository owner, so an owner-rooted, time-bounded delegation that names the repository grants scoped collaborator access for pushing to it, for the `git/push`, `*`, or `repo/admin` actions. A `*` *resource* is refused: a delegation must name the repository it applies to, so it cannot grow to cover repos created later. Push-only cuts the other way too: a delegation grants no read access, so on a private repository the delegate must also be a reader (`twigpine visibility set`) — the two gates a push crosses are described in [`docs/RUN-A-NODE.md`](docs/RUN-A-NODE.md). The rest is unchanged: there is no revocation path, `nb` constraints are refused rather than interpreted, and no other route — reads, pull requests, issues, agents — consults capabilities at all. - Agent lifecycle revocation is not enforced by HTTP Signature authorization; do not rely on removing or revoking an agent record to block a compromised signer. - Task list/get reads (REST and GraphQL) are repository/task-gated and omit `ucan_token`. Slash-form `repo_id` rows (mirror-hosted tasks) can appear on list for the delegator or trimmed assignee, but `GET /api/v1/tasks/{id}` and GraphQL `task` fail closed for every caller because there is no local repository backing to serve. Read visibility is not a blanket data-classification boundary: IPFS-pin and Arweave-anchor listings are not repository-gated; withheld path names can be visible to a root reader; and later visibility changes cannot retract content already announced or externally anchored. @@ -188,15 +188,15 @@ twigpine repo create my-repo --description "My first Twigpine repo" --node http: Use the git remote helper: ```bash -export GITLAWB_NODE=http://localhost:7545 +export TWIGPINE_NODE=http://localhost:7545 git clone gitlawb://did:key:z6Mk.../my-repo ``` -For public-network use, make sure `GITLAWB_NODE` points to the node you want, over +For public-network use, make sure `TWIGPINE_NODE` points to the node you want, over `https://`. The helper defaults to localhost for local development, and plaintext `http://` is allowed only to this machine: requests are signed but not encrypted, so a cleartext hop to a remote node exposes the pack contents and the `Signature` -header. A remote `http://` node is refused, and `GITLAWB_ALLOW_INSECURE_HTTP=1` +header. A remote `http://` node is refused, and `TWIGPINE_ALLOW_INSECURE_HTTP=1` overrides that for a trusted private network. ### Full lifecycle against an iCaptcha-enforcing node @@ -232,8 +232,8 @@ Notes: `git push` is **signed-only** (owner signature is the gate, no per-push challenge); reads (clone / fetch / `repo info`) need no proof. A non-existent repo returns a clear `404`, never a placeholder. -- **API-key iCaptcha deployments:** set `GITLAWB_ICAPTCHA_URL` to your iCaptcha - origin and `GITLAWB_ICAPTCHA_API_KEY` to its key. The client only talks to an +- **API-key iCaptcha deployments:** set `TWIGPINE_ICAPTCHA_URL` to your iCaptcha + origin and `TWIGPINE_ICAPTCHA_API_KEY` to its key. The client only talks to an `https` origin whose host is allowlisted (that URL or the public default), and sends the bearer token **only** to your configured origin, never to a URL a node advertises, so a hostile node can't capture the key or redirect the solve. @@ -371,27 +371,27 @@ POST /api/v1/peers/announce POST /api/v1/sync/notify ``` -When `GITLAWB_REQUIRE_SIGNED_PEER_WRITES=false`, unsigned legacy peers are accepted on those two routes, but signed requests are verified when signature headers are present. Staged rollout relaxes who may announce, not who owns a peer row. An unsigned announce may register a previously unseen peer, and it may refresh an existing row whose `http_url` is unchanged, but changing an existing peer's `http_url` requires an RFC 9421 signature from that peer's own DID and is refused with 403 otherwise. An unsigned announce can only register a `did:key`, since that is the only method whose verifying key can be resolved and therefore the only kind of row anyone could ever correct through the signed path; any other DID is refused with 400. Once all live peers upgrade, operators can set: +When `TWIGPINE_REQUIRE_SIGNED_PEER_WRITES=false`, unsigned legacy peers are accepted on those two routes, but signed requests are verified when signature headers are present. Staged rollout relaxes who may announce, not who owns a peer row. An unsigned announce may register a previously unseen peer, and it may refresh an existing row whose `http_url` is unchanged, but changing an existing peer's `http_url` requires an RFC 9421 signature from that peer's own DID and is refused with 403 otherwise. An unsigned announce can only register a `did:key`, since that is the only method whose verifying key can be resolved and therefore the only kind of row anyone could ever correct through the signed path; any other DID is refused with 400. Once all live peers upgrade, operators can set: ```bash -GITLAWB_REQUIRE_SIGNED_PEER_WRITES=true +TWIGPINE_REQUIRE_SIGNED_PEER_WRITES=true ``` `POST /api/v1/sync/trigger` is not part of the staged rollout: it always requires a signature in both config modes and returns 401 without one, because each call drives an O(peers) outbound fan-out. -A verified signature is spent once on the write routes that require one: repo, issue, PR, task, bounty, profile, webhook, label, star, replica, visibility and agent mutations, plus git push and `POST /api/v1/sync/trigger`. A captured request to any of those cannot be replayed. The two peer-write routes are the exception. `POST /api/v1/peers/announce` and `POST /api/v1/sync/notify` reach the ledger only when `GITLAWB_REQUIRE_SIGNED_PEER_WRITES=true`; under the default (`false`) they verify a signature when the headers are present but never spend it, so a captured signed peer write is still replayable there until the fleet upgrades and the flag is turned on. The ledger keys on the RFC 9421 `nonce` parameter when the client signs one and falls back to the signing-string hash when it does not. The fallback is correct but coarser: a client that repeats a byte-identical mutation within the same second is rejected as a replay and has to re-sign. `GITLAWB_REQUIRE_SIGNATURE_NONCE` closes that fallback once every client emits a nonce: +A verified signature is spent once on the write routes that require one: repo, issue, PR, task, bounty, profile, webhook, label, star, replica, visibility and agent mutations, plus git push and `POST /api/v1/sync/trigger`. A captured request to any of those cannot be replayed. The two peer-write routes are the exception. `POST /api/v1/peers/announce` and `POST /api/v1/sync/notify` reach the ledger only when `TWIGPINE_REQUIRE_SIGNED_PEER_WRITES=true`; under the default (`false`) they verify a signature when the headers are present but never spend it, so a captured signed peer write is still replayable there until the fleet upgrades and the flag is turned on. The ledger keys on the RFC 9421 `nonce` parameter when the client signs one and falls back to the signing-string hash when it does not. The fallback is correct but coarser: a client that repeats a byte-identical mutation within the same second is rejected as a replay and has to re-sign. `TWIGPINE_REQUIRE_SIGNATURE_NONCE` closes that fallback once every client emits a nonce: ```bash -GITLAWB_REQUIRE_SIGNATURE_NONCE=true +TWIGPINE_REQUIRE_SIGNATURE_NONCE=true ``` -With it on, a nonce-less signature on a write route is rejected with 400 and `X-Gitlawb-Error: signature_nonce_required`. Signed reads are never affected. Flipping it on has a federation precondition: three of the node's own outbound signed calls (peer announce, replica registration, sync-notify) are peer traffic, so a node running with both this and `GITLAWB_REQUIRE_SIGNED_PEER_WRITES` set to true will reject peer writes from any node still on a pre-nonce binary. Upgrade the fleet before enabling it. +With it on, a nonce-less signature on a write route is rejected with 400 and `X-Twigpine-Error: signature_nonce_required`. Signed reads are never affected. Flipping it on has a federation precondition: three of the node's own outbound signed calls (peer announce, replica registration, sync-notify) are peer traffic, so a node running with both this and `TWIGPINE_REQUIRE_SIGNED_PEER_WRITES` set to true will reject peer writes from any node still on a pre-nonce binary. Upgrade the fleet before enabling it. -`GITLAWB_REQUIRE_SIGNED_PEER_WRITES` is not HTTP-only. It also gates inbound gossip ref-update events on the libp2p mesh, which carry an Ed25519 payload signature rather than RFC 9421 headers because there are no HTTP headers to sign. Set to `true`, an unsigned gossip event is dropped. Set to `false`, an unsigned event is accepted with a warning during the rolling-upgrade window, and the write budget it consumes is charged to the forwarding peer rather than to the DID it claims, since an unsigned event's claimed DID is asserted and not proven. A present-but-invalid signature is refused in both modes; that is forgery, not an un-upgraded peer. +`TWIGPINE_REQUIRE_SIGNED_PEER_WRITES` is not HTTP-only. It also gates inbound gossip ref-update events on the libp2p mesh, which carry an Ed25519 payload signature rather than RFC 9421 headers because there are no HTTP headers to sign. Set to `true`, an unsigned gossip event is dropped. Set to `false`, an unsigned event is accepted with a warning during the rolling-upgrade window, and the write budget it consumes is charged to the forwarding peer rather than to the DID it claims, since an unsigned event's claimed DID is asserted and not proven. A present-but-invalid signature is refused in both modes; that is forgery, not an un-upgraded peer. -Because `GITLAWB_REQUIRE_SIGNED_PEER_WRITES` now spans both transports, the rollout order matters in one direction: **upgrade every gossip-publishing peer to a build that signs events before you set `GITLAWB_REQUIRE_SIGNED_PEER_WRITES` to `true`.** Enabling it while an old publisher is still live drops that publisher's ref-updates on arrival, and the publisher sees no error, because gossip has no response to carry one. Upgrading the HTTP peers alone is not sufficient. +Because `TWIGPINE_REQUIRE_SIGNED_PEER_WRITES` now spans both transports, the rollout order matters in one direction: **upgrade every gossip-publishing peer to a build that signs events before you set `TWIGPINE_REQUIRE_SIGNED_PEER_WRITES` to `true`.** Enabling it while an old publisher is still live drops that publisher's ref-updates on arrival, and the publisher sees no error, because gossip has no response to carry one. Upgrading the HTTP peers alone is not sufficient. -There is a second precondition on gossip ingest that the flag does not control. A publisher's `node_did` must already exist in the receiving node's peers table, or the event is dropped as an unknown peer DID. This holds in both modes, signed and unsigned alike: a valid signature proves key possession, not membership. Rows reach that table over HTTP, either from `GITLAWB_BOOTSTRAP_PEERS` when this node contacts a bootstrap peer and records the DID it reports, or from a prior `POST /api/v1/peers/announce`. So a peer that only ever joined the libp2p mesh, with no HTTP announce and no bootstrap contact in either direction, will have its ref-updates dropped even with a good signature and the flag off. If gossip is silently not landing from a peer you can see on the mesh, check that its DID is in `GET /api/v1/peers` on the receiving side first. +There is a second precondition on gossip ingest that the flag does not control. A publisher's `node_did` must already exist in the receiving node's peers table, or the event is dropped as an unknown peer DID. This holds in both modes, signed and unsigned alike: a valid signature proves key possession, not membership. Rows reach that table over HTTP, either from `TWIGPINE_BOOTSTRAP_PEERS` when this node contacts a bootstrap peer and records the DID it reports, or from a prior `POST /api/v1/peers/announce`. So a peer that only ever joined the libp2p mesh, with no HTTP announce and no bootstrap contact in either direction, will have its ref-updates dropped even with a good signature and the flag off. If gossip is silently not landing from a peer you can see on the mesh, check that its DID is in `GET /api/v1/peers` on the receiving side first. --- @@ -399,6 +399,12 @@ There is a second precondition on gossip ingest that the flag does not control. All configuration is via environment variables. See [`.env.example`](.env.example) for the full reference. +**Names from before the rename still work.** Settings were `GITLAWB_*` and are `TWIGPINE_*` now. The node, `twigpine` and the git helper accept both; when both are set and differ, the `TWIGPINE_*` value is used. The node logs which old names it was given, and `twigpine doctor` lists them. One case needs a manual rename: a `GITLAWB_*` entry under `environment:` in a `docker-compose.override.yml` no longer replaces the matching entry in the shipped `docker-compose.yml`, which now uses the `TWIGPINE_*` name. The node warns at startup about every setting it was given under both names with different values. Releases up to 0.7.1 know only the `GITLAWB_*` names. + +The default key folder is `~/.twigpine`. An existing `~/.gitlawb` keeps being used as long as there is no `~/.twigpine`; nothing is moved. To switch, stop the node and rename the folder. Once `~/.twigpine` exists it is the only one read: if a key is missing there but present in `~/.gitlawb`, the node refuses to start and says so, and it never creates a second identity beside the first. + +Response headers and webhook deliveries carry both `X-Twigpine-*` and the older `X-Gitlawb-*` names with the same values. + Minimum required for a persistent node: ```env @@ -409,40 +415,40 @@ Important node settings: | Variable | Purpose | |---|---| -| `GITLAWB_HOST` / `GITLAWB_PORT` | HTTP bind address and port. | -| `GITLAWB_REPOS_DIR` | Local bare repo storage directory. | -| `GITLAWB_PUBLIC_URL` | Public HTTP URL announced to peers. | -| `GITLAWB_P2P_PORT` | libp2p QUIC/UDP port. Use `0` to disable. | -| `GITLAWB_BOOTSTRAP_PEERS` | Comma-separated HTTP peer URLs. | -| `GITLAWB_P2P_BOOTSTRAP` | Comma-separated libp2p multiaddrs. | -| `GITLAWB_P2P_KEY` | Path to the node's persistent libp2p identity key file, which fixes the PeerId across restarts. Must name a key file inside a directory, such as `/data/keys/p2p.key` or `./keys/p2p.key`. Two kinds of problem are handled differently. A value that cannot name a securable key file at all (a bare filename, `..` traversal, a trailing `/`, the filesystem root, or a `~/` path that escapes home) is refused before the node binds, so the process exits. Anything wrong with the storage itself (a symlinked or non-directory parent, an unsafe ancestor or working directory, an unreadable or malformed key) leaves p2p off while HTTP keeps serving; the node logs it at error level as `p2p_identity_key_load_failed` and sets the `gitlawb_p2p_identity_key_load_failed` metric to 1. Note that `/health` still reports healthy in that state, so alert on the log event or the metric rather than on the health check. Correcting the storage and restarting restores the same PeerId. On Unix a new key is created `0600` inside a `0700` directory. A key directory that grants access beyond its owner is tightened to `0700` on start; one that is closed too far is refused with a `chmod 700` remedy rather than widened, since a directory locked down on purpose is an operator decision. Rotate the key only when the node logs that the directory was group- or world-writable (or the key file itself was group- or world-readable). An ordinary `0755` directory is tightened too, but others could not read a `0600` key or replace its directory entry. An existing key file is never modified: one with group or other bits set is rejected (`chmod 600`), and so is one this node cannot read. On other platforms no permissions are enforced. Default `~/.gitlawb/p2p.key`; point it at a persistent volume when running in a container. | -| `GITLAWB_BOOTSTRAP_DISABLE_SEEDS` | Disable embedded seed peers for isolated dev/test networks. | -| `GITLAWB_REQUIRE_SIGNED_PEER_WRITES` | Require signed peer announce/sync writes. Defaults to `false` during the staged rollout below. | -| `GITLAWB_REQUIRE_SIGNATURE_NONCE` | Require a signed `nonce` on write routes. Default false; see the staged rollout note above. | -| `GITLAWB_ENFORCE_OWNER_PUSH` | Require the pusher on `git-receive-pack` to be the repo owner, or to present an owner-rooted, time-bounded UCAN `git/push` capability naming the repository (`X-Ucan`). **Defaults to `true`.** A `did:key` signature is authentication, not authorization — anyone can mint a key and sign — so with this off every signed caller may push to every repository, private ones included. A CI or delegated key with no such delegation counts as a non-owner and cannot push while this is on. The delegation clears the push gate only; on a private repository the delegate must also be a reader. Set `false` only for a rolling upgrade; see [`docs/RUN-A-NODE.md`](docs/RUN-A-NODE.md). | -| `GITLAWB_AUTO_SYNC` | Enable automatic sync from known peers. | -| `GITLAWB_RECONCILIATION_SWEEP` | Enable the hourly durability sweep that re-pins/backstops missing objects (default `true`; disabled when no IPFS/Pinata backend is configured). Public pin repair runs against any configured backend (IPFS, Pinata, or both). Encrypted recovery repair requires local IPFS (`GITLAWB_IPFS_API`); Pinata-only nodes reconcile public pins only. | -| `GITLAWB_MAX_PACK_BYTES` | Max git pack body size for smart-HTTP routes. | -| `GITLAWB_GIT_SERVICE_TIMEOUT_SECS` | Max seconds a served git upload-pack, receive-pack, or `info/refs` advertisement may run before it is aborted (504). Default 600. Also bounds the withheld-blob classification walk (on both the upload-pack serve and receive-pack replication paths) and the push-side pin-candidate discovery (`rev-list` / `cat-file`), each reaped via process-group teardown at the deadline. On the path-scoped upload-pack path the classification walk and the pack serve share ONE deadline, so this value bounds their combined duration rather than granting each stage a full budget: a walk that consumes it leaves the serve nothing and the clone gets a 504. Serving large path-scoped repos may therefore need a higher value than they did when each stage was budgeted separately. Accepted range is 1 to 3153600000 (100 years), since the node derives deadlines from this value and a larger one cannot be represented. | -| `GITLAWB_GIT_ACQUIRE_TIMEOUT_SECS` | Max seconds the storage-acquisition phase (Tigris HEAD/GET, push advisory-lock) of a served git op may run before the request is shed with a 503, separate from the git-run timeout. The concurrency permit is released on expiry so a stalled backend cannot pin the pool. Default 30. | -| `GITLAWB_MAX_CONCURRENT_GIT_OPS` | Max concurrent served git READ ops (upload-pack and its `info/refs` advertisement) across all callers; over-cap sheds a 503 + Retry-After. Anonymous reads draw from this pool, so pair it with `GITLAWB_MAX_CONCURRENT_READS_PER_CALLER`. Pushes and the receive-pack advertisement have their own pools, so a read flood cannot shed an authenticated push. Default 128. | -| `GITLAWB_MAX_CONCURRENT_GIT_PUSHES` | Max concurrent `git-receive-pack` POST operations, in a pool separate from the read pool. The anon receive-pack `info/refs` advertisement runs in a third pool of the same size, disjoint from both, so an advertisement flood cannot shed a push either. Two per-source push caps are derived from this value (`/8`, floor 1) and have no env var of their own. Over-cap sheds a 503 + Retry-After. Default 32. | -| `GITLAWB_MAX_CONCURRENT_READS_PER_CALLER` | Max concurrent read ops a single caller may hold, so one caller cannot monopolize the read pool. Keyed on the resolved source IP, never the DID, and only as granular as `GITLAWB_TRUSTED_PROXY`: left unset, a node behind an edge or NAT keys every caller on the edge IP and this collapses to one global cap. Default 16. | -| `GITLAWB_MAX_CONCURRENT_PIN_TASKS` | Max post-push pin loops (IPFS + Pinata) running concurrently across all repos. This caps how many loops RUN at once, not how much object-id list memory the node retains: on the local IPFS path a loop parked waiting for a permit still holds its full list. Do not size memory from this knob alone. A loop over cap waits, never drops a pin. Up to two loops run per push that starts its own encrypt/pin task when both IPFS and Pinata are configured; a push coalesced onto an in-flight task adds at most one warm loop. See [docs/STORAGE-AND-PINNING.md](docs/STORAGE-AND-PINNING.md) for the two-tier model, dedup, and parked-list memory. Default 8. | -| `GITLAWB_REPO_LEASE_MAX_WAITERS` | Max pushes parked at once waiting for the same repo's write lease. Each waiter pins its buffered pack body, so this bounds that memory for a hot repo; past the cap the newest push sheds a 503 + Retry-After instead of queueing. Pushes to other repos are unaffected, and the lease holder is not counted. Default 8. | -| `GITLAWB_MAX_CONCURRENT_IPFS_WALKS` | Max concurrent `GET /ipfs/{cid}` visibility walks across all callers (own pool, disjoint from the served-git pools); over-cap sheds 503. Default 32. | -| `GITLAWB_IPFS_WALK_PER_SOURCE` | Max concurrent `/ipfs` walks a single source IP may hold. Default 4. | -| `GITLAWB_IPFS_MAX_LEGACY_PROBES` | Max legacy (NULL-provenance) repos probed per `/ipfs/{cid}` request, bounding the scan-fallback fan-out. A truncated scan returns a retryable 503, not a false 404. Default 256. | -| `GITLAWB_IPFS_MAX_LEGACY_SCAN_ROWS` | Max repo rows one `/ipfs/{cid}` request's legacy scan may read from the database. The probe ceiling above only starts counting once a probe runs, and quarantined or private repos are denied before that, so this is what bounds a scan over an inventory that denies the caller everywhere. A truncated scan sheds a retryable 503 carrying an opaque `continuation` token; echoing it as `?scan=` resumes the scan where it stopped. Every per-request ceiling on this path (rows, probes, visits, retained rule bytes) mints one, so each request advances the ladder by at least the rows it read and a holder buried past a ceiling is reached in a bounded number of requests, `ceil(repos / ceiling) + 1` when this row ceiling is the one that binds. No ceiling ever produces a 404. Every page is charged to the caller's `/ipfs` work allowance, so raising this raises that allowance too. Lowering it sharpens an oracle: because a truncation emits a token and a completed wrap does not, laddering to the end reveals the node's total repo count (private and quarantined included) to within one ceiling. Default 2048. | -| `GITLAWB_IPFS_MAX_REPOS_WALKED` | Max expensive path-scope visibility walks a `/ipfs/{cid}` request may run per phase; over-cap repos are skipped and the scan continues, shedding a retryable 503 (not a false 404) if the object is then found nowhere. The effective cap is the tighter of this knob and the node's internal history-walk ceiling of 17 (`MAX_PIN_SOURCES + 1`), so a value above 17 has no effect while a value below it does tighten the cap. It is charged per phase: the provenance lookup and the legacy-scan fallback get separate equal budgets, so one request can run up to twice the cap in total. Default 64. | -| `GITLAWB_IPFS_MAX_REPO_VISITS` | Ceiling on repos one `/ipfs/{cid}` request may visit (acquire + probe) past the visibility gate. Also the worst-case per-request Tigris fetch count. On exhaustion the scan stops with a retryable 503. Default 1024. | -| `GITLAWB_IPFS_REQUEST_BUDGET_SECS` | Absolute wall-clock budget for one admitted `/ipfs/{cid}` request's acquire+walk lifetime. Per-stage clamps bound the acquire and walk stages to the remaining budget, and no stage starts once it is exhausted; the scan then stops with a retryable 503. The object-type probe and content-read `cat-file` subprocesses are budget-checked before starting and each also run under their own deadline (the lesser of `GITLAWB_GIT_SERVICE_TIMEOUT_SECS` and the remaining budget), reaped via process-group teardown, so a hung `cat-file` cannot hold the request's walk slot past it. One hang path is still unbounded: the probe's object-store readability check is a plain filesystem sweep with nothing to reap, so a wedged filesystem can hold the slot past the deadline. Default 600. Accepted range is 1 to 3153600000 (100 years), since the node derives a deadline from this value and a larger one cannot be represented. | -| `GITLAWB_IPFS_RESOLVE_BUDGET_SECS` | Shorter budget for the pre-walk CID resolve inside an admitted `/ipfs/{cid}` request: the lookup that maps the requested CID to its git oid(s), which runs while the scarce walk admission is already held. A well-formed CID with no pin row does no probe and no walk work, so without this it could hold a walk slot for the whole request budget while nothing walked, and enough such requests shed every real retrieval at admission. The effective deadline is the lesser of this and the remaining request budget, so a value above `GITLAWB_IPFS_REQUEST_BUDGET_SECS` degrades to the request budget. Only the resolve is on this clock; walk and probe work stay on the request budget, so a slow but progressing scan is never shed by it. Default 10. Accepted range is 1 to 3153600000 (100 years). | -| `GITLAWB_IPFS_RATE_LIMIT` | Max `/ipfs/{cid}` requests per client IP per hour (route flood brake). 0 disables. Default 600. | -| `GITLAWB_TASK_READ_RATE_LIMIT` | Max anonymous task-read requests (`GET /api/v1/tasks`, `GET /api/v1/tasks/{id}`) per client IP per hour, sharing the budget with the GraphQL/WS task-read brake. Uses `GITLAWB_TRUSTED_PROXY` to resolve the client IP. 0 disables. Default 1200 (above the `/ipfs` budget to allow list pages followed by per-task reads). | -| `GITLAWB_TIGRIS_BUCKET` | Optional S3/Tigris shared repo storage bucket. | -| `GITLAWB_PINATA_JWT` | Optional Pinata/IPFS warm-storage pinning. | -| `GITLAWB_IRYS_URL` | Optional Irys/Arweave permanent anchoring. | +| `TWIGPINE_HOST` / `TWIGPINE_PORT` | HTTP bind address and port. | +| `TWIGPINE_REPOS_DIR` | Local bare repo storage directory. | +| `TWIGPINE_PUBLIC_URL` | Public HTTP URL announced to peers. | +| `TWIGPINE_P2P_PORT` | libp2p QUIC/UDP port. Use `0` to disable. | +| `TWIGPINE_BOOTSTRAP_PEERS` | Comma-separated HTTP peer URLs. | +| `TWIGPINE_P2P_BOOTSTRAP` | Comma-separated libp2p multiaddrs. | +| `TWIGPINE_P2P_KEY` | Path to the node's persistent libp2p identity key file, which fixes the PeerId across restarts. Must name a key file inside a directory, such as `/data/keys/p2p.key` or `./keys/p2p.key`. Two kinds of problem are handled differently. A value that cannot name a securable key file at all (a bare filename, `..` traversal, a trailing `/`, the filesystem root, or a `~/` path that escapes home) is refused before the node binds, so the process exits. Anything wrong with the storage itself (a symlinked or non-directory parent, an unsafe ancestor or working directory, an unreadable or malformed key) leaves p2p off while HTTP keeps serving; the node logs it at error level as `p2p_identity_key_load_failed` and sets the `gitlawb_p2p_identity_key_load_failed` metric to 1. Note that `/health` still reports healthy in that state, so alert on the log event or the metric rather than on the health check. Correcting the storage and restarting restores the same PeerId. On Unix a new key is created `0600` inside a `0700` directory. A key directory that grants access beyond its owner is tightened to `0700` on start; one that is closed too far is refused with a `chmod 700` remedy rather than widened, since a directory locked down on purpose is an operator decision. Rotate the key only when the node logs that the directory was group- or world-writable (or the key file itself was group- or world-readable). An ordinary `0755` directory is tightened too, but others could not read a `0600` key or replace its directory entry. An existing key file is never modified: one with group or other bits set is rejected (`chmod 600`), and so is one this node cannot read. On other platforms no permissions are enforced. Default `~/.twigpine/p2p.key`; point it at a persistent volume when running in a container. | +| `TWIGPINE_BOOTSTRAP_DISABLE_SEEDS` | Disable embedded seed peers for isolated dev/test networks. | +| `TWIGPINE_REQUIRE_SIGNED_PEER_WRITES` | Require signed peer announce/sync writes. Defaults to `false` during the staged rollout below. | +| `TWIGPINE_REQUIRE_SIGNATURE_NONCE` | Require a signed `nonce` on write routes. Default false; see the staged rollout note above. | +| `TWIGPINE_ENFORCE_OWNER_PUSH` | Require the pusher on `git-receive-pack` to be the repo owner, or to present an owner-rooted, time-bounded UCAN `git/push` capability naming the repository (`X-Ucan`). **Defaults to `true`.** A `did:key` signature is authentication, not authorization — anyone can mint a key and sign — so with this off every signed caller may push to every repository, private ones included. A CI or delegated key with no such delegation counts as a non-owner and cannot push while this is on. The delegation clears the push gate only; on a private repository the delegate must also be a reader. Set `false` only for a rolling upgrade; see [`docs/RUN-A-NODE.md`](docs/RUN-A-NODE.md). | +| `TWIGPINE_AUTO_SYNC` | Enable automatic sync from known peers. | +| `TWIGPINE_RECONCILIATION_SWEEP` | Enable the hourly durability sweep that re-pins/backstops missing objects (default `true`; disabled when no IPFS/Pinata backend is configured). Public pin repair runs against any configured backend (IPFS, Pinata, or both). Encrypted recovery repair requires local IPFS (`TWIGPINE_IPFS_API`); Pinata-only nodes reconcile public pins only. | +| `TWIGPINE_MAX_PACK_BYTES` | Max git pack body size for smart-HTTP routes. | +| `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` | Max seconds a served git upload-pack, receive-pack, or `info/refs` advertisement may run before it is aborted (504). Default 600. Also bounds the withheld-blob classification walk (on both the upload-pack serve and receive-pack replication paths) and the push-side pin-candidate discovery (`rev-list` / `cat-file`), each reaped via process-group teardown at the deadline. On the path-scoped upload-pack path the classification walk and the pack serve share ONE deadline, so this value bounds their combined duration rather than granting each stage a full budget: a walk that consumes it leaves the serve nothing and the clone gets a 504. Serving large path-scoped repos may therefore need a higher value than they did when each stage was budgeted separately. Accepted range is 1 to 3153600000 (100 years), since the node derives deadlines from this value and a larger one cannot be represented. | +| `TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS` | Max seconds the storage-acquisition phase (Tigris HEAD/GET, push advisory-lock) of a served git op may run before the request is shed with a 503, separate from the git-run timeout. The concurrency permit is released on expiry so a stalled backend cannot pin the pool. Default 30. | +| `TWIGPINE_MAX_CONCURRENT_GIT_OPS` | Max concurrent served git READ ops (upload-pack and its `info/refs` advertisement) across all callers; over-cap sheds a 503 + Retry-After. Anonymous reads draw from this pool, so pair it with `TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER`. Pushes and the receive-pack advertisement have their own pools, so a read flood cannot shed an authenticated push. Default 128. | +| `TWIGPINE_MAX_CONCURRENT_GIT_PUSHES` | Max concurrent `git-receive-pack` POST operations, in a pool separate from the read pool. The anon receive-pack `info/refs` advertisement runs in a third pool of the same size, disjoint from both, so an advertisement flood cannot shed a push either. Two per-source push caps are derived from this value (`/8`, floor 1) and have no env var of their own. Over-cap sheds a 503 + Retry-After. Default 32. | +| `TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER` | Max concurrent read ops a single caller may hold, so one caller cannot monopolize the read pool. Keyed on the resolved source IP, never the DID, and only as granular as `TWIGPINE_TRUSTED_PROXY`: left unset, a node behind an edge or NAT keys every caller on the edge IP and this collapses to one global cap. Default 16. | +| `TWIGPINE_MAX_CONCURRENT_PIN_TASKS` | Max post-push pin loops (IPFS + Pinata) running concurrently across all repos. This caps how many loops RUN at once, not how much object-id list memory the node retains: on the local IPFS path a loop parked waiting for a permit still holds its full list. Do not size memory from this knob alone. A loop over cap waits, never drops a pin. Up to two loops run per push that starts its own encrypt/pin task when both IPFS and Pinata are configured; a push coalesced onto an in-flight task adds at most one warm loop. See [docs/STORAGE-AND-PINNING.md](docs/STORAGE-AND-PINNING.md) for the two-tier model, dedup, and parked-list memory. Default 8. | +| `TWIGPINE_REPO_LEASE_MAX_WAITERS` | Max pushes parked at once waiting for the same repo's write lease. Each waiter pins its buffered pack body, so this bounds that memory for a hot repo; past the cap the newest push sheds a 503 + Retry-After instead of queueing. Pushes to other repos are unaffected, and the lease holder is not counted. Default 8. | +| `TWIGPINE_MAX_CONCURRENT_IPFS_WALKS` | Max concurrent `GET /ipfs/{cid}` visibility walks across all callers (own pool, disjoint from the served-git pools); over-cap sheds 503. Default 32. | +| `TWIGPINE_IPFS_WALK_PER_SOURCE` | Max concurrent `/ipfs` walks a single source IP may hold. Default 4. | +| `TWIGPINE_IPFS_MAX_LEGACY_PROBES` | Max legacy (NULL-provenance) repos probed per `/ipfs/{cid}` request, bounding the scan-fallback fan-out. A truncated scan returns a retryable 503, not a false 404. Default 256. | +| `TWIGPINE_IPFS_MAX_LEGACY_SCAN_ROWS` | Max repo rows one `/ipfs/{cid}` request's legacy scan may read from the database. The probe ceiling above only starts counting once a probe runs, and quarantined or private repos are denied before that, so this is what bounds a scan over an inventory that denies the caller everywhere. A truncated scan sheds a retryable 503 carrying an opaque `continuation` token; echoing it as `?scan=` resumes the scan where it stopped. Every per-request ceiling on this path (rows, probes, visits, retained rule bytes) mints one, so each request advances the ladder by at least the rows it read and a holder buried past a ceiling is reached in a bounded number of requests, `ceil(repos / ceiling) + 1` when this row ceiling is the one that binds. No ceiling ever produces a 404. Every page is charged to the caller's `/ipfs` work allowance, so raising this raises that allowance too. Lowering it sharpens an oracle: because a truncation emits a token and a completed wrap does not, laddering to the end reveals the node's total repo count (private and quarantined included) to within one ceiling. Default 2048. | +| `TWIGPINE_IPFS_MAX_REPOS_WALKED` | Max expensive path-scope visibility walks a `/ipfs/{cid}` request may run per phase; over-cap repos are skipped and the scan continues, shedding a retryable 503 (not a false 404) if the object is then found nowhere. The effective cap is the tighter of this knob and the node's internal history-walk ceiling of 17 (`MAX_PIN_SOURCES + 1`), so a value above 17 has no effect while a value below it does tighten the cap. It is charged per phase: the provenance lookup and the legacy-scan fallback get separate equal budgets, so one request can run up to twice the cap in total. Default 64. | +| `TWIGPINE_IPFS_MAX_REPO_VISITS` | Ceiling on repos one `/ipfs/{cid}` request may visit (acquire + probe) past the visibility gate. Also the worst-case per-request Tigris fetch count. On exhaustion the scan stops with a retryable 503. Default 1024. | +| `TWIGPINE_IPFS_REQUEST_BUDGET_SECS` | Absolute wall-clock budget for one admitted `/ipfs/{cid}` request's acquire+walk lifetime. Per-stage clamps bound the acquire and walk stages to the remaining budget, and no stage starts once it is exhausted; the scan then stops with a retryable 503. The object-type probe and content-read `cat-file` subprocesses are budget-checked before starting and each also run under their own deadline (the lesser of `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` and the remaining budget), reaped via process-group teardown, so a hung `cat-file` cannot hold the request's walk slot past it. One hang path is still unbounded: the probe's object-store readability check is a plain filesystem sweep with nothing to reap, so a wedged filesystem can hold the slot past the deadline. Default 600. Accepted range is 1 to 3153600000 (100 years), since the node derives a deadline from this value and a larger one cannot be represented. | +| `TWIGPINE_IPFS_RESOLVE_BUDGET_SECS` | Shorter budget for the pre-walk CID resolve inside an admitted `/ipfs/{cid}` request: the lookup that maps the requested CID to its git oid(s), which runs while the scarce walk admission is already held. A well-formed CID with no pin row does no probe and no walk work, so without this it could hold a walk slot for the whole request budget while nothing walked, and enough such requests shed every real retrieval at admission. The effective deadline is the lesser of this and the remaining request budget, so a value above `TWIGPINE_IPFS_REQUEST_BUDGET_SECS` degrades to the request budget. Only the resolve is on this clock; walk and probe work stay on the request budget, so a slow but progressing scan is never shed by it. Default 10. Accepted range is 1 to 3153600000 (100 years). | +| `TWIGPINE_IPFS_RATE_LIMIT` | Max `/ipfs/{cid}` requests per client IP per hour (route flood brake). 0 disables. Default 600. | +| `TWIGPINE_TASK_READ_RATE_LIMIT` | Max anonymous task-read requests (`GET /api/v1/tasks`, `GET /api/v1/tasks/{id}`) per client IP per hour, sharing the budget with the GraphQL/WS task-read brake. Uses `TWIGPINE_TRUSTED_PROXY` to resolve the client IP. 0 disables. Default 1200 (above the `/ipfs` budget to allow list pages followed by per-task reads). | +| `TWIGPINE_TIGRIS_BUCKET` | Optional S3/Tigris shared repo storage bucket. | +| `TWIGPINE_PINATA_JWT` | Optional Pinata/IPFS warm-storage pinning. | +| `TWIGPINE_IRYS_URL` | Optional Irys/Arweave permanent anchoring. | Production note: change the default Postgres password before exposing a node publicly. @@ -451,23 +457,23 @@ Legacy-pin window: releases before the CID-resolver work stored the provider CID ### Upgrading: the PeerId rotates once This node's libp2p identity is now a keypair generated on first start and kept -at `GITLAWB_P2P_KEY`, rather than one derived from the node DID. Every node +at `TWIGPINE_P2P_KEY`, rather than one derived from the node DID. Every node therefore gets a new PeerId once, on the first start after upgrading, and keeps it from then on as long as that key file survives (put it on a persistent volume in a container). Two things to check before upgrading: -- Any `GITLAWB_P2P_BOOTSTRAP` multiaddr that pins a peer's old PeerId with a +- Any `TWIGPINE_P2P_BOOTSTRAP` multiaddr that pins a peer's old PeerId with a `/p2p/` suffix stops matching once that peer upgrades. Update the suffix, or drop it and let identify supply the current one. Addresses without the suffix keep working untouched. -- `GITLAWB_P2P_KEY` must name a key file inside a directory, such as +- `TWIGPINE_P2P_KEY` must name a key file inside a directory, such as `/data/keys/p2p.key` or `./keys/p2p.key`. A bare filename is refused at startup, since the node will not keep its identity key in the working directory. -Peers found over `GITLAWB_BOOTSTRAP_PEERS` and the embedded seed list are +Peers found over `TWIGPINE_BOOTSTRAP_PEERS` and the embedded seed list are unaffected, since those are HTTP URLs and carry no PeerId. --- @@ -479,16 +485,16 @@ Twigpine Node includes optional Base L2 node-operator hooks. Operators can regis PoS is disabled unless these are configured: ```env -GITLAWB_CONTRACT_NODE_STAKING=0x... -GITLAWB_OPERATOR_PRIVATE_KEY=0x... -GITLAWB_CHAIN_RPC_URL=https://mainnet.base.org +TWIGPINE_CONTRACT_NODE_STAKING=0x... +TWIGPINE_OPERATOR_PRIVATE_KEY=0x... +TWIGPINE_CHAIN_RPC_URL=https://mainnet.base.org ``` Recommended for operators: ```env -GITLAWB_OPERATOR_STRICT_MODE=true -GITLAWB_HEARTBEAT_INTERVAL_HOURS=20 +TWIGPINE_OPERATOR_STRICT_MODE=true +TWIGPINE_HEARTBEAT_INTERVAL_HOURS=20 ``` Read: diff --git a/SECURITY.md b/SECURITY.md index 52aaba69..cbda0f26 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -54,9 +54,9 @@ We will acknowledge receipt within 48 hours and aim to release a fix within 14 d These are documented limitations of the current live release. They should be prioritized without breaking existing nodes during rolling upgrades. ### Repository write authorization defaults -- `git-receive-pack` verifies HTTP Signatures and, with the default configuration, also requires the pusher DID to be the repository owner: `GITLAWB_ENFORCE_OWNER_PUSH` defaults to `true`. +- `git-receive-pack` verifies HTTP Signatures and, with the default configuration, also requires the pusher DID to be the repository owner: `TWIGPINE_ENFORCE_OWNER_PUSH` defaults to `true`. - **Impact:** With the default setting, a valid signature authenticates the pusher, and the pusher must be the repository owner. Authentication is not authorization on its own, since anyone can mint a `did:key` and sign, so owner enforcement is the only thing that prevents every signed caller from pushing to every repository, including private ones. -- **Mitigation:** `GITLAWB_ENFORCE_OWNER_PUSH=false` is the explicit rolling-upgrade compatibility override. Disable it only for the duration of an upgrade whose pushers are not yet the repo owner, then turn it back on. Delegated and CI keys count as non-owners: a UCAN `git/push` capability is verified but not yet honored for authorization, so they cannot push while this is on. +- **Mitigation:** `TWIGPINE_ENFORCE_OWNER_PUSH=false` is the explicit rolling-upgrade compatibility override. Disable it only for the duration of an upgrade whose pushers are not yet the repo owner, then turn it back on. Delegated and CI keys count as non-owners: a UCAN `git/push` capability is verified but not yet honored for authorization, so they cannot push while this is on. ### UCAN delegation and revocation - The middleware validates a supplied UCAN's complete proof chain, but a root token is accepted without an independently trusted issuer anchor. `Ucan::can` is not yet used by write handlers, so a UCAN does not grant scoped repository access. @@ -73,7 +73,7 @@ These are documented limitations of the current live release. They should be pri ### Private repository reads - Repository and path-scoped visibility checks are enforced for repository API and Git content reads. A denied whole-repository or root read returns the same 404 shape as a missing repository, so the denial does not reveal private-repository existence. - Sparse-clone support exposes withheld path globs to callers who may read the repository root. Do not put sensitive information in withheld path names. -- Task list/get reads (`GET /api/v1/tasks`, `GET /api/v1/tasks/{id}`, and GraphQL `tasks` / `task` over HTTP and WebSocket) are repository/task-gated through shared visibility collectors and omit `ucan_token`. Slash-form `repo_id` rows (mirror-hosted tasks) can appear on list for the delegator or trimmed assignee, but `GET /api/v1/tasks/{id}` and GraphQL `task` fail closed for every caller because there is no local repository backing to serve. All of those transports share the same per-IP `GITLAWB_TASK_READ_RATE_LIMIT` budget. `/api/v1/ipfs/pins` and `/api/v1/arweave/anchors` are not repository-gated; pin and anchor listings expose object and ref metadata. +- Task list/get reads (`GET /api/v1/tasks`, `GET /api/v1/tasks/{id}`, and GraphQL `tasks` / `task` over HTTP and WebSocket) are repository/task-gated through shared visibility collectors and omit `ucan_token`. Slash-form `repo_id` rows (mirror-hosted tasks) can appear on list for the delegator or trimmed assignee, but `GET /api/v1/tasks/{id}` and GraphQL `task` fail closed for every caller because there is no local repository backing to serve. All of those transports share the same per-IP `TWIGPINE_TASK_READ_RATE_LIMIT` budget. `/api/v1/ipfs/pins` and `/api/v1/arweave/anchors` are not repository-gated; pin and anchor listings expose object and ref metadata. - Changing a repository's visibility controls future serving, but cannot retract ref metadata or configured external pins and anchors already announced while the repository was public. Do not push secrets to an announceable repository. - **Impact:** Visibility policies protect the repository and Git content routes they gate, not every metadata endpoint or previously published content. - **Remaining boundary:** This read control does not address the independent write-authorization and UCAN-delegation limitations described above. @@ -89,7 +89,7 @@ These are documented limitations of the current live release. They should be pri ### Peer route hardening rollout - Peer announce and sync notification routes accept signed requests and verify DID matches when a signature is present. - **Impact:** Unsigned peer writes are still accepted by default so existing live nodes can keep communicating during rolling upgrades. -- **Mitigation:** After all active peers run signed-node builds, operators can set `GITLAWB_REQUIRE_SIGNED_PEER_WRITES=true`. +- **Mitigation:** After all active peers run signed-node builds, operators can set `TWIGPINE_REQUIRE_SIGNED_PEER_WRITES=true`. - **Fix target:** staged rollout --- diff --git a/crates/git-remote-twigpine/Cargo.toml b/crates/git-remote-twigpine/Cargo.toml index b927f50d..b5702e2e 100644 --- a/crates/git-remote-twigpine/Cargo.toml +++ b/crates/git-remote-twigpine/Cargo.toml @@ -33,7 +33,7 @@ serde_json = { workspace = true } chrono = { workspace = true } tracing = { workspace = true } tracing-subscriber = { workspace = true } -# Home-directory lookup for the shared GITLAWB_KEY resolver in twigpine-core, +# Home-directory lookup for the shared TWIGPINE_KEY resolver in twigpine-core, # which takes `home` as an argument so core's dependency allowlist stays lean. dirs = "5" diff --git a/crates/git-remote-twigpine/src/main.rs b/crates/git-remote-twigpine/src/main.rs index 3b12ed4c..a94290fd 100644 --- a/crates/git-remote-twigpine/src/main.rs +++ b/crates/git-remote-twigpine/src/main.rs @@ -9,7 +9,7 @@ //! //! # v0.1 resolution //! DID → http://127.0.0.1:7545 (hardcoded; v0.2 will use DHT) -//! Override with: GITLAWB_NODE=http://my-node:7545 +//! Override with: TWIGPINE_NODE=http://my-node:7545 //! //! # Protocol flow (connect capability) //! capabilities → "connect\n\n" @@ -30,6 +30,10 @@ use twigpine_core::transport_policy::{allow_insecure_http_value, is_http, is_ins use twigpine_core::{resolve_transport_node, DEFAULT_LOCAL_NODE}; fn main() -> Result<()> { + // Before anything reads a setting: accept the names settings had before + // the rename. + twigpine_core::legacy_env::adopt(); + let args: Vec = std::env::args().collect(); // Handle informational flags before anything else. Git always invokes a @@ -51,9 +55,21 @@ fn main() -> Result<()> { // All logging goes to stderr so it doesn't corrupt the git protocol on stdout tracing_subscriber::fmt() .with_writer(std::io::stderr) - .with_env_filter(std::env::var("GITLAWB_LOG").unwrap_or_else(|_| "warn".to_string())) + .with_env_filter(std::env::var("TWIGPINE_LOG").unwrap_or_else(|_| "warn".to_string())) .init(); + // A setting given under both its names with different values: the + // TWIGPINE_ one is used. Worth a line here, because the value that lost + // may be a node someone passed for this one command. + let legacy = twigpine_core::legacy_env::report(); + if !legacy.conflicts.is_empty() { + tracing::warn!( + "{} set under both the TWIGPINE_ and the old GITLAWB_ name with different values; \ + using the TWIGPINE_ value", + legacy.conflicts.join(", ") + ); + } + if args.len() < 3 { eprintln!("usage: git-remote-twigpine "); eprintln!("try 'git-remote-twigpine --help' for more information"); @@ -65,7 +81,7 @@ fn main() -> Result<()> { let (_, short_owner, repo_name) = parse_gitlawb_url(url)?; - // v0.1: default to localhost. Override with GITLAWB_NODE env var. Shared with + // v0.1: default to localhost. Override with TWIGPINE_NODE env var. Shared with // `twigpine doctor` so the diagnostic reports the URL this actually resolves. let node_base = node_base_from_env(); check_transport_security(&node_base, allow_insecure_http_enabled())?; @@ -84,18 +100,18 @@ fn main() -> Result<()> { /// The node base URL this helper will contact, resolved through the same function /// `twigpine doctor` reports on so the diagnostic cannot describe a different node. fn node_base_from_env() -> String { - resolve_transport_node(std::env::var("GITLAWB_NODE").ok().as_deref()) + resolve_transport_node(std::env::var("TWIGPINE_NODE").ok().as_deref()) } -/// Fixed warning for a `GITLAWB_ALLOW_INSECURE_HTTP` value that is set but not +/// Fixed warning for a `TWIGPINE_ALLOW_INSECURE_HTTP` value that is set but not /// truthy. The raw value is never logged. fn warn_allow_insecure_http_non_truthy() { tracing::warn!( - "GITLAWB_ALLOW_INSECURE_HTTP is set but not truthy (expected 1 or true); plaintext http to a remote node remains refused" + "TWIGPINE_ALLOW_INSECURE_HTTP is set but not truthy (expected 1 or true); plaintext http to a remote node remains refused" ); } -/// Parse a possibly-present `GITLAWB_ALLOW_INSECURE_HTTP` value. +/// Parse a possibly-present `TWIGPINE_ALLOW_INSECURE_HTTP` value. /// /// Only `1` or `true` (case-insensitive, after trim) opens the gate. Presence /// alone is not consent: `=0`, `=false` and an empty value read as "not opting @@ -116,7 +132,7 @@ fn allow_insecure_http_from_str(raw: Option<&str>) -> bool { } } -/// Interpret the result of `std::env::var("GITLAWB_ALLOW_INSECURE_HTTP")` +/// Interpret the result of `std::env::var("TWIGPINE_ALLOW_INSECURE_HTTP")` /// without reading the environment again. A non-UTF-8 value fails closed and /// warns, like a present non-truthy one. fn allow_insecure_http_from_var(result: Result) -> bool { @@ -131,13 +147,13 @@ fn allow_insecure_http_from_var(result: Result) -> b } fn allow_insecure_http_enabled() -> bool { - allow_insecure_http_from_var(std::env::var("GITLAWB_ALLOW_INSECURE_HTTP")) + allow_insecure_http_from_var(std::env::var("TWIGPINE_ALLOW_INSECURE_HTTP")) } /// Refuse a cleartext hop off this machine unless the operator has opted in. /// /// Fail closed: the alternative is signing a request and then handing it, and -/// the pack it carries, to anyone on the path. `GITLAWB_ALLOW_INSECURE_HTTP` +/// the pack it carries, to anyone on the path. `TWIGPINE_ALLOW_INSECURE_HTTP` /// exists for a private LAN where the operator has decided that is acceptable. fn check_transport_security(node_base: &str, allow_insecure: bool) -> Result<()> { if allow_insecure || !is_insecure_remote(node_base) { @@ -148,7 +164,7 @@ fn check_transport_security(node_base: &str, allow_insecure: bool) -> Result<()> Requests are signed but not encrypted, so the pack contents and the \ Signature header are readable by anyone on the path, and a captured \ signature can be replayed.\n\ - Use https://, or set GITLAWB_ALLOW_INSECURE_HTTP=1 to accept the risk \ + Use https://, or set TWIGPINE_ALLOW_INSECURE_HTTP=1 to accept the risk \ (for a trusted private network only)." ) } @@ -198,12 +214,12 @@ fn help_text() -> String { \x20 git clone gitlawb://did:key:z6Mk.../\n\ \n\ ENVIRONMENT:\n\ - \x20 GITLAWB_NODE Node base URL (default: {DEFAULT_LOCAL_NODE})\n\ - \x20 GITLAWB_KEY Identity PEM path for signed fetch/push, absolute\n\ - \x20 (default: ~/.gitlawb/identity.pem). Its parent also\n\ + \x20 TWIGPINE_NODE Node base URL (default: {DEFAULT_LOCAL_NODE})\n\ + \x20 TWIGPINE_KEY Identity PEM path for signed fetch/push, absolute\n\ + \x20 (default: ~/.twigpine/identity.pem). Its parent also\n\ \x20 holds the delegations `twigpine ucan import` writes.\n\ - \x20 GITLAWB_ALLOW_INSECURE_HTTP Permit plaintext http:// to a non-loopback node (unset by default)\n\ - \x20 GITLAWB_LOG Log filter (default: warn)\n\ + \x20 TWIGPINE_ALLOW_INSECURE_HTTP Permit plaintext http:// to a non-loopback node (unset by default)\n\ + \x20 TWIGPINE_LOG Log filter (default: warn)\n\ \n\ FLAGS:\n\ \x20 -V, --version Print version and exit\n\ @@ -601,7 +617,7 @@ fn build_invocation( /// ``` /// /// Strips the KNOWN trailing `//` rather than reading the -/// first two segments, because `GITLAWB_NODE` may carry a path prefix — a +/// first two segments, because `TWIGPINE_NODE` may carry a path prefix — a /// reverse-proxied `https://host/gitlawb` is a supported base, and `repo_base` is /// built as `{node_base}/{owner}/{repo}` with the service appended after it. /// Reading from the front makes the prefix the owner, which fails the delegation @@ -1219,7 +1235,16 @@ fn safe_error_body_excerpt(body: &str) -> String { fn load_keypair() -> Option { let key_path = resolve_key_path()?; if !key_path.exists() { - tracing::debug!("no keypair found at {key_path:?}"); + // Unsigned from here on. If the key is sitting in the folder from + // before the rename, say so: the push will be refused and nothing + // else would explain why. + match twigpine_core::identity_path::stranded_legacy_key(&key_path, home_dir().as_deref()) { + Some(legacy) => tracing::warn!( + "{}", + twigpine_core::identity_path::stranded_legacy_key_message(&key_path, &legacy) + ), + None => tracing::debug!("no keypair found at {key_path:?}"), + } return None; } match std::fs::read_to_string(&key_path) { @@ -1243,7 +1268,7 @@ fn load_keypair() -> Option { /// The identity PEM, resolved by the same rules `twigpine` uses. /// /// Shared through `twigpine-core` rather than reimplemented here: this helper and -/// `twigpine ucan import` have to derive the same delegation store from `GITLAWB_KEY`, +/// `twigpine ucan import` have to derive the same delegation store from `TWIGPINE_KEY`, /// and the two had drifted — the local version read `env::var` (so a non-UTF-8 /// value silently became the default key), expanded only a literal `"~/"`, fell /// back to `"."` when `HOME` was unset, and never required an absolute path. @@ -1268,7 +1293,7 @@ fn resolve_identity_dir() -> Option { /// which on Windows is always, so the default key resolved against whatever /// directory git happened to invoke the helper from. /// -/// `None` is not fatal — an absolute `GITLAWB_KEY` resolves without it, and only +/// `None` is not fatal — an absolute `TWIGPINE_KEY` resolves without it, and only /// the default and `~/`-prefixed forms need a home at all. fn home_dir() -> Option { dirs::home_dir() @@ -1379,7 +1404,7 @@ mod insecure_transport_tests { "the refusal must say why: {msg}" ); assert!( - msg.contains("GITLAWB_ALLOW_INSECURE_HTTP"), + msg.contains("TWIGPINE_ALLOW_INSECURE_HTTP"), "the refusal must name the escape hatch: {msg}" ); @@ -1432,7 +1457,7 @@ mod insecure_transport_tests { /// discover reads as a broken transport rather than a deliberate refusal. #[test] fn help_documents_the_opt_in() { - assert!(help_text().contains("GITLAWB_ALLOW_INSECURE_HTTP")); + assert!(help_text().contains("TWIGPINE_ALLOW_INSECURE_HTTP")); } /// An unparseable or non-http value is not classified as insecure here: it @@ -2008,7 +2033,7 @@ mod tests { .create(); let post_url = format!("{repo_base}/{service}"); // `build_pack_post_request` reaches `delegation_header`, whose store - // resolves from process-global `GITLAWB_KEY`. Point it at an empty dir + // resolves from process-global `TWIGPINE_KEY`. Point it at an empty dir // under the shared lock so the read cannot race a sibling's mutation // and cannot pick up a developer's real store. let req = crate::delegated_push_tests::with_identity_dir(empty.path(), || { @@ -2646,7 +2671,7 @@ mod tests { assert!(help.starts_with(&version_line())); assert!(help.contains("--version")); assert!(help.contains("--help")); - assert!(help.contains("GITLAWB_NODE")); + assert!(help.contains("TWIGPINE_NODE")); // The advertised default must be the value the helper actually resolves. assert!(help.contains(DEFAULT_LOCAL_NODE)); assert!(help.ends_with('\n')); @@ -2657,7 +2682,7 @@ mod tests { #[test] fn node_base_matches_the_shared_resolver() { // No env manipulation: assert the call site delegates, for the default case. - let expected = resolve_transport_node(std::env::var("GITLAWB_NODE").ok().as_deref()); + let expected = resolve_transport_node(std::env::var("TWIGPINE_NODE").ok().as_deref()); assert_eq!(node_base_from_env(), expected); assert_eq!(resolve_transport_node(None), DEFAULT_LOCAL_NODE); } @@ -3723,7 +3748,7 @@ mod delegated_push_tests { )), "the origin must come back intact so the node DID can be fetched from it" ); - // A reverse-proxied GITLAWB_NODE carries a path prefix, which survives into + // A reverse-proxied TWIGPINE_NODE carries a path prefix, which survives into // the pack URL through `repo_base`. Reading the FIRST two segments as // owner/repo makes the prefix the owner: the delegation lookup misses, the // DID probe hits the wrong URL, no X-Ucan is sent, and a valid delegate is @@ -3794,13 +3819,13 @@ mod delegated_push_tests { // just stops attaching `X-Ucan` and the delegate starts getting 403s with no // local explanation. - /// `delegation_header` resolves its store from `GITLAWB_KEY`, which is + /// `delegation_header` resolves its store from `TWIGPINE_KEY`, which is /// process-global. Every test that sets it, and every test that reaches the /// resolver, takes this lock. `pub(crate)` so `tests::` cases that reach the /// resolver without setting the variable can serialize their read too. pub(crate) static KEY_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); - /// Point `GITLAWB_KEY` at `dir/identity.pem` for the duration of `f`, so the + /// Point `TWIGPINE_KEY` at `dir/identity.pem` for the duration of `f`, so the /// delegation store resolves to `dir/delegations`. The restore runs on drop: /// a panic inside `f` cannot leak the tempdir path into later tests. pub(crate) fn with_identity_dir(dir: &std::path::Path, f: impl FnOnce() -> T) -> T { @@ -3808,14 +3833,14 @@ mod delegated_push_tests { impl Drop for Restore { fn drop(&mut self) { match self.0.take() { - Some(v) => std::env::set_var("GITLAWB_KEY", v), - None => std::env::remove_var("GITLAWB_KEY"), + Some(v) => std::env::set_var("TWIGPINE_KEY", v), + None => std::env::remove_var("TWIGPINE_KEY"), } } } let _guard = KEY_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); - let _restore = Restore(std::env::var_os("GITLAWB_KEY")); - std::env::set_var("GITLAWB_KEY", dir.join("identity.pem")); + let _restore = Restore(std::env::var_os("TWIGPINE_KEY")); + std::env::set_var("TWIGPINE_KEY", dir.join("identity.pem")); f() } @@ -4109,7 +4134,7 @@ mod delegated_push_tests { } } - /// A reverse-proxied `GITLAWB_NODE` carries a path prefix, and that prefix + /// A reverse-proxied `TWIGPINE_NODE` carries a path prefix, and that prefix /// survives into the pack URL. `split_pack_post_url` is unit-tested for it, but /// nothing checked that the probe actually goes to the prefixed base — a /// regression there would GET `/` on the proxy host, read whatever landing page diff --git a/crates/git-remote-twigpine/tests/real_git_fetch.rs b/crates/git-remote-twigpine/tests/real_git_fetch.rs index f55c4170..ef8c5f25 100644 --- a/crates/git-remote-twigpine/tests/real_git_fetch.rs +++ b/crates/git-remote-twigpine/tests/real_git_fetch.rs @@ -357,11 +357,12 @@ fn fetch_with_helper_env( // test, e.g. `expected ACK/NAK`) are the untranslated English strings on a // machine/CI with git-l10n installed and LANG set to a translated locale. .env("LC_ALL", "C") - .env("GITLAWB_NODE", node_url) - .env("GITLAWB_KEY", "/nonexistent-key-for-anon-fetch") + .env("TWIGPINE_NODE", node_url) + .env("TWIGPINE_KEY", "/nonexistent-key-for-anon-fetch") // The helper inherits this process's environment, so an operator or CI // that exports the insecure-HTTP override would decide the transport // policy for every test below. Clear it and let each test opt in. + .env_remove("TWIGPINE_ALLOW_INSECURE_HTTP") .env_remove("GITLAWB_ALLOW_INSECURE_HTTP"); for (k, v) in extra_env { cmd.env(k, v); @@ -393,8 +394,9 @@ fn push_with_helper(local: &Path, node_url: &str, args: &[&str]) -> (bool, std:: .args(args) .env("PATH", path_env) .env("LC_ALL", "C") - .env("GITLAWB_NODE", node_url) - .env("GITLAWB_KEY", "/nonexistent-key-for-anon-push") + .env("TWIGPINE_NODE", node_url) + .env("TWIGPINE_KEY", "/nonexistent-key-for-anon-push") + .env_remove("TWIGPINE_ALLOW_INSECURE_HTTP") .env_remove("GITLAWB_ALLOW_INSECURE_HTTP"); run_bounded(cmd, Duration::from_secs(30)) } @@ -1399,12 +1401,12 @@ fn real_git_fetch_refuses_a_remote_plaintext_node() { "the helper must refuse the cleartext hop and say so; stderr was: {stderr}" ); assert!( - stderr.contains("GITLAWB_ALLOW_INSECURE_HTTP"), + stderr.contains("TWIGPINE_ALLOW_INSECURE_HTTP"), "the refusal must name the escape hatch; stderr was: {stderr}" ); } -/// The opt-in is read as a value, not as presence. `GITLAWB_ALLOW_INSECURE_HTTP` +/// The opt-in is read as a value, not as presence. `TWIGPINE_ALLOW_INSECURE_HTTP` /// set to `0`, `false`, empty or a misspelling must leave the gate closed: the /// README and the refusal message both tell the operator to set it to `1`, so /// anything else reads as "not opting in". Drives the built binary because the @@ -1416,18 +1418,18 @@ fn real_git_fetch_still_refuses_a_remote_plaintext_node_when_override_is_not_tru let (ok, out) = fetch_with_helper_env( &repos.clone, "http://192.0.2.1:7545", - &[("GITLAWB_ALLOW_INSECURE_HTTP", value)], + &[("TWIGPINE_ALLOW_INSECURE_HTTP", value)], ); let stderr = String::from_utf8_lossy(&out.stderr); assert!( !ok || !out.status.success(), - "GITLAWB_ALLOW_INSECURE_HTTP={value:?} must not permit a remote plaintext node: {stderr}" + "TWIGPINE_ALLOW_INSECURE_HTTP={value:?} must not permit a remote plaintext node: {stderr}" ); // The not-truthy warning also says "plaintext http", so match the text // only the refusal itself emits. assert!( stderr.contains("refusing to send git data"), - "GITLAWB_ALLOW_INSECURE_HTTP={value:?} must leave the gate refusing; stderr was: {stderr}" + "TWIGPINE_ALLOW_INSECURE_HTTP={value:?} must leave the gate refusing; stderr was: {stderr}" ); } } diff --git a/crates/icaptcha-client/src/lib.rs b/crates/icaptcha-client/src/lib.rs index 6130ed1e..845eeb83 100644 --- a/crates/icaptcha-client/src/lib.rs +++ b/crates/icaptcha-client/src/lib.rs @@ -88,7 +88,7 @@ fn sanitize_excerpt(s: &str) -> String { out } -/// Fixed warning when `GITLAWB_ICAPTCHA_INSECURE` is present but not an +/// Fixed warning when `TWIGPINE_ICAPTCHA_INSECURE` is present but not an /// explicit truthy value. Does not include the raw env value (arbitrary /// deployment input — secrets / terminal controls). fn warn_icaptcha_insecure_non_truthy() { @@ -97,11 +97,11 @@ fn warn_icaptcha_insecure_non_truthy() { // single-line form makes that property visible without knowing the escape // semantics, which is what the review asked for. tracing::warn!( - "GITLAWB_ICAPTCHA_INSECURE is set but not truthy (expected 1 or true); loopback HTTP trust relaxation remains disabled" + "TWIGPINE_ICAPTCHA_INSECURE is set but not truthy (expected 1 or true); loopback HTTP trust relaxation remains disabled" ); } -/// Parse a possibly-present `GITLAWB_ICAPTCHA_INSECURE` string. +/// Parse a possibly-present `TWIGPINE_ICAPTCHA_INSECURE` string. /// /// Only an explicit truthy value (`1` / `true`, case-insensitive, after trim) /// enables the loopback-HTTP trust relaxation. Presence alone is not enough: @@ -122,7 +122,7 @@ fn icaptcha_insecure_from_str(raw: Option<&str>) -> bool { } } -/// Interpret `std::env::var("GITLAWB_ICAPTCHA_INSECURE")` without reading the +/// Interpret `std::env::var("TWIGPINE_ICAPTCHA_INSECURE")` without reading the /// environment again — used by production and by unit tests. /// /// `NotPresent` → disabled. `NotUnicode` → disabled + the same fixed warning @@ -138,7 +138,7 @@ fn icaptcha_insecure_from_var(result: Result) -> boo } } -/// Whether `GITLAWB_ICAPTCHA_INSECURE` explicitly enables the loopback-HTTP +/// Whether `TWIGPINE_ICAPTCHA_INSECURE` explicitly enables the loopback-HTTP /// trust relaxation used by integration tests. /// /// Only an explicit truthy value (`1` / `true`, case-insensitive, after trim) @@ -147,7 +147,7 @@ fn icaptcha_insecure_from_var(result: Result) -> boo /// present non-Unicode value) emits a `tracing::warn!` (visible when the /// `icaptcha_client` target is at WARN+, e.g. `RUST_LOG=icaptcha_client=warn`). fn icaptcha_insecure_enabled() -> bool { - icaptcha_insecure_from_var(std::env::var("GITLAWB_ICAPTCHA_INSECURE")) + icaptcha_insecure_from_var(std::env::var("TWIGPINE_ICAPTCHA_INSECURE")) } /// Whether `u` parses as a trusted URL, given a pre-parsed insecure flag. @@ -194,7 +194,7 @@ fn origin_key(u: &str) -> Option { /// it at an attacker origin (client-side SSRF) or capture a bearer token on the /// first hop. So an advertised URL is honored only when it is `https` AND its /// host is allowlisted — the public default host, or the operator's own -/// `GITLAWB_ICAPTCHA_URL`. Otherwise we fall back to the operator/default origin. +/// `TWIGPINE_ICAPTCHA_URL`. Otherwise we fall back to the operator/default origin. /// /// The API key is attached only when the resolved origin is the operator's /// explicitly-configured host (never a node-discovered one), so a key is never @@ -268,16 +268,16 @@ impl IcaptchaCfg { /// /// The advertised URL is validated and allowlisted (see [`resolve_solver_url`]) /// so a hostile node cannot redirect the solve to an attacker origin. The - /// `GITLAWB_ICAPTCHA_API_KEY` bearer token is attached only when the resolved - /// origin is the operator's own `GITLAWB_ICAPTCHA_URL`, never a + /// `TWIGPINE_ICAPTCHA_API_KEY` bearer token is attached only when the resolved + /// origin is the operator's own `TWIGPINE_ICAPTCHA_URL`, never a /// node-discovered one. pub fn new(did: impl Into, url: Option, level: Option) -> Self { - let operator = std::env::var("GITLAWB_ICAPTCHA_URL") + let operator = std::env::var("TWIGPINE_ICAPTCHA_URL") .ok() .filter(|s| !s.is_empty()); let (resolved_url, key_trusted) = resolve_solver_url(url.as_deref(), operator.as_deref()); let api_key = if key_trusted { - std::env::var("GITLAWB_ICAPTCHA_API_KEY") + std::env::var("TWIGPINE_ICAPTCHA_API_KEY") .ok() .filter(|s| !s.is_empty()) } else { @@ -337,7 +337,7 @@ pub fn obtain_proof(cfg: &IcaptchaCfg, solver: Option<&Solver>) -> Result Self { let lock = Self::lock(); - let prev = std::env::var_os("GITLAWB_ICAPTCHA_INSECURE"); - std::env::set_var("GITLAWB_ICAPTCHA_INSECURE", val); + let prev = std::env::var_os("TWIGPINE_ICAPTCHA_INSECURE"); + std::env::set_var("TWIGPINE_ICAPTCHA_INSECURE", val); EnvGuard { _lock: lock, prev } } fn unset() -> Self { let lock = Self::lock(); - let prev = std::env::var_os("GITLAWB_ICAPTCHA_INSECURE"); - std::env::remove_var("GITLAWB_ICAPTCHA_INSECURE"); + let prev = std::env::var_os("TWIGPINE_ICAPTCHA_INSECURE"); + std::env::remove_var("TWIGPINE_ICAPTCHA_INSECURE"); EnvGuard { _lock: lock, prev } } } @@ -490,8 +490,8 @@ mod tests { impl Drop for EnvGuard { fn drop(&mut self) { match self.prev.take() { - Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_INSECURE", v), - None => std::env::remove_var("GITLAWB_ICAPTCHA_INSECURE"), + Some(v) => std::env::set_var("TWIGPINE_ICAPTCHA_INSECURE", v), + None => std::env::remove_var("TWIGPINE_ICAPTCHA_INSECURE"), } } } @@ -749,13 +749,13 @@ mod tests { #[test] fn new_withholds_key_from_untrusted_origin_but_attaches_for_operator() { let guard = ICAPTCHA_ENV_LOCK.lock().unwrap(); - let prev_key = std::env::var_os("GITLAWB_ICAPTCHA_API_KEY"); - let prev_op = std::env::var_os("GITLAWB_ICAPTCHA_URL"); - std::env::set_var("GITLAWB_ICAPTCHA_API_KEY", "secret-bearer"); + let prev_key = std::env::var_os("TWIGPINE_ICAPTCHA_API_KEY"); + let prev_op = std::env::var_os("TWIGPINE_ICAPTCHA_URL"); + std::env::set_var("TWIGPINE_ICAPTCHA_API_KEY", "secret-bearer"); // Arm 1: No operator configured, node advertises an attacker origin. // The key has no trusted destination; the advert is rejected. - std::env::remove_var("GITLAWB_ICAPTCHA_URL"); + std::env::remove_var("TWIGPINE_ICAPTCHA_URL"); let untrusted = IcaptchaCfg::new("did:key:zTEST", Some("https://evil.example".into()), None); @@ -765,7 +765,7 @@ mod tests { let no_operator_no_advert = IcaptchaCfg::new("did:key:zTEST", None, None); // Arm 2: Operator origin configured and advertised — key attached. - std::env::set_var("GITLAWB_ICAPTCHA_URL", "https://icap.mynode.example"); + std::env::set_var("TWIGPINE_ICAPTCHA_URL", "https://icap.mynode.example"); let operator_match = IcaptchaCfg::new( "did:key:zTEST", Some("https://icap.mynode.example/v1".into()), @@ -811,12 +811,12 @@ mod tests { // Restore env and release the lock BEFORE asserting, so a failing // assertion can't poison the shared lock or cascade into a sibling. match prev_key { - Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_API_KEY", v), - None => std::env::remove_var("GITLAWB_ICAPTCHA_API_KEY"), + Some(v) => std::env::set_var("TWIGPINE_ICAPTCHA_API_KEY", v), + None => std::env::remove_var("TWIGPINE_ICAPTCHA_API_KEY"), } match prev_op { - Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_URL", v), - None => std::env::remove_var("GITLAWB_ICAPTCHA_URL"), + Some(v) => std::env::set_var("TWIGPINE_ICAPTCHA_URL", v), + None => std::env::remove_var("TWIGPINE_ICAPTCHA_URL"), } drop(guard); @@ -919,40 +919,40 @@ mod tests { #[test] fn new_normalizes_empty_api_key_to_none_on_trusted_origin() { let guard = ICAPTCHA_ENV_LOCK.lock().unwrap(); - let prev_key = std::env::var_os("GITLAWB_ICAPTCHA_API_KEY"); - let prev_op = std::env::var_os("GITLAWB_ICAPTCHA_URL"); + let prev_key = std::env::var_os("TWIGPINE_ICAPTCHA_API_KEY"); + let prev_op = std::env::var_os("TWIGPINE_ICAPTCHA_URL"); // Operator origin configured and resolved as trusted (no advert), so // api_key reaches the env read and the emptiness filter is the only // thing standing between a blank var and an empty bearer token. - std::env::set_var("GITLAWB_ICAPTCHA_URL", "https://icap.mynode.example"); + std::env::set_var("TWIGPINE_ICAPTCHA_URL", "https://icap.mynode.example"); // "Operator set the var but left it blank" must stay keyless: a // Some("") would attach `Authorization: Bearer ` (empty token) to the // challenge and answer requests instead of omitting the header. - std::env::set_var("GITLAWB_ICAPTCHA_API_KEY", ""); + std::env::set_var("TWIGPINE_ICAPTCHA_API_KEY", ""); let empty = IcaptchaCfg::new("did:key:zTEST", None, None); // Contrast arm: a real key on the same trusted path must survive the // filter, so the filter can't regress to dropping every key. - std::env::set_var("GITLAWB_ICAPTCHA_API_KEY", "secret-bearer"); + std::env::set_var("TWIGPINE_ICAPTCHA_API_KEY", "secret-bearer"); let non_empty = IcaptchaCfg::new("did:key:zTEST", None, None); // Restore env and release the lock BEFORE asserting, so a failing // assertion can't poison the shared lock or cascade into a sibling. match prev_key { - Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_API_KEY", v), - None => std::env::remove_var("GITLAWB_ICAPTCHA_API_KEY"), + Some(v) => std::env::set_var("TWIGPINE_ICAPTCHA_API_KEY", v), + None => std::env::remove_var("TWIGPINE_ICAPTCHA_API_KEY"), } match prev_op { - Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_URL", v), - None => std::env::remove_var("GITLAWB_ICAPTCHA_URL"), + Some(v) => std::env::set_var("TWIGPINE_ICAPTCHA_URL", v), + None => std::env::remove_var("TWIGPINE_ICAPTCHA_URL"), } drop(guard); assert_eq!( empty.api_key, None, - "empty GITLAWB_ICAPTCHA_API_KEY must normalize to None" + "empty TWIGPINE_ICAPTCHA_API_KEY must normalize to None" ); assert_eq!(non_empty.api_key.as_deref(), Some("secret-bearer")); } diff --git a/crates/twigpine-cli/src/agent.rs b/crates/twigpine-cli/src/agent.rs index d198871a..7e07b00b 100644 --- a/crates/twigpine-cli/src/agent.rs +++ b/crates/twigpine-cli/src/agent.rs @@ -19,7 +19,7 @@ pub enum AgentCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, /// Filter by capability (e.g. git:push) @@ -35,7 +35,7 @@ pub enum AgentCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, }, @@ -69,7 +69,7 @@ async fn cmd_list(node: String, capability: Option) -> Result<()> { if resp.status() == reqwest::StatusCode::NOT_FOUND { anyhow::bail!( "this node does not yet support the agents API (v0.3+)\n\ - upgrade the node or check GITLAWB_NODE is pointing to the right server" + upgrade the node or check TWIGPINE_NODE is pointing to the right server" ); } @@ -120,7 +120,7 @@ async fn cmd_show(did: String, node: String) -> Result<()> { if resp.status() == reqwest::StatusCode::NOT_FOUND { anyhow::bail!( "agent not found, or this node does not yet support the agents API (v0.3+)\n\ - upgrade the node or check GITLAWB_NODE is pointing to the right server" + upgrade the node or check TWIGPINE_NODE is pointing to the right server" ); } diff --git a/crates/twigpine-cli/src/bounty.rs b/crates/twigpine-cli/src/bounty.rs index eca52a4a..aea3ec87 100644 --- a/crates/twigpine-cli/src/bounty.rs +++ b/crates/twigpine-cli/src/bounty.rs @@ -41,7 +41,7 @@ pub enum BountyCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -57,7 +57,7 @@ pub enum BountyCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -70,7 +70,7 @@ pub enum BountyCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -86,7 +86,7 @@ pub enum BountyCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -102,7 +102,7 @@ pub enum BountyCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -118,7 +118,7 @@ pub enum BountyCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -131,7 +131,7 @@ pub enum BountyCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -142,7 +142,7 @@ pub enum BountyCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, }, diff --git a/crates/twigpine-cli/src/cert.rs b/crates/twigpine-cli/src/cert.rs index d98dea5a..44e10e8c 100644 --- a/crates/twigpine-cli/src/cert.rs +++ b/crates/twigpine-cli/src/cert.rs @@ -29,7 +29,7 @@ pub enum CertCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -49,7 +49,7 @@ pub enum CertCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] diff --git a/crates/twigpine-cli/src/changelog.rs b/crates/twigpine-cli/src/changelog.rs index d72af83c..4e3d71ec 100644 --- a/crates/twigpine-cli/src/changelog.rs +++ b/crates/twigpine-cli/src/changelog.rs @@ -17,7 +17,7 @@ pub struct ChangelogArgs { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] pub node: String, #[arg(long)] diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index 1c1a6314..994870a8 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -79,7 +79,7 @@ pub struct CloneArgs { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] pub node: String, @@ -88,7 +88,7 @@ pub struct CloneArgs { #[arg( long, default_value = "https://arweave.net", - env = "GITLAWB_ARWEAVE_GATEWAY" + env = "TWIGPINE_ARWEAVE_GATEWAY" )] pub arweave_gateway: String, @@ -96,7 +96,7 @@ pub struct CloneArgs { #[arg( long, default_value = "https://dweb.link", - env = "GITLAWB_IPFS_GATEWAY" + env = "TWIGPINE_IPFS_GATEWAY" )] pub ipfs_gateway: String, } diff --git a/crates/twigpine-cli/src/doctor.rs b/crates/twigpine-cli/src/doctor.rs index 7db7b3f2..a6286a93 100644 --- a/crates/twigpine-cli/src/doctor.rs +++ b/crates/twigpine-cli/src/doctor.rs @@ -1,10 +1,10 @@ //! `twigpine doctor` — check your Twigpine installation and connectivity. //! //! Checks: -//! 1. Identity — ~/.gitlawb/identity.pem exists, DID parseable -//! 2. Registration — ~/.gitlawb/ucan.json exists (registered with a node) -//! 3. GITLAWB_NODE — env var points at a public node (unset is advisory) -//! 4. Node — GITLAWB_NODE is reachable (default: https://node.twigpine.com) +//! 1. Identity — ~/.twigpine/identity.pem exists, DID parseable +//! 2. Registration — ~/.twigpine/ucan.json exists (registered with a node) +//! 3. TWIGPINE_NODE — env var points at a public node (unset is advisory) +//! 4. Node — TWIGPINE_NODE is reachable (default: https://node.twigpine.com) //! 5. git helper — git-remote-gitlawb (the name git runs) is in PATH //! 6. git — git is installed //! 7. version — twigpine is up to date with latest GitHub release @@ -24,10 +24,10 @@ const GITHUB_API_BASE: &str = "https://api.github.com"; #[derive(Args)] pub struct DoctorArgs { /// Node URL to check connectivity against - #[arg(long, default_value = PUBLIC_NODE, env = "GITLAWB_NODE")] + #[arg(long, default_value = PUBLIC_NODE, env = "TWIGPINE_NODE")] pub node: String, - /// Identity directory (default: the parent of $GITLAWB_KEY, else ~/.gitlawb) + /// Identity directory (default: the parent of $TWIGPINE_KEY, else ~/.twigpine) #[arg(long)] pub dir: Option, } @@ -73,13 +73,13 @@ impl Check { } /// Resolve the config dir and key path without aborting on a refused resolver. -/// The whole point of doctor is to explain a broken setup, so a `GITLAWB_KEY` +/// The whole point of doctor is to explain a broken setup, so a `TWIGPINE_KEY` /// or `--dir` the resolvers reject becomes `Check::fail` rows for the checks /// that depend on them, while node/git checks still run. fn resolve_config_paths( args_dir: Option, ) -> (Option, Option, Vec) { - let dir = crate::identity::gitlawb_dir(args_dir.clone()); + let dir = crate::identity::identity_dir(args_dir.clone()); let mut checks = Vec::new(); let dir = match dir { Ok(d) => Some(d), @@ -87,12 +87,12 @@ fn resolve_config_paths( checks.push(Check::fail( "identity", format!("could not resolve config dir: {e}"), - "fix GITLAWB_KEY or --dir", + "fix TWIGPINE_KEY or --dir", )); checks.push(Check::fail( "registration", "skipped: config dir unresolved", - "fix GITLAWB_KEY or --dir", + "fix TWIGPINE_KEY or --dir", )); None } @@ -104,7 +104,7 @@ fn resolve_config_paths( checks.push(Check::fail( "identity", format!("could not resolve key path: {e}"), - "fix GITLAWB_KEY or --dir", + "fix TWIGPINE_KEY or --dir", )); } None @@ -118,7 +118,7 @@ pub async fn run(args: DoctorArgs) -> Result<()> { println!(); // The same resolver every other command uses. `doctor` reporting on - // `~/.gitlawb` while `twigpine register` writes to the parent of `GITLAWB_KEY` would + // `~/.twigpine` while `twigpine register` writes to the parent of `TWIGPINE_KEY` would // make the one command whose job is to explain a broken setup the one that // misreports it. let args_dir = args.dir.clone(); @@ -146,11 +146,25 @@ pub async fn run(args: DoctorArgs) -> Result<()> { } } } else if let Some(pem_path) = &pem_path { - checks.push(Check::fail( - "identity", - format!("not found at {}", pem_path.display()), - "twigpine identity new", - )); + let home = dirs::home_dir(); + match twigpine_core::identity_path::stranded_legacy_key(pem_path, home.as_deref()) { + // The key is in the folder from before the rename. "identity new" + // would be the wrong advice: it means a second identity. + Some(legacy) => checks.push(Check::fail( + "identity", + format!( + "not found at {}, but there is one at {}", + pem_path.display(), + legacy.display() + ), + twigpine_core::identity_path::stranded_legacy_key_message(pem_path, &legacy), + )), + None => checks.push(Check::fail( + "identity", + format!("not found at {}", pem_path.display()), + "twigpine identity new", + )), + } } // ── 2. Registration ─────────────────────────────────────────────────── @@ -185,14 +199,14 @@ pub async fn run(args: DoctorArgs) -> Result<()> { } } - // ── 3. GITLAWB_NODE env var ─────────────────────────────────────────── + // ── 3. TWIGPINE_NODE env var ─────────────────────────────────────────── // The node `git clone` / `git push` will contact is not always the node `twigpine` // contacts: `--node` defaults to the public node and an explicit flag outranks // the environment, so the two diverge whenever the variable is unset, blank, or // overridden. Probing only `twigpine`'s node is what let doctor greenlight an install // whose transport was dead, so resolve the transport's node through the same // function the helper uses and report on that one. - let env_node = std::env::var("GITLAWB_NODE").ok(); + let env_node = std::env::var("TWIGPINE_NODE").ok(); let transport_node = resolve_transport_node(env_node.as_deref()); let gl_node = sanitize_node_msg(&args.node); @@ -201,7 +215,7 @@ pub async fn run(args: DoctorArgs) -> Result<()> { if transport_node == args.node.trim() { // twigpine and the transport agree, so one row covers both. Classify the row from // the variable itself: `--node` matching the transport default does not mean - // the user set `GITLAWB_NODE`. + // the user set `TWIGPINE_NODE`. let env_val = env_node .as_deref() .map(str::trim) @@ -219,7 +233,7 @@ pub async fn run(args: DoctorArgs) -> Result<()> { // quoted for the shell. The display string above is capped and stripped for // the terminal, which is a different encoding and must not be reused here. let fix = format!( - "export GITLAWB_NODE={}", + "export TWIGPINE_NODE={}", shell_single_quote(&recovery_target(&args.node)) ); // Tiering follows who chose the broken value. An unset variable on a stock @@ -231,14 +245,14 @@ pub async fn run(args: DoctorArgs) -> Result<()> { .map(str::trim) .is_some_and(|v| !v.is_empty()); if verdict.usable || !env_was_set { - checks.push(Check::warn("GITLAWB_NODE", detail, fix)); + checks.push(Check::warn("TWIGPINE_NODE", detail, fix)); } else { - checks.push(Check::fail("GITLAWB_NODE", detail, fix)); + checks.push(Check::fail("TWIGPINE_NODE", detail, fix)); } } // ── 4. Node connectivity ────────────────────────────────────────────── - // GITLAWB_NODE="" binds args.node to "" through clap, and check 3 groups + // TWIGPINE_NODE="" binds args.node to "" through clap, and check 3 groups // empty with unset. The probe must apply the same normalization or it // would dial "" and Fail while the env row only Warns. let node_url = effective_node_url(&args.node); @@ -271,14 +285,14 @@ pub async fn run(args: DoctorArgs) -> Result<()> { checks.push(Check::fail( "node", format!("{} returned HTTP {}", node_url, resp.status()), - "check GITLAWB_NODE env var or try twigpine register --node ", + "check TWIGPINE_NODE env var or try twigpine register --node ", )); } Err(e) => { checks.push(Check::fail( "node", format!("{} unreachable: {e}", node_url), - "check your internet connection or set GITLAWB_NODE", + "check your internet connection or set TWIGPINE_NODE", )); } } @@ -286,7 +300,7 @@ pub async fn run(args: DoctorArgs) -> Result<()> { // ── 4b. iCaptcha capability ─────────────────────────────────────────── // Gated writes (repo create / register / fork) auto-solve a challenge at the // iCaptcha service; check it's reachable so the failure mode is obvious. - let icaptcha_url = std::env::var("GITLAWB_ICAPTCHA_URL") + let icaptcha_url = std::env::var("TWIGPINE_ICAPTCHA_URL") .unwrap_or_else(|_| icaptcha_client::DEFAULT_URL.to_string()); match NodeClient::new(&icaptcha_url, None).get("/v1/pubkey").await { Ok(resp) if resp.status().is_success() => { @@ -303,7 +317,7 @@ pub async fn run(args: DoctorArgs) -> Result<()> { checks.push(Check::warn( "iCaptcha", format!("{icaptcha_url} unreachable: {e}"), - "set GITLAWB_ICAPTCHA_URL or check connectivity — repo create / register solve a challenge there", + "set TWIGPINE_ICAPTCHA_URL or check connectivity — repo create / register solve a challenge there", )); } } @@ -347,12 +361,18 @@ pub async fn run(args: DoctorArgs) -> Result<()> { let current = env!("CARGO_PKG_VERSION"); // Production uses the real endpoint; the override exists so the subprocess tests // can route the release lookup to a local fixture instead of the public API. - let github_api = std::env::var("GITLAWB_GITHUB_API_URL") + let github_api = std::env::var("TWIGPINE_GITHUB_API_URL") .ok() .filter(|v| !v.trim().is_empty()) .unwrap_or_else(|| GITHUB_API_BASE.to_string()); checks.push(check_version(current, &github_api).await); + // Settings still given under their names from before the rename. They + // work; this row only appears when there is something to update. + if let Some(check) = legacy_settings_check(&twigpine_core::legacy_env::report()) { + checks.push(check); + } + // ── Render ──────────────────────────────────────────────────────────── for check in &checks { let icon = match check.state { @@ -440,7 +460,7 @@ fn recovery_target(node: &str) -> String { /// /// This models the git helper, so it takes the helper's transport policy: a /// plaintext http node off this machine is refused without a request unless -/// `GITLAWB_ALLOW_INSECURE_HTTP` opts in; a loopback http node is dialed directly, +/// `TWIGPINE_ALLOW_INSECURE_HTTP` opts in; a loopback http node is dialed directly, /// never through a proxy; every other node uses reqwest's default environment proxy /// discovery, as the helper does; redirects follow the shared same-origin decision /// and chain bound; and the identity must parse as a DID, which the helper requires @@ -448,13 +468,13 @@ fn recovery_target(node: &str) -> String { /// must not inherit the 30s request timeout, which stalls every stock `twigpine doctor` /// run behind a hung listener, and it sends no credentials. async fn probe_transport(url: &str) -> TransportVerdict { - let allow_insecure = std::env::var("GITLAWB_ALLOW_INSECURE_HTTP") + let allow_insecure = std::env::var("TWIGPINE_ALLOW_INSECURE_HTTP") .is_ok_and(|v| transport_policy::allow_insecure_http_value(&v)); if !allow_insecure && transport_policy::is_insecure_remote(url) { return TransportVerdict { usable: false, detail: "refused: plaintext http to a remote node (use https://, or set \ - GITLAWB_ALLOW_INSECURE_HTTP=1 for a trusted private network)" + TWIGPINE_ALLOW_INSECURE_HTTP=1 for a trusted private network)" .to_string(), }; } @@ -519,7 +539,7 @@ async fn probe_transport(url: &str) -> TransportVerdict { } } -/// Classify the `GITLAWB_NODE` env var for `twigpine doctor`. Extracted so unit +/// Classify the `TWIGPINE_NODE` env var for `twigpine doctor`. Extracted so unit /// tests can pin the Warn tier directly (#357): an unset env is advisory, not /// a failure, because `--node` defaults to `https://node.twigpine.com` and the /// CLI works without it. Flipping this back to `Check::fail` must break a @@ -530,12 +550,12 @@ fn gitlawb_node_env_check(env_val: Option<&str>) -> Check { // harness) — the connectivity check below fails loudly if it is not // actually reachable, so don't red-flag the configuration itself. Some(v) if is_loopback_url(v) => Check::pass( - "GITLAWB_NODE", + "TWIGPINE_NODE", format!( "{v} (local node — intentional for self-hosting/dev; unset to target the public network)" ), ), - Some(v) if !v.is_empty() => Check::pass("GITLAWB_NODE", v.to_string()), + Some(v) if !v.is_empty() => Check::pass("TWIGPINE_NODE", v.to_string()), // `--node` defaults to `https://node.twigpine.com` and the CLI works // fine without the variable, so an unset env is advisory, not a // failure. Warn-class keeps the exit code 0 for a stock working @@ -543,14 +563,14 @@ fn gitlawb_node_env_check(env_val: Option<&str>) -> Check { // on any failure" change would have flipped to exit 1 on every // default-config install (#357). _ => Check::warn( - "GITLAWB_NODE", + "TWIGPINE_NODE", "not set — git-remote-twigpine will fall back to http://127.0.0.1:7545", - format!("export GITLAWB_NODE={PUBLIC_NODE}"), + format!("export TWIGPINE_NODE={PUBLIC_NODE}"), ), } } -/// The URL the connectivity probe should dial. `GITLAWB_NODE` set but empty +/// The URL the connectivity probe should dial. `TWIGPINE_NODE` set but empty /// (or whitespace-only) binds `args.node` to `""` through clap rather than /// to the `default_value`, and check 3 already groups empty with unset, so /// the probe applies the same normalization: an empty effective URL means @@ -564,7 +584,7 @@ fn effective_node_url(node: &str) -> &str { } /// True when at least one check is Fail-class. Warn-only runs (iCaptcha offline, -/// version drift, GITLAWB_NODE unset) keep exit 0; +/// version drift, TWIGPINE_NODE unset) keep exit 0; /// this is the gating predicate for #357's exit-status fix. fn has_failures(checks: &[Check]) -> bool { checks.iter().any(|c| matches!(c.state, CheckState::Fail)) @@ -596,7 +616,33 @@ fn which_in_path(name: &str) -> bool { } /// Fetch the latest release tag from Twigpine/node (the actual release repo — see install.sh's -/// `GITLAWB_RELEASE_REPO` default) and compare to current version. +/// `TWIGPINE_RELEASE_REPO` default) and compare to current version. +/// A warn row naming settings given under their old `GITLAWB_` names, or +/// under both names with different values. `None` when there are none. +fn legacy_settings_check(report: &twigpine_core::legacy_env::Report) -> Option { + if report.is_empty() { + return None; + } + let mut parts = Vec::new(); + if !report.legacy_only.is_empty() { + parts.push(format!( + "set under the old GITLAWB_ name (still works): {}", + report.legacy_only.join(", ") + )); + } + if !report.conflicts.is_empty() { + parts.push(format!( + "set under both names with different values (TWIGPINE_ wins): {}", + report.conflicts.join(", ") + )); + } + Some(Check::warn( + "settings", + parts.join("; "), + "rename GITLAWB_* to TWIGPINE_* in your shell profile or service unit", + )) +} + async fn check_version(current: &'static str, github_api_base: &str) -> Check { let client = match reqwest::Client::builder() .user_agent(format!("gl/{current}")) @@ -724,7 +770,7 @@ mod tests { #[test] fn refused_resolver_becomes_check_rows_not_abort() { - // A relative GITLAWB_KEY makes both resolvers Err; doctor must turn + // A relative TWIGPINE_KEY makes both resolvers Err; doctor must turn // that into fail rows for the dependent checks and keep going, not // exit before the node/git checks ever run. crate::identity::test_env::with_key(Some("relative/path"), || { @@ -836,7 +882,7 @@ mod tests { } /// #357: Warn-class rows (iCaptcha offline, version drift, - /// GITLAWB_NODE unset on a default-config install) are NOT + /// TWIGPINE_NODE unset on a default-config install) are NOT /// exit-status failures — they are still printed to the user but the /// process exits 0. This is the rule that the previous "any /// Fail-or-Warn row → exit 1" change would have broken for stock @@ -845,7 +891,7 @@ mod tests { fn exit_predicate_is_false_for_warn_only() { let checks = vec![ Check::pass("identity", "ok"), - Check::warn("GITLAWB_NODE", "unset", "export GITLAWB_NODE=..."), + Check::warn("TWIGPINE_NODE", "unset", "export TWIGPINE_NODE=..."), Check::warn("iCaptcha", "offline", "check connectivity"), Check::warn("version", "drift", "upgrade"), ]; @@ -867,17 +913,32 @@ mod tests { let mixed_warns = vec![ Check::pass("identity", "ok"), - Check::warn("GITLAWB_NODE", "unset", "export"), + Check::warn("TWIGPINE_NODE", "unset", "export"), Check::fail("node", "unreachable", "check network"), Check::warn("iCaptcha", "offline", "check"), ]; assert!(has_failures(&mixed_warns)); } - /// #357: `GITLAWB_NODE` unset must be Warn, not Fail. This pins the + /// #357: `TWIGPINE_NODE` unset must be Warn, not Fail. This pins the /// re-tier so flipping it back to `Check::fail` breaks the suite — the /// previous `has_failures`-only tests built their own `Check::warn` rows /// and could not see the re-tier at all. + #[test] + fn legacy_settings_row_appears_only_when_an_old_name_is_in_use() { + use twigpine_core::legacy_env::Report; + assert!(legacy_settings_check(&Report::default()).is_none()); + + let check = legacy_settings_check(&Report { + legacy_only: vec!["TWIGPINE_NODE".into()], + conflicts: vec!["TWIGPINE_KEY".into()], + }) + .expect("a row"); + assert!(matches!(check.state, CheckState::Warn)); + assert!(check.detail.contains("TWIGPINE_NODE"), "{}", check.detail); + assert!(check.detail.contains("TWIGPINE_KEY"), "{}", check.detail); + } + #[test] fn gitlawb_node_env_unset_is_warn() { let check = gitlawb_node_env_check(None); @@ -887,7 +948,7 @@ mod tests { assert!(matches!(empty.state, CheckState::Warn)); } - /// `GITLAWB_NODE=""` binds `args.node` to `""` through clap, and check 3 + /// `TWIGPINE_NODE=""` binds `args.node` to `""` through clap, and check 3 /// groups empty with unset. The probe must dial the same URL unset /// would — removing the normalization makes check 4 probe `""` and Fail /// while the env row only Warns, so an empty env install exits 1. diff --git a/crates/twigpine-cli/src/http.rs b/crates/twigpine-cli/src/http.rs index fa55d6ea..c2cc4696 100644 --- a/crates/twigpine-cli/src/http.rs +++ b/crates/twigpine-cli/src/http.rs @@ -95,7 +95,7 @@ fn is_loopback_http(url: &str) -> bool { } /// Refuse to sign a request destined for a cleartext hop off this machine -/// unless the operator has opted in. `GITLAWB_ALLOW_INSECURE_HTTP` exists for a +/// unless the operator has opted in. `TWIGPINE_ALLOW_INSECURE_HTTP` exists for a /// private LAN where the operator has decided that is acceptable; only `1` or /// `true` opts in. A loopback node is never proxied (see /// [`is_loopback_http`]), so a proxy cannot carry its signed requests @@ -109,12 +109,12 @@ fn ensure_signing_transport(node_base: &str, allow_insecure: bool) -> Result<()> The request is signed but not encrypted, so the Signature header and \ the body are readable by anyone on the path, and a captured signature \ can be replayed.\n\ - Use https://, or set GITLAWB_ALLOW_INSECURE_HTTP=1 to accept the risk \ + Use https://, or set TWIGPINE_ALLOW_INSECURE_HTTP=1 to accept the risk \ (for a trusted private network only)." ) } -/// Parse a `GITLAWB_ALLOW_INSECURE_HTTP` value. Only `1` or `true` +/// Parse a `TWIGPINE_ALLOW_INSECURE_HTTP` value. Only `1` or `true` /// (case-insensitive, after trim) opens the gate. Presence alone is not /// consent: `=0`, `=false` and an empty value read as "not opting in" to the /// operator, and the README and the refusal message document `=1`. A non-empty @@ -137,7 +137,7 @@ fn allow_insecure_http_from_str(raw: Option<&str>) -> bool { /// Fixed warning for a set but non-truthy value. The raw value is never printed. fn warn_allow_insecure_http_non_truthy() { eprintln!( - "warning: GITLAWB_ALLOW_INSECURE_HTTP is set but not truthy (expected 1 or true); \ + "warning: TWIGPINE_ALLOW_INSECURE_HTTP is set but not truthy (expected 1 or true); \ plaintext http to a remote node remains refused" ); } @@ -146,7 +146,7 @@ fn warn_allow_insecure_http_non_truthy() { /// or shell can set it without rebuilding the client. A non-UTF-8 value fails /// closed and warns like any other non-truthy one. fn insecure_http_allowed() -> bool { - match std::env::var("GITLAWB_ALLOW_INSECURE_HTTP") { + match std::env::var("TWIGPINE_ALLOW_INSECURE_HTTP") { Ok(v) => allow_insecure_http_from_str(Some(&v)), Err(std::env::VarError::NotUnicode(_)) => { warn_allow_insecure_http_non_truthy(); @@ -325,7 +325,7 @@ impl NodeClient { /// signs afresh, so the retry is a new signature over the same bytes, not a /// resend of the original one. Emits an actionable hint on a 401 "not an /// agent" (the old-CLI / unregistered failure mode), and converts every - /// denial the node names in `x-gitlawb-error` into an error. + /// denial the node names in `x-twigpine-error` into an error. async fn send_signed( &self, method: &str, @@ -354,11 +354,7 @@ impl NodeClient { let status = resp.status(); if status == reqwest::StatusCode::UNAUTHORIZED - && resp - .headers() - .get("x-gitlawb-error") - .and_then(|v| v.to_str().ok()) - == Some("human_detected") + && node_error_code(resp.headers()) == Some("human_detected") { eprintln!( "note: this node requires signed requests (RFC 9421). If writes keep \ @@ -437,7 +433,7 @@ impl NodeClient { /// A write the node refused with a code this build recognises. struct SignatureRejection { - /// Which denial it was. Its `as_str` is the `x-gitlawb-error` code, printed + /// Which denial it was. Its `as_str` is the `x-twigpine-error` code, printed /// verbatim so scripts can match on it. denial: NodeDenial, /// What the user should actually do next. @@ -471,7 +467,7 @@ impl SignatureRejection { } /// Recognise a node rejection from the status and the -/// `x-gitlawb-error` header, before anything reads the body. +/// `x-twigpine-error` header, before anything reads the body. /// /// Known limit: the node also puts the same code in the body's `error` field, /// and this does not look at it, so a proxy or CDN that strips unknown `X-` @@ -501,8 +497,18 @@ impl SignatureRejection { /// the caller's instructions for it. That is the whole point of the type, since /// the previous arrangement (a list of literals in each crate) silently missed /// `signature_nonce_too_short` for several commits and returned `Ok(400)` for it. +/// The code the node put in its error header: `x-twigpine-error`, or the +/// header's name before the rename when the node is older than that. +fn node_error_code(headers: &reqwest::header::HeaderMap) -> Option<&str> { + twigpine_core::legacy_headers::ERROR_READ_ORDER + .iter() + .find_map(|name| headers.get(*name))? + .to_str() + .ok() +} + fn signature_rejection(resp: &reqwest::Response) -> Option { - let code = resp.headers().get("x-gitlawb-error")?.to_str().ok()?; + let code = node_error_code(resp.headers())?; // A code this build does not know: not our denial to describe. The header // came from a node the user chose, which may be newer, older, or hostile, // so the response goes back to the caller untouched. @@ -805,7 +811,7 @@ mod tests { use twigpine_core::identity::Keypair; /// Serializes the two integration tests that touch the process-global - /// `GITLAWB_ICAPTCHA_URL` / `GITLAWB_ICAPTCHA_INSECURE` env vars so they + /// `TWIGPINE_ICAPTCHA_URL` / `TWIGPINE_ICAPTCHA_INSECURE` env vars so they /// never race. static ICAPTCHA_ENV_LOCK: Mutex<()> = Mutex::new(()); @@ -1058,7 +1064,7 @@ mod tests { async fn send_signed_errors_on_replayed_signature_and_never_retries() { let (resp, _server) = send_signed_once( 409, - &[("x-gitlawb-error", "signature_replayed")], + &[("x-twigpine-error", "signature_replayed")], r#"{"error":"signature_replayed","message":"this signature was already used"}"#, ) .await; @@ -1080,7 +1086,7 @@ mod tests { async fn send_signed_errors_on_ledger_full_and_never_retries() { let (resp, _server) = send_signed_once( 429, - &[("x-gitlawb-error", "signature_ledger_full")], + &[("x-twigpine-error", "signature_ledger_full")], r#"{"error":"signature_ledger_full","message":"ledger at capacity"}"#, ) .await; @@ -1098,7 +1104,7 @@ mod tests { async fn send_signed_errors_on_ledger_unavailable_and_never_retries() { let (resp, _server) = send_signed_once( 503, - &[("x-gitlawb-error", "signature_ledger_unavailable")], + &[("x-twigpine-error", "signature_ledger_unavailable")], r#"{"error":"signature_ledger_unavailable","message":"ledger down"}"#, ) .await; @@ -1112,7 +1118,7 @@ mod tests { async fn send_signed_errors_on_nonce_required_and_never_retries() { let (resp, _server) = send_signed_once( 400, - &[("x-gitlawb-error", "signature_nonce_required")], + &[("x-twigpine-error", "signature_nonce_required")], r#"{"error":"signature_nonce_required","message":"this node requires a nonce"}"#, ) .await; @@ -1130,7 +1136,7 @@ mod tests { async fn send_signed_errors_on_identity_missing_and_never_retries() { let (resp, _server) = send_signed_once( 500, - &[("x-gitlawb-error", "signature_identity_missing")], + &[("x-twigpine-error", "signature_identity_missing")], r#"{"error":"signature_identity_missing","message":"no verified identity"}"#, ) .await; @@ -1148,7 +1154,7 @@ mod tests { async fn send_signed_errors_on_nonce_too_short_and_never_retries() { let (resp, _server) = send_signed_once( 400, - &[("x-gitlawb-error", "signature_nonce_too_short")], + &[("x-twigpine-error", "signature_nonce_too_short")], r#"{"error":"signature_nonce_too_short","message":"the nonce must be at least 16 characters"}"#, ) .await; @@ -1173,7 +1179,7 @@ mod tests { async fn send_signed_tells_a_rate_limit_brake_apart_from_a_full_ledger() { let (brake, _s1) = send_signed_once( 429, - &[("x-gitlawb-error", "rate_limited")], + &[("x-twigpine-error", "rate_limited")], r#"{"error":"rate_limited","message":"rate limit exceeded — try again later"}"#, ) .await; @@ -1183,7 +1189,7 @@ mod tests { let (ledger, _s2) = send_signed_once( 429, - &[("x-gitlawb-error", "signature_ledger_full")], + &[("x-twigpine-error", "signature_ledger_full")], r#"{"error":"signature_ledger_full","message":"ledger at capacity"}"#, ) .await; @@ -1233,7 +1239,7 @@ mod tests { for (status, code) in all_denials() { let body = format!(r#"{{"error":"{code}","message":"node says no"}}"#); let (resp, _server) = - send_signed_once(status, &[("x-gitlawb-error", code)], &body).await; + send_signed_once(status, &[("x-twigpine-error", code)], &body).await; let err = match resp { Ok(r) => panic!("{code} returned Ok({}) instead of an error", r.status()), Err(e) => e.to_string(), @@ -1249,7 +1255,7 @@ mod tests { #[tokio::test] async fn send_signed_does_not_see_a_denial_carried_only_in_the_body() { // Documents a known limit rather than a wanted behaviour: detection is - // header-keyed, so a proxy stripping `x-gitlawb-error` leaves the denial + // header-keyed, so a proxy stripping `x-twigpine-error` leaves the denial // to the caller (see `signature_rejection`). The callers that must not // read one as a success handle it themselves: `twigpine init` compares // `error` from the body, `twigpine task` checks the status before parsing. @@ -1278,7 +1284,15 @@ mod tests { }) .to_string(); let (resp, _server) = + send_signed_once(409, &[("x-twigpine-error", "signature_replayed")], &body).await; + // A node from before the rename names the denial in the old header. + // It must be refused just the same, not handed back as a response. + let (old, _old_server) = send_signed_once(409, &[("x-gitlawb-error", "signature_replayed")], &body).await; + assert!( + old.is_err(), + "a denial under the old header name must still be an error" + ); let err = resp.expect_err("a replay must error").to_string(); assert!( !err.contains('\u{1b}'), @@ -1319,10 +1333,10 @@ mod tests { #[tokio::test] async fn send_signed_returns_409_with_other_error_header_unchanged() { // Only the three signature_* codes are converted; any other - // x-gitlawb-error on a 409 is left to the caller. + // x-twigpine-error on a 409 is left to the caller. let (resp, _server) = send_signed_once( 409, - &[("x-gitlawb-error", "repo_exists")], + &[("x-twigpine-error", "repo_exists")], r#"{"error":"repo_exists"}"#, ) .await; @@ -1334,7 +1348,7 @@ mod tests { async fn send_signed_returns_401_invalid_signature_unchanged() { let (resp, _server) = send_signed_once( 401, - &[("x-gitlawb-error", "invalid_signature")], + &[("x-twigpine-error", "invalid_signature")], r#"{"error":"invalid_signature"}"#, ) .await; @@ -1351,7 +1365,7 @@ mod tests { .mock("POST", "/api/v1/repos") .with_status(401) .with_header("content-type", "application/json") - .with_header("x-gitlawb-error", "human_detected") + .with_header("x-twigpine-error", "human_detected") .with_body(r#"{"error":"human_detected"}"#) .expect(1) .create_async() @@ -1371,7 +1385,7 @@ mod tests { // match too, so a 200 carrying a stray header stays a success. let (resp, _server) = send_signed_once( 200, - &[("x-gitlawb-error", "signature_replayed")], + &[("x-twigpine-error", "signature_replayed")], r#"{"ok":true}"#, ) .await; @@ -1381,7 +1395,7 @@ mod tests { // ── send_signed iCaptcha retry (full integration) ──────────────────── - /// Set GITLAWB_ICAPTCHA_URL and GITLAWB_ICAPTCHA_INSECURE so the iCaptcha + /// Set TWIGPINE_ICAPTCHA_URL and TWIGPINE_ICAPTCHA_INSECURE so the iCaptcha /// client trusts a local mockito HTTP server, restoring any prior values on /// drop so a test run launched with those variables keeps working. /// Holds [`ICAPTCHA_ENV_LOCK`] for its lifetime so concurrent tests don't @@ -1395,10 +1409,10 @@ mod tests { impl IcaptchaEnv { fn new(url: &str) -> Self { let lock = ICAPTCHA_ENV_LOCK.lock().unwrap(); - let prev_url = std::env::var_os("GITLAWB_ICAPTCHA_URL"); - let prev_insecure = std::env::var_os("GITLAWB_ICAPTCHA_INSECURE"); - std::env::set_var("GITLAWB_ICAPTCHA_URL", url); - std::env::set_var("GITLAWB_ICAPTCHA_INSECURE", "1"); + let prev_url = std::env::var_os("TWIGPINE_ICAPTCHA_URL"); + let prev_insecure = std::env::var_os("TWIGPINE_ICAPTCHA_INSECURE"); + std::env::set_var("TWIGPINE_ICAPTCHA_URL", url); + std::env::set_var("TWIGPINE_ICAPTCHA_INSECURE", "1"); IcaptchaEnv { _lock: lock, prev_url, @@ -1410,12 +1424,12 @@ mod tests { impl Drop for IcaptchaEnv { fn drop(&mut self) { match self.prev_url.take() { - Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_URL", v), - None => std::env::remove_var("GITLAWB_ICAPTCHA_URL"), + Some(v) => std::env::set_var("TWIGPINE_ICAPTCHA_URL", v), + None => std::env::remove_var("TWIGPINE_ICAPTCHA_URL"), } match self.prev_insecure.take() { - Some(v) => std::env::set_var("GITLAWB_ICAPTCHA_INSECURE", v), - None => std::env::remove_var("GITLAWB_ICAPTCHA_INSECURE"), + Some(v) => std::env::set_var("TWIGPINE_ICAPTCHA_INSECURE", v), + None => std::env::remove_var("TWIGPINE_ICAPTCHA_INSECURE"), } } } @@ -2160,7 +2174,7 @@ mod tests { // ── #413 plaintext-remote signing guard ────────────────────────────── - /// Holds [`ICAPTCHA_ENV_LOCK`] while it points `GITLAWB_ALLOW_INSECURE_HTTP` + /// Holds [`ICAPTCHA_ENV_LOCK`] while it points `TWIGPINE_ALLOW_INSECURE_HTTP` /// at `value` (or removes it), restoring the prior value on drop. struct InsecureHttpEnv { _lock: MutexGuard<'static, ()>, @@ -2170,10 +2184,10 @@ mod tests { impl InsecureHttpEnv { fn set(value: Option<&str>) -> Self { let lock = ICAPTCHA_ENV_LOCK.lock().unwrap(); - let prev = std::env::var_os("GITLAWB_ALLOW_INSECURE_HTTP"); + let prev = std::env::var_os("TWIGPINE_ALLOW_INSECURE_HTTP"); match value { - Some(v) => std::env::set_var("GITLAWB_ALLOW_INSECURE_HTTP", v), - None => std::env::remove_var("GITLAWB_ALLOW_INSECURE_HTTP"), + Some(v) => std::env::set_var("TWIGPINE_ALLOW_INSECURE_HTTP", v), + None => std::env::remove_var("TWIGPINE_ALLOW_INSECURE_HTTP"), } InsecureHttpEnv { _lock: lock, prev } } @@ -2182,8 +2196,8 @@ mod tests { impl Drop for InsecureHttpEnv { fn drop(&mut self) { match self.prev.take() { - Some(v) => std::env::set_var("GITLAWB_ALLOW_INSECURE_HTTP", v), - None => std::env::remove_var("GITLAWB_ALLOW_INSECURE_HTTP"), + Some(v) => std::env::set_var("TWIGPINE_ALLOW_INSECURE_HTTP", v), + None => std::env::remove_var("TWIGPINE_ALLOW_INSECURE_HTTP"), } } } @@ -2221,7 +2235,7 @@ mod tests { let err = ensure_signing_transport("http://10.0.0.36:7777", false).unwrap_err(); assert!( err.to_string().contains("plaintext http") - && err.to_string().contains("GITLAWB_ALLOW_INSECURE_HTTP"), + && err.to_string().contains("TWIGPINE_ALLOW_INSECURE_HTTP"), "the refusal names the risk and the opt-in: {err}" ); // Opted in, loopback, and https all pass. @@ -2251,11 +2265,14 @@ mod tests { async fn get_signed_proceeds_when_insecure_http_opted_in() { let _env = InsecureHttpEnv::set(Some("1")); let client = NodeClient::new("http://gl-nonexistent-node.invalid", Some(test_keypair())); - let err = client.get_signed("/api/v1/x").await.unwrap_err(); - assert!( - !err.to_string().contains("plaintext http"), - "the opt-in should let the request attempt the hop, got: {err}" - ); + // Under HTTP_PROXY the proxy may answer instead of DNS failing; either + // way the guard let the request go, which is all this test is about. + if let Err(err) = client.get_signed("/api/v1/x").await { + assert!( + !err.to_string().contains("plaintext http"), + "the opt-in should let the request attempt the hop, got: {err}" + ); + } } /// Unsigned calls are not this guard's business: no keypair means no @@ -2264,11 +2281,12 @@ mod tests { async fn unsigned_call_to_plaintext_remote_is_ungated() { let _env = InsecureHttpEnv::set(None); let client = NodeClient::new("http://gl-nonexistent-node.invalid", None); - let err = client.post("/api/v1/x", b"{}").await.unwrap_err(); - assert!( - !err.to_string().contains("plaintext http"), - "an unsigned request should not hit the signing guard, got: {err}" - ); + if let Err(err) = client.post("/api/v1/x", b"{}").await { + assert!( + !err.to_string().contains("plaintext http"), + "an unsigned request should not hit the signing guard, got: {err}" + ); + } } /// The opt-in is read as a value, not as presence, with the same contract as @@ -2308,7 +2326,7 @@ mod tests { "all_proxy", "NO_PROXY", "no_proxy", - "GITLAWB_ALLOW_INSECURE_HTTP", + "TWIGPINE_ALLOW_INSECURE_HTTP", ] { cmd.env_remove(k); } @@ -2481,7 +2499,7 @@ mod tests { &[ ("GL_ROUTE_REMOTE", "1"), ("GL_ROUTE_ALLOW", "1"), - ("GITLAWB_ALLOW_INSECURE_HTTP", "1"), + ("TWIGPINE_ALLOW_INSECURE_HTTP", "1"), ], ); } diff --git a/crates/twigpine-cli/src/identity.rs b/crates/twigpine-cli/src/identity.rs index c3ba1f8c..36d0798e 100644 --- a/crates/twigpine-cli/src/identity.rs +++ b/crates/twigpine-cli/src/identity.rs @@ -10,7 +10,7 @@ pub enum IdentityCmd { /// Generate a new Ed25519 keypair and DID New { /// Output directory for key files - /// (default: the parent of $GITLAWB_KEY, else ~/.gitlawb) + /// (default: the parent of $TWIGPINE_KEY, else ~/.twigpine) #[arg(long)] dir: Option, /// Overwrite existing keys if present @@ -69,19 +69,19 @@ pub async fn run(cmd: IdentityCmd) -> Result<()> { /// place the identity itself lives. /// /// Without an override this is [`twigpine_core::identity_path::identity_dir`] — the -/// parent of `GITLAWB_KEY`, else `~/.gitlawb`. The rules live in `twigpine-core` +/// parent of `TWIGPINE_KEY`, else `~/.twigpine`. The rules live in `twigpine-core` /// because `git-remote-twigpine` needs the identical answer: an operator who moved -/// their key (`GITLAWB_KEY=/data/keys/identity.pem`, the shape `.env.example` +/// their key (`TWIGPINE_KEY=/data/keys/identity.pem`, the shape `.env.example` /// documents) would otherwise have `twigpine ucan import` write the delegation to -/// `~/.gitlawb/delegations` while the helper reads `/data/keys/delegations` and +/// `~/.twigpine/delegations` while the helper reads `/data/keys/delegations` and /// finds it empty. The push then goes out with no `X-Ucan` and the delegate is /// refused, with nothing on either side to indicate why. -pub fn gitlawb_dir(override_dir: Option) -> Result { +pub fn identity_dir(override_dir: Option) -> Result { if let Some(d) = override_dir { return Ok(d); } // `home_dir()` is passed as an Option rather than demanded here: an absolute - // GITLAWB_KEY resolves without a home directory, and a host that has none is a + // TWIGPINE_KEY resolves without a home directory, and a host that has none is a // normal container shape, not a reason to refuse a correctly-configured key. let home = dirs::home_dir(); twigpine_core::identity_path::identity_dir(home.as_deref()).map_err(|e| anyhow::anyhow!("{e}")) @@ -91,12 +91,12 @@ pub fn gitlawb_dir(override_dir: Option) -> Result { /// /// With an explicit `--dir` this is `/identity.pem`, the conventional layout. /// Without one it is [`twigpine_core::identity_path::identity_key_path`] — the whole -/// of `GITLAWB_KEY`, basename included. +/// of `TWIGPINE_KEY`, basename included. /// /// Taking only the parent and re-appending `identity.pem` was a real divergence, -/// not a tidy-up: `GITLAWB_KEY` is documented as a path to a PEM, and +/// not a tidy-up: `TWIGPINE_KEY` is documented as a path to a PEM, and /// `git-remote-twigpine` opens exactly that path. With -/// `GITLAWB_KEY=/data/keys/ci-agent.pem`, `twigpine identity new` wrote +/// `TWIGPINE_KEY=/data/keys/ci-agent.pem`, `twigpine identity new` wrote /// `/data/keys/identity.pem` while every push loaded `/data/keys/ci-agent.pem`, so /// the two either disagreed on identity or the helper found no key at all — and /// owner enforcement and the delegation proof both key off that identity. @@ -111,6 +111,24 @@ pub(crate) fn key_path_for(dir: Option<&Path>) -> Result { } } +/// Refuse to create a key at `path` when it is the key file in `~/.twigpine` +/// and the identity is still in `~/.gitlawb` from before the rename. +/// +/// Every command that can generate a key calls this first. Generating there +/// would give the user a second DID beside the one their repositories and +/// delegations belong to, which is the outcome the folder rule must never +/// produce. +pub(crate) fn refuse_if_stranded(path: &Path) -> Result<()> { + let home = dirs::home_dir(); + match twigpine_core::identity_path::stranded_legacy_key(path, home.as_deref()) { + Some(legacy) => anyhow::bail!( + "not creating a new identity: {}", + twigpine_core::identity_path::stranded_legacy_key_message(path, &legacy) + ), + None => Ok(()), + } +} + fn load_keypair(dir: Option) -> Result { load_keypair_from_dir(dir.as_deref()) } @@ -118,18 +136,28 @@ fn load_keypair(dir: Option) -> Result { /// Load keypair from an optional directory override. /// Used by other modules (register, repo, mcp). /// -/// Routed through [`gitlawb_dir`] rather than reaching for `~/.gitlawb` directly: -/// `twigpine identity new` writes the key wherever `GITLAWB_KEY` points, so a second +/// Routed through [`identity_dir`] rather than reaching for `~/.twigpine` directly: +/// `twigpine identity new` writes the key wherever `TWIGPINE_KEY` points, so a second /// resolver here would have every other command read a different file than the one /// just created — `twigpine ucan delegate` would either fail to find an identity or sign /// with a stale DID that is not the repo owner. pub fn load_keypair_from_dir(dir: Option<&std::path::Path>) -> Result { let path = key_path_for(dir)?; let pem = fs::read_to_string(&path).with_context(|| { - format!( - "no identity found at {}\nRun `twigpine identity new` to create one", - path.display() - ) + // The key may be sitting in the folder from before the rename. Saying + // "create one" there would walk the user into a second identity. + let home = dirs::home_dir(); + match twigpine_core::identity_path::stranded_legacy_key(&path, home.as_deref()) { + Some(legacy) => format!( + "no identity found at {}\n{}", + path.display(), + twigpine_core::identity_path::stranded_legacy_key_message(&path, &legacy) + ), + None => format!( + "no identity found at {}\nRun `twigpine identity new` to create one", + path.display() + ), + } })?; Keypair::from_pem(&pem).context("failed to load keypair from PEM") } @@ -141,15 +169,15 @@ pub fn load_optional_keypair(dir: Option<&std::path::Path>) -> Result) -> Result Keypair::from_pem(&pem) .context("failed to load keypair from PEM") .map(Some), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + // Missing means anonymous, unless the key is sitting in the folder from + // before the rename: then going anonymous would hide a real identity. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + refuse_if_stranded(&path).map_err(|_| { + let home = dirs::home_dir(); + let legacy = + twigpine_core::identity_path::stranded_legacy_key(&path, home.as_deref()) + .unwrap_or_default(); + anyhow::anyhow!( + "no identity found at {}\n{}", + path.display(), + twigpine_core::identity_path::stranded_legacy_key_message(&path, &legacy) + ) + })?; + Ok(None) + } Err(e) => Err(anyhow::Error::from(e) .context(format!("failed to read identity from {}", path.display()))), } @@ -197,6 +240,10 @@ async fn cmd_new_with_reader( println!("Aborted."); return Ok(()); } + } else if !force { + // `--force` is the deliberate way to start over; without it, a key left + // in the folder from before the rename stops a second identity. + refuse_if_stranded(&path)?; } crate::secret_file::create_dir(&dir) @@ -341,7 +388,7 @@ mod tests { assert_eq!( loaded.map(|k| k.did().to_string()), Some(kp.did().to_string()), - "the configured basename must be read, not ~/.gitlawb/identity.pem" + "the configured basename must be read, not ~/.twigpine/identity.pem" ); }); } @@ -582,7 +629,7 @@ mod tests { } } -/// Scoped `GITLAWB_KEY` for tests, shared crate-wide. +/// Scoped `TWIGPINE_KEY` for tests, shared crate-wide. /// /// The process environment is global and more than one suite in this crate /// depends on it — the resolver's own cases here, and `twigpine register`'s check that @@ -604,25 +651,25 @@ pub(crate) mod test_env { impl Drop for KeyEnv { fn drop(&mut self) { match self.restore.take() { - Some(v) => std::env::set_var("GITLAWB_KEY", v), - None => std::env::remove_var("GITLAWB_KEY"), + Some(v) => std::env::set_var("TWIGPINE_KEY", v), + None => std::env::remove_var("TWIGPINE_KEY"), } } } - /// Run `f` with `GITLAWB_KEY` set, restoring it afterwards. + /// Run `f` with `TWIGPINE_KEY` set, restoring it afterwards. pub(crate) fn with_key>(value: Option, f: impl FnOnce() -> T) -> T { let _guard = set_key(value); f() } - /// Set `GITLAWB_KEY` (or remove it, for `None`) until the guard drops. + /// Set `TWIGPINE_KEY` (or remove it, for `None`) until the guard drops. pub(crate) fn set_key>(value: Option) -> KeyEnv { let guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); - let restore = std::env::var_os("GITLAWB_KEY"); + let restore = std::env::var_os("TWIGPINE_KEY"); match value { - Some(v) => std::env::set_var("GITLAWB_KEY", v), - None => std::env::remove_var("GITLAWB_KEY"), + Some(v) => std::env::set_var("TWIGPINE_KEY", v), + None => std::env::remove_var("TWIGPINE_KEY"), } KeyEnv { _guard: guard, @@ -632,33 +679,33 @@ pub(crate) mod test_env { } #[cfg(test)] -mod gitlawb_dir_tests { - use super::{gitlawb_dir, load_keypair_from_dir}; +mod identity_dir_tests { + use super::{identity_dir, load_keypair_from_dir}; use std::ffi::OsString; use std::path::PathBuf; - /// Run `f` with `GITLAWB_KEY` set to `value` (or removed for `None`), restoring + /// Run `f` with `TWIGPINE_KEY` set to `value` (or removed for `None`), restoring /// whatever was there before. fn with_key_env(value: Option, f: impl FnOnce() -> T) -> T { let _env = crate::identity::test_env::set_key(value); f() } - /// An explicit --dir always wins and is never validated against GITLAWB_KEY. + /// An explicit --dir always wins and is never validated against TWIGPINE_KEY. #[test] fn explicit_override_wins() { let d = PathBuf::from("/tmp/explicit"); - assert_eq!(gitlawb_dir(Some(d.clone())).unwrap(), d); + assert_eq!(identity_dir(Some(d.clone())).unwrap(), d); } - /// A relative GITLAWB_KEY must fail loudly. `twigpine` and `git-remote-twigpine` run + /// A relative TWIGPINE_KEY must fail loudly. `twigpine` and `git-remote-twigpine` run /// from different working directories, so resolving one relatively sends the /// import and the lookup to different stores; a one-component value yields an /// empty parent and puts the store in `./delegations`. #[test] fn relative_key_paths_are_refused() { for raw in ["identity.pem", "keys/identity.pem"] { - let result = with_key_env(Some(OsString::from(raw)), || gitlawb_dir(None)); + let result = with_key_env(Some(OsString::from(raw)), || identity_dir(None)); assert!(result.is_err(), "{raw} is relative and must be refused"); } } @@ -671,17 +718,18 @@ mod gitlawb_dir_tests { // rule resolves to anonymous there, so this assertion has nothing to // compare against and is a pass, not a panic. let Some(home) = dirs::home_dir() else { return }; - let result = with_key_env(Some(OsString::new()), || gitlawb_dir(None)); + let result = with_key_env(Some(OsString::new()), || identity_dir(None)); assert_eq!( result.unwrap(), - home.join(".gitlawb"), + // `~/.twigpine`, or an existing `~/.gitlawb` from before the rename. + twigpine_core::identity_path::default_dir(&home), "an empty value selects the default directory" ); } - /// The reason `gitlawb_dir` reads through `var_os`: `env::var` folds a non-UTF-8 + /// The reason `identity_dir` reads through `var_os`: `env::var` folds a non-UTF-8 /// value into the same `Err` as unset, so a bad path would silently resolve to - /// `~/.gitlawb` instead of being reported. Byte 0xFF is not valid UTF-8 in any + /// `~/.twigpine` instead of being reported. Byte 0xFF is not valid UTF-8 in any /// position, so this value is unreachable through `env::var`. #[cfg(unix)] #[test] @@ -689,7 +737,7 @@ mod gitlawb_dir_tests { use std::os::unix::ffi::OsStringExt; let raw = OsString::from_vec(b"keys/\xFF/identity.pem".to_vec()); - let result = with_key_env(Some(raw), || gitlawb_dir(None)); + let result = with_key_env(Some(raw), || identity_dir(None)); let err = result.expect_err("a non-UTF-8 relative path must be refused"); assert!( @@ -700,17 +748,17 @@ mod gitlawb_dir_tests { let mut absolute = OsString::from("/data/"); absolute.push(OsString::from_vec(vec![0xFF])); absolute.push("/identity.pem"); - let resolved = with_key_env(Some(absolute.clone()), || gitlawb_dir(None)).unwrap(); + let resolved = with_key_env(Some(absolute.clone()), || identity_dir(None)).unwrap(); assert_eq!( resolved, PathBuf::from(&absolute).parent().unwrap(), - "an absolute non-UTF-8 path resolves to its own parent, not to ~/.gitlawb" + "an absolute non-UTF-8 path resolves to its own parent, not to ~/.twigpine" ); } - /// `twigpine identity new` writes the key wherever `GITLAWB_KEY` points, so every + /// `twigpine identity new` writes the key wherever `TWIGPINE_KEY` points, so every /// other command has to read it back from there. `load_keypair_from_dir(None)` - /// used to hardcode `~/.gitlawb`, which made `twigpine ucan delegate` sign with a + /// used to hardcode `~/.twigpine`, which made `twigpine ucan delegate` sign with a /// stale DID — or fail outright — for exactly the operators who moved the key. #[test] fn load_keypair_from_dir_honours_the_key_env() { @@ -720,7 +768,7 @@ mod gitlawb_dir_tests { std::fs::write(&key, expected.to_pem().unwrap()).unwrap(); let loaded = with_key_env(Some(key.into_os_string()), || load_keypair_from_dir(None)) - .expect("the identity beside GITLAWB_KEY must be found"); + .expect("the identity beside TWIGPINE_KEY must be found"); assert_eq!(loaded.did(), expected.did()); } @@ -730,9 +778,9 @@ mod gitlawb_dir_tests { mod key_basename_tests { use super::*; - /// `GITLAWB_KEY` names a FILE. `twigpine` used to keep only its parent and re-append + /// `TWIGPINE_KEY` names a FILE. `twigpine` used to keep only its parent and re-append /// `identity.pem`, while `git-remote-twigpine` opened the configured path — so - /// with `GITLAWB_KEY=/data/keys/ci-agent.pem` the CLI and the push path loaded + /// with `TWIGPINE_KEY=/data/keys/ci-agent.pem` the CLI and the push path loaded /// different files, and owner enforcement and the delegation proof both key off /// whichever identity that was. #[test] @@ -748,7 +796,7 @@ mod key_basename_tests { assert_eq!(resolved, key, "the configured basename must survive"); assert_eq!( - loaded.expect("the key at GITLAWB_KEY must load").did(), + loaded.expect("the key at TWIGPINE_KEY must load").did(), expected.did(), "twigpine must load the same file the helper opens" ); diff --git a/crates/twigpine-cli/src/init.rs b/crates/twigpine-cli/src/init.rs index 3738374c..ed2a8915 100644 --- a/crates/twigpine-cli/src/init.rs +++ b/crates/twigpine-cli/src/init.rs @@ -22,11 +22,11 @@ pub struct InitArgs { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] pub node: String, - /// Identity directory (default: the parent of $GITLAWB_KEY, else ~/.gitlawb) + /// Identity directory (default: the parent of $TWIGPINE_KEY, else ~/.twigpine) #[arg(long)] pub dir: Option, @@ -78,7 +78,15 @@ async fn run_in(cwd: &std::path::Path, args: InitArgs) -> Result<()> { println!("Identity found: {}", kp.did()); kp } - Err(_) => { + Err(e) => { + // Only a key that is really absent may be created. A file that + // exists but does not load is reported, never replaced, and a key + // left in the folder from before the rename is pointed at. + let path = crate::identity::key_path_for(args.dir.as_deref())?; + if path.exists() { + return Err(e); + } + crate::identity::refuse_if_stranded(&path)?; println!("No identity found — generating new keypair..."); let kp = generate_identity(args.dir.as_deref())?; println!(" DID: {}", kp.did()); @@ -109,7 +117,7 @@ async fn run_in(cwd: &std::path::Path, args: InitArgs) -> Result<()> { // Save UCAN if returned if let Some(ucan) = payload.get("ucan").and_then(|v| v.as_str()) { if !ucan.is_empty() { - let ucan_dir = crate::identity::gitlawb_dir(args.dir.clone())?; + let ucan_dir = crate::identity::identity_dir(args.dir.clone())?; crate::secret_file::create_dir(&ucan_dir)?; let record = json!({ "ucan": ucan, @@ -392,7 +400,7 @@ mod tests { #[tokio::test] async fn init_fails_on_replay_409_without_the_error_header() { // The node refused the create (the signature was already spent) and a - // proxy stripped `x-gitlawb-error`, so the client layer cannot see the + // proxy stripped `x-twigpine-error`, so the client layer cannot see the // denial and hands the 409 straight back. `twigpine init` used to read // "already" out of the prose, print "Repository already exists — // continuing", add the remote, print "Ready! Push with", and exit 0 for diff --git a/crates/twigpine-cli/src/ipfs_cmd.rs b/crates/twigpine-cli/src/ipfs_cmd.rs index 9b124c81..ae947114 100644 --- a/crates/twigpine-cli/src/ipfs_cmd.rs +++ b/crates/twigpine-cli/src/ipfs_cmd.rs @@ -25,10 +25,10 @@ pub enum IpfsCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, - /// Identity directory (default: the parent of $GITLAWB_KEY, else ~/.gitlawb) + /// Identity directory (default: the parent of $TWIGPINE_KEY, else ~/.twigpine) #[arg(long)] dir: Option, }, @@ -76,10 +76,10 @@ pub enum IpfsCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, - /// Identity directory (default: the parent of $GITLAWB_KEY, else ~/.gitlawb) + /// Identity directory (default: the parent of $TWIGPINE_KEY, else ~/.twigpine) #[arg(long)] dir: Option, /// Resume token from a scan that stopped at a bound, as printed by a @@ -120,7 +120,7 @@ async fn cmd_list(node: String, dir: Option) -> Result<()> { if pins.is_empty() { println!("No IPFS pins recorded on {node}"); - println!("(Push to a repo with GITLAWB_IPFS_API set to start pinning)"); + println!("(Push to a repo with TWIGPINE_IPFS_API set to start pinning)"); return Ok(()); } diff --git a/crates/twigpine-cli/src/issue.rs b/crates/twigpine-cli/src/issue.rs index 36733a11..fa96e78f 100644 --- a/crates/twigpine-cli/src/issue.rs +++ b/crates/twigpine-cli/src/issue.rs @@ -35,7 +35,7 @@ pub enum IssueCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -48,7 +48,7 @@ pub enum IssueCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -63,7 +63,7 @@ pub enum IssueCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -78,7 +78,7 @@ pub enum IssueCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -93,7 +93,7 @@ pub enum IssueCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -106,7 +106,7 @@ pub enum IssueCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] diff --git a/crates/twigpine-cli/src/main.rs b/crates/twigpine-cli/src/main.rs index a2e00481..ebc3948d 100644 --- a/crates/twigpine-cli/src/main.rs +++ b/crates/twigpine-cli/src/main.rs @@ -142,8 +142,31 @@ enum Commands { Whoami(whoami::WhoamiArgs), } +/// The command was `gl` before the rename and still answers to it. Say so +/// once per run, on stderr, and only to a person: scripts and the MCP server +/// (which owns stdout and is never a terminal on stderr's side of a pipe) see +/// nothing. +fn old_command_name_notice() { + use std::io::IsTerminal; + let invoked_as_gl = std::env::args_os() + .next() + .map(std::path::PathBuf::from) + .and_then(|p| p.file_stem().map(|s| s.to_os_string())) + .is_some_and(|stem| stem == "gl"); + if invoked_as_gl && std::io::stderr().is_terminal() { + eprintln!("note: `gl` is now `twigpine` (short: `twig`). `gl` still works for now."); + } +} + +fn main() -> Result<()> { + // Before the runtime starts its threads, and before anything reads a + // setting: accept the names settings had before the rename. + twigpine_core::legacy_env::adopt(); + run() +} + #[tokio::main] -async fn main() -> Result<()> { +async fn run() -> Result<()> { tracing_subscriber::fmt() .with_env_filter( tracing_subscriber::EnvFilter::from_default_env() @@ -152,6 +175,8 @@ async fn main() -> Result<()> { .with_writer(std::io::stderr) // keep stdout clean for MCP framing .init(); + old_command_name_notice(); + let cli = Cli::parse(); match cli.command { Commands::Identity { cmd } => identity::run(cmd).await, diff --git a/crates/twigpine-cli/src/mcp.rs b/crates/twigpine-cli/src/mcp.rs index cc1091c0..e8b33fd4 100644 --- a/crates/twigpine-cli/src/mcp.rs +++ b/crates/twigpine-cli/src/mcp.rs @@ -58,7 +58,7 @@ pub enum McpCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, /// Identity directory @@ -136,6 +136,9 @@ async fn dispatch( "initialize" => Ok(json!({ "protocolVersion": "2024-11-05", "capabilities": { "tools": {} }, + // Wire-visible, like the CLI's user agent: it moves to "twigpine" + // with the other names peers and clients can see, in the protocol + // step of the rename, not here. "serverInfo": { "name": "gitlawb", "version": env!("CARGO_PKG_VERSION"), @@ -803,7 +806,7 @@ async fn call_tool( // The directory the server was started with, like every sibling tool. // Reading the default here while the rest honour `--dir` splits one MCP // session across two identity directories. - let ucan_path = crate::identity::gitlawb_dir(dir.map(std::path::Path::to_path_buf))? + let ucan_path = crate::identity::identity_dir(dir.map(std::path::Path::to_path_buf))? .join("ucan.json"); if !ucan_path.exists() { return Ok( @@ -2058,7 +2061,7 @@ mod tests { #[tokio::test] async fn test_task_list_via_mcp_follows_cursors() { // The env-mutating suites serialize on test_env's lock; a resolver - // reader that skips it can observe a half-set GITLAWB_KEY mid-race. + // reader that skips it can observe a half-set TWIGPINE_KEY mid-race. // Taking it here (with the key absent) keeps this read deterministic. let _key_guard = crate::identity::test_env::set_key(None::<&str>); let mut server = mockito::Server::new_async().await; @@ -3093,7 +3096,7 @@ mod tests { .await; // Point at an EMPTY dir rather than passing `None`: `None` falls back to - // the ambient ~/.gitlawb/identity.pem, which exists on a dev box and not + // the ambient ~/.twigpine/identity.pem, which exists on a dev box and not // on CI, so the request would be signed here and unsigned there. let empty = tempfile::TempDir::new().unwrap(); let err = call_tool( @@ -3385,7 +3388,7 @@ mod tests { .mock("POST", "/api/v1/repos") .with_status(409) .with_header("content-type", "application/json") - .with_header("x-gitlawb-error", "signature_replayed") + .with_header("x-twigpine-error", "signature_replayed") .with_body(r#"{"error":"signature_replayed","message":"signature already spent"}"#) .expect(1) .create_async() @@ -3412,7 +3415,7 @@ mod tests { .mock("POST", "/api/v1/repos/alice/myrepo/issues") .with_status(409) .with_header("content-type", "application/json") - .with_header("x-gitlawb-error", "signature_replayed") + .with_header("x-twigpine-error", "signature_replayed") .with_body(r#"{"error":"signature_replayed","message":"signature already spent"}"#) .expect(1) .create_async() @@ -3458,7 +3461,7 @@ mod tests { #[tokio::test] async fn test_repo_create_repo_exists_409_is_distinguishable_from_a_replay() { - // The pre-existing 409 carries no x-gitlawb-error header. It must still + // The pre-existing 409 carries no x-twigpine-error header. It must still // fail the tool call (a denial is not a success), but its message must // not name a signature rejection. let mut server = mockito::Server::new_async().await; diff --git a/crates/twigpine-cli/src/mirror.rs b/crates/twigpine-cli/src/mirror.rs index a08e1106..b2fee5c4 100644 --- a/crates/twigpine-cli/src/mirror.rs +++ b/crates/twigpine-cli/src/mirror.rs @@ -33,7 +33,7 @@ pub struct MirrorArgs { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] pub node: String, @@ -128,6 +128,8 @@ pub async fn run(args: MirrorArgs) -> Result<()> { let push_status = Command::new("git") .args(["push", "--mirror", &gitlawb_url]) .current_dir(&mirror_path) + .env("TWIGPINE_NODE", &args.node) + // The helper on PATH may be a build from before the rename. .env("GITLAWB_NODE", &args.node) .status() .context("failed to run git push")?; diff --git a/crates/twigpine-cli/src/name.rs b/crates/twigpine-cli/src/name.rs index cd64183e..f1de93aa 100644 --- a/crates/twigpine-cli/src/name.rs +++ b/crates/twigpine-cli/src/name.rs @@ -67,10 +67,10 @@ pub enum NameCmd { #[arg(long, env = "ETH_PRIVATE_KEY")] private_key: String, /// RPC URL (default: Base Sepolia) - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] rpc_url: String, /// Name registry contract address - #[arg(long, env = "GITLAWB_CONTRACT_NAME_REGISTRY", default_value = DEFAULT_NAME_REGISTRY)] + #[arg(long, env = "TWIGPINE_CONTRACT_NAME_REGISTRY", default_value = DEFAULT_NAME_REGISTRY)] contract: String, /// Twigpine identity directory (reads your DID) #[arg(long)] @@ -80,27 +80,27 @@ pub enum NameCmd { /// Resolve name → owner address + DID Resolve { name: String, - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] rpc_url: String, - #[arg(long, env = "GITLAWB_CONTRACT_NAME_REGISTRY", default_value = DEFAULT_NAME_REGISTRY)] + #[arg(long, env = "TWIGPINE_CONTRACT_NAME_REGISTRY", default_value = DEFAULT_NAME_REGISTRY)] contract: String, }, /// Reverse lookup: DID → registered name Lookup { did: String, - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] rpc_url: String, - #[arg(long, env = "GITLAWB_CONTRACT_NAME_REGISTRY", default_value = DEFAULT_NAME_REGISTRY)] + #[arg(long, env = "TWIGPINE_CONTRACT_NAME_REGISTRY", default_value = DEFAULT_NAME_REGISTRY)] contract: String, }, /// Check whether a name is available to register Available { name: String, - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] rpc_url: String, - #[arg(long, env = "GITLAWB_CONTRACT_NAME_REGISTRY", default_value = DEFAULT_NAME_REGISTRY)] + #[arg(long, env = "TWIGPINE_CONTRACT_NAME_REGISTRY", default_value = DEFAULT_NAME_REGISTRY)] contract: String, }, @@ -108,9 +108,9 @@ pub enum NameCmd { RegisterDid { #[arg(long, env = "ETH_PRIVATE_KEY")] private_key: String, - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] rpc_url: String, - #[arg(long, env = "GITLAWB_CONTRACT_DID_REGISTRY", default_value = DEFAULT_DID_REGISTRY)] + #[arg(long, env = "TWIGPINE_CONTRACT_DID_REGISTRY", default_value = DEFAULT_DID_REGISTRY)] contract: String, #[arg(long)] dir: Option, @@ -119,9 +119,9 @@ pub enum NameCmd { /// Resolve a DID from the on-chain DID registry ResolveDid { did: String, - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = DEFAULT_RPC_URL)] rpc_url: String, - #[arg(long, env = "GITLAWB_CONTRACT_DID_REGISTRY", default_value = DEFAULT_DID_REGISTRY)] + #[arg(long, env = "TWIGPINE_CONTRACT_DID_REGISTRY", default_value = DEFAULT_DID_REGISTRY)] contract: String, }, } diff --git a/crates/twigpine-cli/src/node.rs b/crates/twigpine-cli/src/node.rs index d17a08e8..c4d80530 100644 --- a/crates/twigpine-cli/src/node.rs +++ b/crates/twigpine-cli/src/node.rs @@ -23,10 +23,10 @@ pub enum NodeCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, - /// Identity directory (default: the parent of $GITLAWB_KEY, else ~/.gitlawb) + /// Identity directory (default: the parent of $TWIGPINE_KEY, else ~/.twigpine) #[arg(long)] dir: Option, }, @@ -36,7 +36,7 @@ pub enum NodeCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, }, @@ -46,7 +46,7 @@ pub enum NodeCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, }, @@ -61,16 +61,16 @@ pub enum NodeCmd { #[arg(long)] http_url: String, /// Operator private key (0x-prefixed hex) - #[arg(long, env = "GITLAWB_OPERATOR_PRIVATE_KEY")] + #[arg(long, env = "TWIGPINE_OPERATOR_PRIVATE_KEY")] private_key: String, /// $GITLAWB ERC20 address - #[arg(long, env = "GITLAWB_TOKEN")] + #[arg(long, env = "TWIGPINE_TOKEN")] token: String, /// GitlawbNodeStaking contract address - #[arg(long, env = "GITLAWB_CONTRACT_NODE_STAKING")] + #[arg(long, env = "TWIGPINE_CONTRACT_NODE_STAKING")] contract: String, /// Base RPC URL - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] rpc_url: String, /// Identity dir (reads DID) #[arg(long)] @@ -79,11 +79,11 @@ pub enum NodeCmd { /// Manually post a heartbeat (usually automatic once the node is running) Heartbeat { - #[arg(long, env = "GITLAWB_OPERATOR_PRIVATE_KEY")] + #[arg(long, env = "TWIGPINE_OPERATOR_PRIVATE_KEY")] private_key: String, - #[arg(long, env = "GITLAWB_CONTRACT_NODE_STAKING")] + #[arg(long, env = "TWIGPINE_CONTRACT_NODE_STAKING")] contract: String, - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] rpc_url: String, #[arg(long)] dir: Option, @@ -91,9 +91,9 @@ pub enum NodeCmd { /// View your node's on-chain stake, rewards, and active flag OnchainStatus { - #[arg(long, env = "GITLAWB_CONTRACT_NODE_STAKING")] + #[arg(long, env = "TWIGPINE_CONTRACT_NODE_STAKING")] contract: String, - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] rpc_url: String, #[arg(long)] dir: Option, @@ -101,11 +101,11 @@ pub enum NodeCmd { /// Claim accumulated PoS rewards without unstaking Claim { - #[arg(long, env = "GITLAWB_OPERATOR_PRIVATE_KEY")] + #[arg(long, env = "TWIGPINE_OPERATOR_PRIVATE_KEY")] private_key: String, - #[arg(long, env = "GITLAWB_CONTRACT_NODE_STAKING")] + #[arg(long, env = "TWIGPINE_CONTRACT_NODE_STAKING")] contract: String, - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] rpc_url: String, #[arg(long)] dir: Option, @@ -113,11 +113,11 @@ pub enum NodeCmd { /// Request unstake — starts the 7-day cooldown UnstakeRequest { - #[arg(long, env = "GITLAWB_OPERATOR_PRIVATE_KEY")] + #[arg(long, env = "TWIGPINE_OPERATOR_PRIVATE_KEY")] private_key: String, - #[arg(long, env = "GITLAWB_CONTRACT_NODE_STAKING")] + #[arg(long, env = "TWIGPINE_CONTRACT_NODE_STAKING")] contract: String, - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] rpc_url: String, #[arg(long)] dir: Option, @@ -125,11 +125,11 @@ pub enum NodeCmd { /// Complete unstake after the 7-day cooldown — returns stake + pending rewards Unstake { - #[arg(long, env = "GITLAWB_OPERATOR_PRIVATE_KEY")] + #[arg(long, env = "TWIGPINE_OPERATOR_PRIVATE_KEY")] private_key: String, - #[arg(long, env = "GITLAWB_CONTRACT_NODE_STAKING")] + #[arg(long, env = "TWIGPINE_CONTRACT_NODE_STAKING")] contract: String, - #[arg(long, env = "GITLAWB_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] + #[arg(long, env = "TWIGPINE_CHAIN_RPC_URL", default_value = node_stake::default_rpc_url())] rpc_url: String, #[arg(long)] dir: Option, @@ -700,7 +700,7 @@ mod tests { // Mirror of the above for the absent-`--dir` case: `None` must never resolve to // DirUnusable — it degrades to Anonymous (no default keystore) or Keyed (one // present). Env-independent: only the None->DirUnusable mapping is guarded, so it - // holds whether or not the runner has a default `~/.gitlawb` identity. + // holds whether or not the runner has a default `~/.twigpine` identity. #[test] fn resolve_pins_auth_none_is_never_dir_unusable() { assert!( diff --git a/crates/twigpine-cli/src/node_stake.rs b/crates/twigpine-cli/src/node_stake.rs index ffffb101..3299a27a 100644 --- a/crates/twigpine-cli/src/node_stake.rs +++ b/crates/twigpine-cli/src/node_stake.rs @@ -146,9 +146,9 @@ pub async fn cmd_register( println!(" Operator wallet: {operator_addr}"); println!(); println!("Next: set these env vars on the node:"); - println!(" export GITLAWB_CONTRACT_NODE_STAKING={contract}"); - println!(" export GITLAWB_OPERATOR_PRIVATE_KEY="); - println!(" export GITLAWB_CHAIN_RPC_URL={rpc_url}"); + println!(" export TWIGPINE_CONTRACT_NODE_STAKING={contract}"); + println!(" export TWIGPINE_OPERATOR_PRIVATE_KEY="); + println!(" export TWIGPINE_CHAIN_RPC_URL={rpc_url}"); Ok(()) } @@ -328,8 +328,8 @@ pub async fn cmd_unstake( // ── Helpers ───────────────────────────────────────────────────────────────── fn load_did(dir: Option) -> Result { - // The shared resolver, not a local `~/.gitlawb`: `twigpine identity new` writes the - // key wherever `GITLAWB_KEY` points, and the old fallback to `.` on a missing + // The shared resolver, not a local `~/.twigpine`: `twigpine identity new` writes the + // key wherever `TWIGPINE_KEY` points, and the old fallback to `.` on a missing // home made the answer depend on the working directory. let path = crate::identity::key_path_for(dir.as_deref())?; let pem = std::fs::read_to_string(&path).with_context(|| { diff --git a/crates/twigpine-cli/src/peer.rs b/crates/twigpine-cli/src/peer.rs index 7a869562..ab7e2775 100644 --- a/crates/twigpine-cli/src/peer.rs +++ b/crates/twigpine-cli/src/peer.rs @@ -23,7 +23,7 @@ pub enum PeerCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, }, @@ -34,7 +34,7 @@ pub enum PeerCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -47,7 +47,7 @@ pub enum PeerCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, }, @@ -58,7 +58,7 @@ pub enum PeerCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, }, diff --git a/crates/twigpine-cli/src/pr.rs b/crates/twigpine-cli/src/pr.rs index 0a4cfed0..c9308f29 100644 --- a/crates/twigpine-cli/src/pr.rs +++ b/crates/twigpine-cli/src/pr.rs @@ -38,7 +38,7 @@ pub enum PrCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -51,7 +51,7 @@ pub enum PrCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -66,7 +66,7 @@ pub enum PrCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -81,7 +81,7 @@ pub enum PrCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -96,7 +96,7 @@ pub enum PrCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -117,7 +117,7 @@ pub enum PrCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -135,7 +135,7 @@ pub enum PrCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -150,7 +150,7 @@ pub enum PrCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] diff --git a/crates/twigpine-cli/src/profile.rs b/crates/twigpine-cli/src/profile.rs index 3f4904f9..f26461a2 100644 --- a/crates/twigpine-cli/src/profile.rs +++ b/crates/twigpine-cli/src/profile.rs @@ -62,7 +62,7 @@ pub enum ProfileCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, @@ -77,7 +77,7 @@ pub enum ProfileCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, @@ -95,7 +95,7 @@ pub enum ProfileCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, }, @@ -113,7 +113,7 @@ pub enum ProfileCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, @@ -128,7 +128,7 @@ pub enum ProfileCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, @@ -508,7 +508,7 @@ mod tests { // Header present: the client recognises the code up front. let err = set_against( 429, - &[("x-gitlawb-error", "rate_limited")], + &[("x-twigpine-error", "rate_limited")], r#"{"error":"rate_limited","message":"rate limit exceeded — try again later"}"#, ) .await; diff --git a/crates/twigpine-cli/src/protect.rs b/crates/twigpine-cli/src/protect.rs index 2c277a29..b731d8d4 100644 --- a/crates/twigpine-cli/src/protect.rs +++ b/crates/twigpine-cli/src/protect.rs @@ -25,7 +25,7 @@ pub enum ProtectCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -40,7 +40,7 @@ pub enum ProtectCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -53,7 +53,7 @@ pub enum ProtectCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] diff --git a/crates/twigpine-cli/src/quickstart.rs b/crates/twigpine-cli/src/quickstart.rs index 4ff743d1..ac813413 100644 --- a/crates/twigpine-cli/src/quickstart.rs +++ b/crates/twigpine-cli/src/quickstart.rs @@ -20,10 +20,10 @@ const PUBLIC_NODE: &str = "https://node.twigpine.com"; #[derive(Args)] pub struct QuickstartArgs { /// Node URL to register with - #[arg(long, default_value = PUBLIC_NODE, env = "GITLAWB_NODE")] + #[arg(long, default_value = PUBLIC_NODE, env = "TWIGPINE_NODE")] pub node: String, - /// Identity directory (default: the parent of $GITLAWB_KEY, else ~/.gitlawb) + /// Identity directory (default: the parent of $TWIGPINE_KEY, else ~/.twigpine) #[arg(long)] pub dir: Option, @@ -34,15 +34,15 @@ pub struct QuickstartArgs { pub async fn run(args: QuickstartArgs) -> Result<()> { println!(); - println!("Welcome to gitlawb."); + println!("Welcome to Twigpine."); println!("This wizard will set up your identity, register you with a node,"); println!("and create your first repository."); println!(); // The wizard generates the identity AND stores the bootstrap UCAN, so it has to - // land where every later command reads from — the parent of `GITLAWB_KEY`, not - // an unconditional `~/.gitlawb`. - let dir = crate::identity::gitlawb_dir(args.dir.clone())?; + // land where every later command reads from — the parent of `TWIGPINE_KEY`, not + // an unconditional `~/.twigpine`. + let dir = crate::identity::identity_dir(args.dir.clone())?; // ── Step 1: Identity ────────────────────────────────────────────────── println!("── Step 1: Identity ─────────────────────────────────────────────────"); @@ -52,7 +52,7 @@ pub async fn run(args: QuickstartArgs) -> Result<()> { let keypair = if pem_path.exists() { // `args.dir.as_deref()`, not `Some(&dir)`. Passing the DIRECTORY made the // loader re-derive the basename as `identity.pem`, so with - // `GITLAWB_KEY=/data/keys/ci-agent.pem` the check above found `ci-agent.pem` + // `TWIGPINE_KEY=/data/keys/ci-agent.pem` the check above found `ci-agent.pem` // while the load looked for a sibling that need not exist. The load must // target the file that was actually selected, and a file that exists but // fails to load is refused below, never regenerated over: `pem_path` can @@ -74,6 +74,7 @@ pub async fn run(args: QuickstartArgs) -> Result<()> { } } } else { + crate::identity::refuse_if_stranded(&pem_path)?; println!(" No identity found. Generating a new Ed25519 keypair..."); generate_identity(&dir, &pem_path)? }; diff --git a/crates/twigpine-cli/src/register.rs b/crates/twigpine-cli/src/register.rs index d219266a..720352be 100644 --- a/crates/twigpine-cli/src/register.rs +++ b/crates/twigpine-cli/src/register.rs @@ -18,13 +18,13 @@ pub struct RegisterArgs { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] pub node: String, /// A pre-obtained iCaptcha proof token, forwarded on the register request /// instead of making the client solve a fresh challenge. - #[arg(long, env = "GITLAWB_ICAPTCHA_PROOF")] + #[arg(long, env = "TWIGPINE_ICAPTCHA_PROOF")] pub icaptcha_proof: Option, /// Capabilities to advertise (comma-separated) @@ -39,7 +39,7 @@ pub struct RegisterArgs { #[arg(long)] pub model: Option, - /// Identity directory (default: the parent of $GITLAWB_KEY, else ~/.gitlawb) + /// Identity directory (default: the parent of $TWIGPINE_KEY, else ~/.twigpine) #[arg(long)] pub dir: Option, } @@ -103,8 +103,8 @@ pub async fn run(args: RegisterArgs) -> Result<()> { println!(" Trust score: {trust:.2}"); println!(" UCAN expires: {}", sanitize_node_msg(expires)); println!(); - // The real path, not the default one: `GITLAWB_KEY` moves it, and an operator - // told to look in `~/.gitlawb` would find nothing there. + // The real path, not the default one: `TWIGPINE_KEY` moves it, and an operator + // told to look in `~/.twigpine` would find nothing there. // Registration without a stored token means the registration-gated // capabilities never arrived, so the closing line must not claim they did. match &saved_to { @@ -125,13 +125,13 @@ pub async fn run(args: RegisterArgs) -> Result<()> { /// Where the bootstrap UCAN is stored: beside the identity key, always. /// -/// Routed through `gitlawb_dir` rather than resolving `~/.gitlawb` locally. The -/// key is READ from the parent of `GITLAWB_KEY`, so writing the token anywhere +/// Routed through `identity_dir` rather than resolving `~/.twigpine` locally. The +/// key is READ from the parent of `TWIGPINE_KEY`, so writing the token anywhere /// else splits the two: registration succeeds, and `twigpine doctor`, `twigpine ucan show`, /// `twigpine init`, and `twigpine mcp ucan_show` all read `ucan.json` from the key's /// directory and report an unregistered identity. fn ucan_path(dir: Option<&std::path::Path>) -> Result { - let base = crate::identity::gitlawb_dir(dir.map(std::path::Path::to_path_buf))?; + let base = crate::identity::identity_dir(dir.map(std::path::Path::to_path_buf))?; crate::secret_file::create_dir(&base) .with_context(|| format!("failed to create {}", base.display()))?; Ok(base.join("ucan.json")) @@ -211,8 +211,8 @@ mod tests { m.assert(); } - /// `twigpine register` READS the identity from the parent of `GITLAWB_KEY`, so it has - /// to WRITE the bootstrap token there too. Sending it to `~/.gitlawb` instead is + /// `twigpine register` READS the identity from the parent of `TWIGPINE_KEY`, so it has + /// to WRITE the bootstrap token there too. Sending it to `~/.twigpine` instead is /// silent split-brain: registration prints success, and every command that later /// reads `ucan.json` — `twigpine doctor`, `twigpine ucan show`, `twigpine init`, `twigpine mcp` — looks /// beside the key, finds nothing, and reports an unregistered identity. @@ -220,7 +220,7 @@ mod tests { async fn register_saves_the_bootstrap_ucan_beside_the_key() { let dir = TempDir::new().unwrap(); write_identity(&dir); - // No --dir: the destination has to come from GITLAWB_KEY alone. + // No --dir: the destination has to come from TWIGPINE_KEY alone. let _env = crate::identity::test_env::set_key(Some(dir.path().join("identity.pem"))); let mut server = mockito::Server::new_async().await; @@ -247,7 +247,7 @@ mod tests { let beside_the_key = dir.path().join("ucan.json"); assert!( beside_the_key.exists(), - "the bootstrap UCAN must land beside GITLAWB_KEY, not in ~/.gitlawb" + "the bootstrap UCAN must land beside TWIGPINE_KEY, not in ~/.twigpine" ); let content: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(beside_the_key).unwrap()).unwrap(); diff --git a/crates/twigpine-cli/src/repo.rs b/crates/twigpine-cli/src/repo.rs index 762466fd..7687d712 100644 --- a/crates/twigpine-cli/src/repo.rs +++ b/crates/twigpine-cli/src/repo.rs @@ -28,7 +28,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -39,7 +39,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -51,7 +51,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -63,7 +63,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -82,7 +82,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -98,7 +98,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -111,7 +111,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -124,7 +124,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -136,7 +136,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -149,7 +149,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -169,7 +169,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -182,7 +182,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -195,7 +195,7 @@ pub enum RepoCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -489,6 +489,8 @@ async fn cmd_clone(name: String, node: String, dir: Option) -> Result<( .arg("clone") .arg(&url) // Point the remote helper at the same node the user selected. + .env("TWIGPINE_NODE", &node) + // The helper on PATH may be a build from before the rename. .env("GITLAWB_NODE", &node) .status() .context("failed to run git clone — is git installed?")?; @@ -999,7 +1001,7 @@ mod tests { async fn fork_surfaces_a_rate_limit_brake_not_invalid_json() { let err = fork_against( 429, - &[("x-gitlawb-error", "rate_limited")], + &[("x-twigpine-error", "rate_limited")], r#"{"error":"rate_limited","message":"rate limit exceeded — try again later"}"#, ) .await; diff --git a/crates/twigpine-cli/src/secret_file.rs b/crates/twigpine-cli/src/secret_file.rs index 6cc7a6bf..c63920ed 100644 --- a/crates/twigpine-cli/src/secret_file.rs +++ b/crates/twigpine-cli/src/secret_file.rs @@ -64,7 +64,7 @@ pub(crate) fn write_new(path: &Path, contents: &[u8]) -> std::io::Result<()> { /// Create `path` (and missing parents) as an owner-only directory. /// -/// An existing directory is also re-pinned: a `~/.gitlawb` created before +/// An existing directory is also re-pinned: a `~/.twigpine` created before /// this helper stays group- and world-listable otherwise. A symlinked /// `path` is left alone rather than chmodded through, which would strip /// group and world access from whatever the link points at. diff --git a/crates/twigpine-cli/src/star.rs b/crates/twigpine-cli/src/star.rs index a244b89e..1104263f 100644 --- a/crates/twigpine-cli/src/star.rs +++ b/crates/twigpine-cli/src/star.rs @@ -22,7 +22,7 @@ pub enum StarCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -35,7 +35,7 @@ pub enum StarCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -48,7 +48,7 @@ pub enum StarCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] diff --git a/crates/twigpine-cli/src/status.rs b/crates/twigpine-cli/src/status.rs index c649a454..b23a038b 100644 --- a/crates/twigpine-cli/src/status.rs +++ b/crates/twigpine-cli/src/status.rs @@ -13,7 +13,7 @@ pub struct StatusArgs { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] pub node: String, #[arg(long)] diff --git a/crates/twigpine-cli/src/sync.rs b/crates/twigpine-cli/src/sync.rs index 61ccef19..c5374b8d 100644 --- a/crates/twigpine-cli/src/sync.rs +++ b/crates/twigpine-cli/src/sync.rs @@ -13,7 +13,7 @@ pub struct SyncArgs { /// Node URL #[arg( long, - env = "GITLAWB_NODE", + env = "TWIGPINE_NODE", default_value = "https://node.twigpine.com" )] pub node: String, diff --git a/crates/twigpine-cli/src/task.rs b/crates/twigpine-cli/src/task.rs index a310ee52..e6b9456c 100644 --- a/crates/twigpine-cli/src/task.rs +++ b/crates/twigpine-cli/src/task.rs @@ -42,7 +42,7 @@ pub enum TaskCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -65,7 +65,7 @@ pub enum TaskCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -77,7 +77,7 @@ pub enum TaskCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -89,7 +89,7 @@ pub enum TaskCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -103,7 +103,7 @@ pub enum TaskCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -117,7 +117,7 @@ pub enum TaskCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] diff --git a/crates/twigpine-cli/src/ucan_cmd.rs b/crates/twigpine-cli/src/ucan_cmd.rs index 95d1a19d..0056a451 100644 --- a/crates/twigpine-cli/src/ucan_cmd.rs +++ b/crates/twigpine-cli/src/ucan_cmd.rs @@ -445,7 +445,7 @@ pub(crate) async fn import_delegation( // already holds `identity.pem`, whose disclosure is strictly worse than a // delegation's. `create_private_dir` and `write_private_file` below carry the // per-platform reasoning. - let base = crate::identity::gitlawb_dir(dir.map(std::path::Path::to_path_buf))?; + let base = crate::identity::identity_dir(dir.map(std::path::Path::to_path_buf))?; let store = base.join("delegations"); create_private_dir(&store).with_context(|| format!("could not create {}", store.display()))?; @@ -646,7 +646,7 @@ fn write_private_file(path: &std::path::Path, contents: &[u8]) -> std::io::Resul Ok(()) } -// `std::fs` has no portable ACL API, and `gitlawb_dir` accepts any directory, so +// `std::fs` has no portable ACL API, and `identity_dir` accepts any directory, so // the contract off Unix is that the caller supplies a user-private directory — // which is what the platform's per-user profile gives by default. The private key // sits in the same directory under the same assumption, and its disclosure is @@ -773,7 +773,7 @@ async fn cmd_delegate( } async fn cmd_show(dir: Option) -> Result<()> { - let ucan_path = crate::identity::gitlawb_dir(dir)?.join("ucan.json"); + let ucan_path = crate::identity::identity_dir(dir)?.join("ucan.json"); if !ucan_path.exists() { println!("No UCAN saved. Run `twigpine register` first."); diff --git a/crates/twigpine-cli/src/visibility.rs b/crates/twigpine-cli/src/visibility.rs index 40a8ae49..351c7170 100644 --- a/crates/twigpine-cli/src/visibility.rs +++ b/crates/twigpine-cli/src/visibility.rs @@ -30,7 +30,7 @@ pub enum VisibilityCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -44,7 +44,7 @@ pub enum VisibilityCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -57,7 +57,7 @@ pub enum VisibilityCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] diff --git a/crates/twigpine-cli/src/webhook.rs b/crates/twigpine-cli/src/webhook.rs index 2900eaec..99b37295 100644 --- a/crates/twigpine-cli/src/webhook.rs +++ b/crates/twigpine-cli/src/webhook.rs @@ -28,13 +28,13 @@ pub enum WebhookCmd { /// pull_request.closed, push, * #[arg(long, default_value = "*")] events: String, - /// Optional HMAC secret for payload signing (sets X-Gitlawb-Signature-256) + /// Optional HMAC secret for payload signing (sets X-Twigpine-Signature-256) #[arg(long)] secret: Option, #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -47,7 +47,7 @@ pub enum WebhookCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] @@ -62,7 +62,7 @@ pub enum WebhookCmd { #[arg( long, default_value = "https://node.twigpine.com", - env = "GITLAWB_NODE" + env = "TWIGPINE_NODE" )] node: String, #[arg(long)] diff --git a/crates/twigpine-cli/src/whoami.rs b/crates/twigpine-cli/src/whoami.rs index 20fd657a..fa497ced 100644 --- a/crates/twigpine-cli/src/whoami.rs +++ b/crates/twigpine-cli/src/whoami.rs @@ -10,11 +10,11 @@ use crate::identity::load_keypair_from_dir; #[derive(Args)] pub struct WhoamiArgs { - /// Identity directory (default: the parent of $GITLAWB_KEY, else ~/.gitlawb) + /// Identity directory (default: the parent of $TWIGPINE_KEY, else ~/.twigpine) #[arg(long)] dir: Option, /// Node URL to query for registration info - #[arg(long, env = "GITLAWB_NODE")] + #[arg(long, env = "TWIGPINE_NODE")] node: Option, /// Output structured JSON for scripting #[arg(long)] diff --git a/crates/twigpine-cli/tests/doctor_exit.rs b/crates/twigpine-cli/tests/doctor_exit.rs index 8ef2fcb7..9af405e7 100644 --- a/crates/twigpine-cli/tests/doctor_exit.rs +++ b/crates/twigpine-cli/tests/doctor_exit.rs @@ -1,7 +1,7 @@ //! #357: pin the `twigpine doctor` exit-code wiring, not just the predicate. //! //! The unit tests for `has_failures` never touch `std::process::exit(1)` or -//! the `GITLAWB_NODE` Warn tier. Deleting the exit gate outright kept +//! the `TWIGPINE_NODE` Warn tier. Deleting the exit gate outright kept //! `cargo test -p twigpine-cli doctor::` green, so this binary probe is the only thing //! that breaks when the wiring is gutted. @@ -22,12 +22,13 @@ fn doctor_exits_nonzero_when_fail_rows_present() { "--node", "http://127.0.0.1:1", ]) - // Inherit PATH but neutralize GITLAWB_NODE so the test is deterministic + // Inherit PATH but neutralize TWIGPINE_NODE so the test is deterministic // across machines that have it set (otherwise it would be Pass). + .env_remove("TWIGPINE_NODE") .env_remove("GITLAWB_NODE") // iCaptcha probes a real URL by default; keep it unreachable too so // it stays Warn and does not affect the Fail gating. - .env("GITLAWB_ICAPTCHA_URL", "http://127.0.0.1:1") + .env("TWIGPINE_ICAPTCHA_URL", "http://127.0.0.1:1") .output() .expect("run twigpine doctor"); diff --git a/crates/twigpine-cli/tests/doctor_transport_node.rs b/crates/twigpine-cli/tests/doctor_transport_node.rs index a316965c..d20f125d 100644 --- a/crates/twigpine-cli/tests/doctor_transport_node.rs +++ b/crates/twigpine-cli/tests/doctor_transport_node.rs @@ -2,7 +2,7 @@ //! //! `twigpine`'s `--node` defaults to the public node while `git-remote-twigpine` falls //! back to a local one, and an explicit `--node` outranks the environment. So the -//! two disagree whenever GITLAWB_NODE is unset, blank, or overridden, and doctor's +//! two disagree whenever TWIGPINE_NODE is unset, blank, or overridden, and doctor's //! own `node` row describes a URL `git clone` and `git push` never contact. use std::io::{Read, Write}; @@ -112,29 +112,40 @@ fn doctor_with(env_node: Option<&str>, node_flag: Option<&str>, extra_env: &[(&s if let Some(n) = node_flag { cmd.args(["--node", n]); } + // No setting from the developer's shell reaches the run, under either + // name: an exported TWIGPINE_ALLOW_INSECURE_HTTP or GITLAWB_NODE would + // change what these tests observe. Cleared first, so the settings the + // test sets below survive. Upper-cased because Windows treats names as + // case-insensitive. + for (name, _) in std::env::vars_os() { + let upper = name.to_string_lossy().to_ascii_uppercase(); + if upper.starts_with("GITLAWB_") || upper.starts_with("TWIGPINE_") { + cmd.env_remove(name); + } + } cmd.arg("--dir") .arg(dir.path().join("gitlawb")) - .env("GITLAWB_ICAPTCHA_URL", "http://127.0.0.1:1") + .env("TWIGPINE_ICAPTCHA_URL", "http://127.0.0.1:1") .env( - "GITLAWB_GITHUB_API_URL", + "TWIGPINE_GITHUB_API_URL", format!("http://127.0.0.1:{release_port}"), ); for v in PROXY_VARS { cmd.env_remove(v); } + match env_node { + Some(v) => cmd.env("TWIGPINE_NODE", v), + None => cmd.env_remove("TWIGPINE_NODE"), + }; for (k, v) in extra_env { cmd.env(k, v); } - match env_node { - Some(v) => cmd.env("GITLAWB_NODE", v), - None => cmd.env_remove("GITLAWB_NODE"), - }; let out = cmd.output().unwrap(); // Under a configured proxy the lookup goes to the proxy fixture, not this one, // so the fixture-boundary check only applies to the unproxied runs. let proxied = extra_env .iter() - .any(|(k, _)| *k == "HTTP_PROXY" || *k == "GITLAWB_GITHUB_API_URL"); + .any(|(k, _)| *k == "HTTP_PROXY" || *k == "TWIGPINE_GITHUB_API_URL"); assert!( proxied || release_hits.load(Ordering::SeqCst) >= 1, "the release lookup never reached the fixture, so it went to the public API" @@ -144,7 +155,7 @@ fn doctor_with(env_node: Option<&str>, node_flag: Option<&str>, extra_env: &[(&s } } -/// GITLAWB_NODE unset: the helper falls back to the local node, twigpine targets the +/// TWIGPINE_NODE unset: the helper falls back to the local node, twigpine targets the /// public one, so the row must name the local node as the transport target. #[test] fn unset_env_reports_the_transport_node() { @@ -200,7 +211,7 @@ fn agreeing_env_and_flag_produce_no_divergence_row() { } /// `--node` equal to the transport default says nothing about whether the user -/// set `GITLAWB_NODE`. With the variable unset the row must stay the advisory +/// set `TWIGPINE_NODE`. With the variable unset the row must stay the advisory /// "not set" Warn, not a Pass describing a configured loopback node. #[test] fn unset_env_with_flag_equal_to_transport_default_still_warns_not_set() { @@ -208,8 +219,8 @@ fn unset_env_with_flag_equal_to_transport_default_still_warns_not_set() { let row = r .stdout .lines() - .find(|l| l.contains("GITLAWB_NODE")) - .unwrap_or_else(|| panic!("no GITLAWB_NODE row in:\n{}", r.stdout)); + .find(|l| l.contains("TWIGPINE_NODE")) + .unwrap_or_else(|| panic!("no TWIGPINE_NODE row in:\n{}", r.stdout)); assert!( row.contains("not set"), "unset env must report 'not set', got row {row:?} in:\n{}", @@ -274,7 +285,7 @@ fn control_characters_in_the_node_url_are_stripped() { let owned: String = r .stdout .lines() - .filter(|l| l.contains(DIVERGENCE) || l.trim_start().starts_with("GITLAWB_NODE:")) + .filter(|l| l.contains(DIVERGENCE) || l.trim_start().starts_with("TWIGPINE_NODE:")) .collect::>() .join("\n"); assert!( @@ -320,7 +331,7 @@ fn an_unset_env_adds_no_failing_row() { .filter(|l| l.trim_start().starts_with('\u{2717}')) .collect(); assert!( - failing.iter().all(|l| !l.contains("GITLAWB_NODE")), + failing.iter().all(|l| !l.contains("TWIGPINE_NODE")), "an unset variable must stay advisory, got failing rows: {failing:?}" ); assert!(r.divergence_line().is_some(), "got:\n{}", r.stdout); @@ -330,7 +341,7 @@ fn an_unset_env_adds_no_failing_row() { fn fix_line(r: &Run) -> &str { r.stdout .lines() - .find(|l| l.trim_start().starts_with("GITLAWB_NODE:")) + .find(|l| l.trim_start().starts_with("TWIGPINE_NODE:")) .unwrap_or("") } @@ -417,7 +428,7 @@ fn a_node_reachable_only_through_the_configured_proxy_is_reachable() { Some("http://127.0.0.1:1"), &[ ("HTTP_PROXY", &format!("http://127.0.0.1:{proxy}")), - ("GITLAWB_ALLOW_INSECURE_HTTP", "1"), + ("TWIGPINE_ALLOW_INSECURE_HTTP", "1"), ], ); let line = r @@ -476,7 +487,7 @@ fn a_loopback_node_is_never_sent_through_a_live_proxy() { } /// The helper refuses a non-loopback `http://` node before sending anything unless -/// `GITLAWB_ALLOW_INSECURE_HTTP` is truthy. Doctor must report that refusal, as a +/// `TWIGPINE_ALLOW_INSECURE_HTTP` is truthy. Doctor must report that refusal, as a /// failure because the user set the variable, and must not contact the node. #[test] fn a_plaintext_remote_node_is_refused_like_the_helper_and_never_probed() { @@ -521,7 +532,7 @@ fn the_plaintext_refusal_follows_the_helpers_opt_in_parsing() { Some("http://127.0.0.1:1"), &[ ("HTTP_PROXY", &proxy_env), - ("GITLAWB_ALLOW_INSECURE_HTTP", val), + ("TWIGPINE_ALLOW_INSECURE_HTTP", val), ], ); let line = r @@ -605,7 +616,7 @@ fn an_oversized_probe_body_is_rejected_not_parsed() { assert!(!line.contains("(reachable)"), "got: {line}"); } -/// Blank GITLAWB_NODE with no `--node`: clap hands doctor the raw blank value, and +/// Blank TWIGPINE_NODE with no `--node`: clap hands doctor the raw blank value, and /// the remedy must not reproduce it. It names the public node instead. #[test] fn a_blank_env_remedy_does_not_reproduce_the_blank_value() { @@ -613,7 +624,7 @@ fn a_blank_env_remedy_does_not_reproduce_the_blank_value() { let r = doctor_with(Some(blank), None, &[]); let fix = fix_line(&r); assert!( - fix.contains("export GITLAWB_NODE='https://node.twigpine.com'"), + fix.contains("export TWIGPINE_NODE='https://node.twigpine.com'"), "blank {blank:?} must be replaced by a valid target, got: {fix:?}\n{}", r.stdout ); @@ -631,7 +642,7 @@ fn an_apostrophe_in_the_node_value_cannot_break_out_of_the_remedy() { ); } -/// `GITLAWB_NODE` may carry a path prefix (a reverse-proxied `https://host/mount`), +/// `TWIGPINE_NODE` may carry a path prefix (a reverse-proxied `https://host/mount`), /// with identity served at exactly that prefix and nothing at `/mount/`. The probe /// must request the configured base verbatim, as the helper does. #[test] @@ -668,7 +679,10 @@ fn a_hostile_release_tag_cannot_reach_the_terminal_raw() { let r = doctor_with( None, Some("http://127.0.0.1:1"), - &[("GITLAWB_GITHUB_API_URL", &format!("http://127.0.0.1:{api}"))], + &[( + "TWIGPINE_GITHUB_API_URL", + &format!("http://127.0.0.1:{api}"), + )], ); assert!(hits.load(Ordering::SeqCst) >= 1, "fixture never hit"); assert!( @@ -726,7 +740,7 @@ fn invalid_utf8_in_the_identity_body_is_not_a_reachable_node() { } } -/// A padded `GITLAWB_NODE` with no `--node` resolves to the trimmed URL for the +/// A padded `TWIGPINE_NODE` with no `--node` resolves to the trimmed URL for the /// transport, so the connectivity row must dial the trimmed URL too instead of /// failing to parse ` http://host:port /`. #[test] @@ -744,7 +758,7 @@ fn a_padded_env_node_is_dialed_trimmed_by_the_connectivity_row() { ); } -/// clap binds `--node` from `GITLAWB_NODE` verbatim, while the transport resolver +/// clap binds `--node` from `TWIGPINE_NODE` verbatim, while the transport resolver /// trims it. A padded value therefore resolves to the same node on both sides, and /// doctor must not read the whitespace difference as a divergence: no divergence /// clause, and the env row classified as the configured loopback node (Pass), @@ -762,8 +776,8 @@ fn a_padded_env_node_is_not_a_divergence() { let row = r .stdout .lines() - .find(|l| l.contains("GITLAWB_NODE") && !l.trim_start().starts_with("GITLAWB_NODE:")) - .unwrap_or_else(|| panic!("no GITLAWB_NODE row, got:\n{}", r.stdout)); + .find(|l| l.contains("TWIGPINE_NODE") && !l.trim_start().starts_with("TWIGPINE_NODE:")) + .unwrap_or_else(|| panic!("no TWIGPINE_NODE row, got:\n{}", r.stdout)); assert!( !row.trim_start().starts_with('\u{2717}'), "padding alone must not fail the env row (node up: {up}): {row}" @@ -774,3 +788,48 @@ fn a_padded_env_node_is_not_a_divergence() { ); } } + +/// The `settings` row doctor prints when a setting was given under its name +/// from before the rename. +fn settings_row(r: &Run) -> Option<&str> { + // The row itself, not the fix hint printed under it. + r.stdout + .lines() + .find(|l| l.contains("under the old GITLAWB_ name") || l.contains("TWIGPINE_ wins")) +} + +#[test] +fn a_setting_under_its_old_name_still_selects_the_node() { + let (port, hits) = serve(|_, _| did_ok()); + let url = format!("http://127.0.0.1:{port}"); + // No --node and no TWIGPINE_NODE: the old name is the only source. + let r = doctor_with(None, None, &[("GITLAWB_NODE", &url)]); + assert!( + hits.load(Ordering::SeqCst) > 0, + "the node named by GITLAWB_NODE was never contacted:\n{}", + r.stdout + ); + let row = settings_row(&r).unwrap_or_else(|| panic!("no settings row:\n{}", r.stdout)); + assert!(row.contains("TWIGPINE_NODE"), "{row}"); +} + +#[test] +fn the_new_name_wins_over_the_old_one_and_doctor_says_so() { + let (new_port, new_hits) = serve(|_, _| did_ok()); + let (old_port, old_hits) = serve(|_, _| did_ok()); + let new_url = format!("http://127.0.0.1:{new_port}"); + let old_url = format!("http://127.0.0.1:{old_port}"); + let r = doctor_with(Some(&new_url), None, &[("GITLAWB_NODE", &old_url)]); + assert!(new_hits.load(Ordering::SeqCst) > 0, "{}", r.stdout); + assert_eq!(old_hits.load(Ordering::SeqCst), 0, "{}", r.stdout); + let row = settings_row(&r).unwrap_or_else(|| panic!("no settings row:\n{}", r.stdout)); + assert!(row.contains("TWIGPINE_ wins"), "{row}"); +} + +#[test] +fn no_settings_row_without_an_old_name() { + let (port, _) = serve(|_, _| did_ok()); + let url = format!("http://127.0.0.1:{port}"); + let r = doctor_with(Some(&url), None, &[]); + assert!(settings_row(&r).is_none(), "{}", r.stdout); +} diff --git a/crates/twigpine-cli/tests/identity_left_in_old_folder.rs b/crates/twigpine-cli/tests/identity_left_in_old_folder.rs new file mode 100644 index 00000000..abcc87ab --- /dev/null +++ b/crates/twigpine-cli/tests/identity_left_in_old_folder.rs @@ -0,0 +1,146 @@ +//! A key left in `~/.gitlawb` from before the rename, beside a `~/.twigpine` +//! that has none, must never lead to a second identity. +//! +//! Once `~/.twigpine` exists it is the only folder read, so every command that +//! can create a key would otherwise find "no identity" and make a new one. The +//! user would end up with a DID their repositories and delegations do not +//! belong to. These run the real binary against a scratch home. + +#![cfg(unix)] + +use std::path::Path; +use std::process::{Command, Output}; + +/// A home with the key in the old folder and an empty new folder. +fn stranded_home() -> tempfile::TempDir { + let home = tempfile::tempdir().unwrap(); + std::fs::create_dir(home.path().join(".gitlawb")).unwrap(); + std::fs::write(home.path().join(".gitlawb/identity.pem"), b"not read").unwrap(); + std::fs::create_dir(home.path().join(".twigpine")).unwrap(); + home +} + +/// `twigpine ` with only this home: no setting from the developer's +/// shell, under either name, reaches the run. +fn twigpine(home: &Path, args: &[&str]) -> Output { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_twigpine")); + cmd.args(args) + .env("HOME", home) + .stdin(std::process::Stdio::null()); + for (name, _) in std::env::vars_os() { + let upper = name.to_string_lossy().to_ascii_uppercase(); + if upper.starts_with("GITLAWB_") || upper.starts_with("TWIGPINE_") { + cmd.env_remove(name); + } + } + // Nothing here may reach a network; a node that refuses connections makes + // any attempt fail fast instead of hanging. + // doctor also looks up iCaptcha and the latest release; both go to the + // same refusing address. + cmd.env("TWIGPINE_NODE", "http://127.0.0.1:1") + .env("TWIGPINE_ICAPTCHA_URL", "http://127.0.0.1:1") + .env("TWIGPINE_GITHUB_API_URL", "http://127.0.0.1:1"); + cmd.output().unwrap() +} + +fn text(out: &Output) -> String { + format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) +} + +fn assert_no_new_key(home: &Path) { + assert!( + !home.join(".twigpine/identity.pem").exists(), + "a second identity was created in ~/.twigpine" + ); + assert_eq!( + std::fs::read(home.join(".gitlawb/identity.pem")).unwrap(), + b"not read", + "the original key must be untouched" + ); +} + +/// The refusal names both folders, so the user knows where the key is and +/// what to do. +fn assert_points_at_old_folder(out: &Output) { + let t = text(out); + assert!(t.contains(".gitlawb") && t.contains(".twigpine"), "{t}"); +} + +#[test] +fn identity_new_refuses() { + let home = stranded_home(); + let out = twigpine(home.path(), &["identity", "new"]); + assert!(!out.status.success(), "{}", text(&out)); + assert_points_at_old_folder(&out); + assert_no_new_key(home.path()); +} + +#[test] +fn identity_new_with_force_is_the_deliberate_way_to_start_over() { + let home = stranded_home(); + let out = twigpine(home.path(), &["identity", "new", "--force"]); + assert!(out.status.success(), "{}", text(&out)); + assert!(home.path().join(".twigpine/identity.pem").exists()); + assert_eq!( + std::fs::read(home.path().join(".gitlawb/identity.pem")).unwrap(), + b"not read", + "the old key is left where it was" + ); +} + +#[test] +fn quickstart_refuses_before_reaching_a_node() { + let home = stranded_home(); + let out = twigpine(home.path(), &["quickstart", "--yes"]); + assert!(!out.status.success(), "{}", text(&out)); + assert_points_at_old_folder(&out); + assert_no_new_key(home.path()); +} + +#[test] +fn init_refuses_before_reaching_a_node() { + let home = stranded_home(); + let repo = tempfile::tempdir().unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_twigpine")) + .arg("init") + .current_dir(repo.path()) + .env("HOME", home.path()) + .env("TWIGPINE_NODE", "http://127.0.0.1:1") + .env_remove("TWIGPINE_KEY") + .env_remove("GITLAWB_KEY") + .env_remove("GITLAWB_NODE") + .output() + .unwrap(); + assert!(!out.status.success(), "{}", text(&out)); + assert_points_at_old_folder(&out); + assert_no_new_key(home.path()); +} + +#[test] +fn identity_show_says_where_the_key_is() { + let home = stranded_home(); + let out = twigpine(home.path(), &["identity", "show"]); + assert!(!out.status.success(), "{}", text(&out)); + assert_points_at_old_folder(&out); +} + +#[test] +fn doctor_points_at_the_old_folder_not_at_identity_new() { + let home = stranded_home(); + let out = twigpine(home.path(), &["doctor"]); + let t = text(&out); + let identity_row = t + .lines() + .find(|l| l.contains("identity") && l.contains("not found")) + .unwrap_or_else(|| panic!("no identity row:\n{t}")); + assert!(identity_row.contains(".gitlawb"), "{identity_row}"); + assert!( + !t.contains("twigpine identity new\n"), + "doctor must not advise a new identity here:\n{t}" + ); + assert_no_new_key(home.path()); +} diff --git a/crates/twigpine-core/src/identity_path.rs b/crates/twigpine-core/src/identity_path.rs index f28f4bab..3ab0d5ed 100644 --- a/crates/twigpine-core/src/identity_path.rs +++ b/crates/twigpine-core/src/identity_path.rs @@ -3,7 +3,7 @@ //! `twigpine` and `git-remote-twigpine` have to agree on this. `twigpine ucan import` writes a //! delegation to `/delegations/`, and the helper reads it back from the same //! place when it builds the `X-Ucan` header on push. If the two resolve -//! `GITLAWB_KEY` differently the push goes out with no header and the node refuses +//! `TWIGPINE_KEY` differently the push goes out with no header and the node refuses //! the delegate, with nothing on either side to say why — so the rules live here //! once, in the crate both binaries already depend on, rather than being written //! twice and drifting. @@ -20,18 +20,76 @@ use std::path::{Component, Path, PathBuf}; use crate::{Error, Result}; /// Environment variable naming the identity PEM. -pub const KEY_ENV: &str = "GITLAWB_KEY"; +pub const KEY_ENV: &str = "TWIGPINE_KEY"; /// Name of the PEM file inside the identity directory. pub const KEY_FILE_NAME: &str = "identity.pem"; -/// Directory under the home directory used when `GITLAWB_KEY` is unset. -pub const DEFAULT_DIR_NAME: &str = ".gitlawb"; +/// Directory under the home directory used when `TWIGPINE_KEY` is unset. +pub const DEFAULT_DIR_NAME: &str = ".twigpine"; -/// Absolute path of the identity PEM: `$GITLAWB_KEY`, else -/// `/.gitlawb/identity.pem`. +/// The directory's name before the rename to Twigpine. See [`default_dir`]. +pub const LEGACY_DIR_NAME: &str = ".gitlawb"; + +/// The directory used when `TWIGPINE_KEY` is unset: `/.twigpine`, or an +/// existing `/.gitlawb` when there is no `/.twigpine`. +/// +/// Nothing is moved. An identity created before the rename stays where it is +/// and keeps working; a move that failed halfway could strand the key. Once +/// `/.twigpine` exists (a new install, or the operator renamed the old +/// directory) it is the only one read. +/// +/// The check is on the directory, not on a file in it, so the key, the +/// delegation store and everything else that lives beside the key always +/// resolve to the same place. +pub fn default_dir(home: &Path) -> PathBuf { + let new = home.join(DEFAULT_DIR_NAME); + // `symlink_metadata`: a link named `.twigpine` counts as present even when + // its target is missing, so a broken link is reported where it is instead + // of silently falling back to the old directory. + if new.symlink_metadata().is_err() { + let legacy = home.join(LEGACY_DIR_NAME); + if legacy.is_dir() { + return legacy; + } + } + new +} + +/// The copy of a key file left in the folder from before the rename, when +/// `path` is that file's place in `/.twigpine` and nothing is there. /// -/// An empty `GITLAWB_KEY` counts as unset. That is what a shell leaves behind for +/// This is the one way the folder rule can go wrong: `/.twigpine` came +/// into existence (another tool, a stray `--dir`, a half-finished move) while +/// the keys are still in `/.gitlawb`. Reading on would find no key, and +/// a caller that creates one when none exists would mint a new identity beside +/// a perfectly good one. Callers use this to stop, or to say where the key is. +pub fn stranded_legacy_key(path: &Path, home: Option<&Path>) -> Option { + let home = home?; + if path.parent()? != home.join(DEFAULT_DIR_NAME) || path.symlink_metadata().is_ok() { + return None; + } + let legacy = home.join(LEGACY_DIR_NAME).join(path.file_name()?); + legacy.is_file().then_some(legacy) +} + +/// What to tell someone whose key was found by [`stranded_legacy_key`]. +pub fn stranded_legacy_key_message(path: &Path, legacy: &Path) -> String { + let new_dir = path.parent().unwrap_or(path).display(); + let old_dir = legacy.parent().unwrap_or(legacy).display(); + format!( + "{new_dir} exists but holds no {file}, and there is one at {legacy} from before \ + the rename to Twigpine. Only {new_dir} is read once it exists. Move the contents \ + of {old_dir} into {new_dir}, or remove {new_dir} to keep using {old_dir}.", + file = path.file_name().unwrap_or_default().to_string_lossy(), + legacy = legacy.display(), + ) +} + +/// Absolute path of the identity PEM: `$TWIGPINE_KEY`, else `identity.pem` in +/// [`default_dir`]. +/// +/// An empty `TWIGPINE_KEY` counts as unset. That is what a shell leaves behind for /// `FOO=` and for an unset variable expanded into a wrapper script, and reading it /// as a path would resolve against the process working directory instead. pub fn identity_key_path(home: Option<&Path>) -> Result { @@ -41,9 +99,7 @@ pub fn identity_key_path(home: Option<&Path>) -> Result { // problem. match std::env::var_os(KEY_ENV) { Some(raw) if !raw.is_empty() => resolve_key_value(Path::new(&raw), home), - _ => Ok(require_home(home)? - .join(DEFAULT_DIR_NAME) - .join(KEY_FILE_NAME)), + _ => Ok(default_dir(require_home(home)?).join(KEY_FILE_NAME)), } } @@ -61,7 +117,7 @@ pub fn identity_dir(home: Option<&Path>) -> Result { /// The home directory, demanded only where the value being resolved needs it. /// -/// An absolute `GITLAWB_KEY` never needs home, so requiring it up front would +/// An absolute `TWIGPINE_KEY` never needs home, so requiring it up front would /// discard a perfectly good key on a host where `dirs::home_dir()` returns `None` /// — no `HOME` and no passwd entry, which is an ordinary container shape. The /// helper would then push unsigned, blaming the home directory for a setting the @@ -75,7 +131,7 @@ fn require_home(home: Option<&Path>) -> Result<&Path> { }) } -/// Apply the `GITLAWB_KEY` rules to a raw value. +/// Apply the `TWIGPINE_KEY` rules to a raw value. /// /// Split out from [`identity_key_path`] so the rules can be tested without setting /// a process-global environment variable, which would make the tests race. @@ -164,7 +220,7 @@ mod tests { #[test] fn the_tilde_spelling_of_the_default_resolves_to_the_default() { let resolved = - resolve_key_value(Path::new("~/.gitlawb/identity.pem"), Some(&home())).unwrap(); + resolve_key_value(Path::new("~/.twigpine/identity.pem"), Some(&home())).unwrap(); assert_eq!(resolved, home().join(DEFAULT_DIR_NAME).join(KEY_FILE_NAME)); } @@ -269,7 +325,7 @@ mod no_home_tests { use super::*; /// An absolute key needs no home directory. Demanding one up front discarded a - /// correctly-configured `GITLAWB_KEY` on any host where `dirs::home_dir()` + /// correctly-configured `TWIGPINE_KEY` on any host where `dirs::home_dir()` /// returns `None` — no `HOME` and no passwd entry, an ordinary container shape — /// and the helper then pushed unsigned while blaming the home directory. #[test] @@ -296,4 +352,98 @@ mod no_home_tests { "the error must name the missing home directory, got: {err}" ); } + + /// A scratch home under the system temp directory, removed on drop. + struct ScratchHome(PathBuf); + impl ScratchHome { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!( + "twigpine-core-home-{tag}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + } + impl Drop for ScratchHome { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn default_dir_is_the_new_name_on_a_fresh_home() { + let home = ScratchHome::new("fresh"); + assert_eq!(default_dir(&home.0), home.0.join(".twigpine")); + } + + #[test] + fn default_dir_keeps_an_existing_old_directory() { + let home = ScratchHome::new("old"); + std::fs::create_dir(home.0.join(".gitlawb")).unwrap(); + assert_eq!(default_dir(&home.0), home.0.join(".gitlawb")); + } + + #[test] + fn default_dir_prefers_the_new_directory_once_it_exists() { + let home = ScratchHome::new("both"); + std::fs::create_dir(home.0.join(".gitlawb")).unwrap(); + std::fs::create_dir(home.0.join(".twigpine")).unwrap(); + assert_eq!(default_dir(&home.0), home.0.join(".twigpine")); + } + + #[test] + fn default_dir_ignores_an_old_name_that_is_not_a_directory() { + let home = ScratchHome::new("file"); + std::fs::write(home.0.join(".gitlawb"), b"").unwrap(); + assert_eq!(default_dir(&home.0), home.0.join(".twigpine")); + } + + #[test] + fn a_key_left_in_the_old_folder_is_found_once_the_new_folder_exists() { + let home = ScratchHome::new("stranded"); + let new_key = home.0.join(".twigpine").join(KEY_FILE_NAME); + let old_key = home.0.join(".gitlawb").join(KEY_FILE_NAME); + std::fs::create_dir(home.0.join(".gitlawb")).unwrap(); + std::fs::write(&old_key, b"pem").unwrap(); + + // No new folder yet: the old one is simply the default, nothing stranded. + assert_eq!(default_dir(&home.0), home.0.join(".gitlawb")); + + std::fs::create_dir(home.0.join(".twigpine")).unwrap(); + assert_eq!( + stranded_legacy_key(&new_key, Some(&home.0)), + Some(old_key.clone()) + ); + let msg = stranded_legacy_key_message(&new_key, &old_key); + assert!( + msg.contains(".gitlawb") && msg.contains(".twigpine"), + "{msg}" + ); + + // A different file name, a path outside the default folder, and a key + // that is present are all fine. + assert_eq!( + stranded_legacy_key(&home.0.join(".twigpine/p2p.key"), Some(&home.0)), + None + ); + assert_eq!( + stranded_legacy_key(&home.0.join("keys").join(KEY_FILE_NAME), Some(&home.0)), + None + ); + std::fs::write(&new_key, b"pem").unwrap(); + assert_eq!(stranded_legacy_key(&new_key, Some(&home.0)), None); + assert_eq!(stranded_legacy_key(&new_key, None), None); + } + + #[cfg(unix)] + #[test] + fn default_dir_does_not_fall_back_past_a_broken_new_link() { + let home = ScratchHome::new("link"); + std::fs::create_dir(home.0.join(".gitlawb")).unwrap(); + std::os::unix::fs::symlink(home.0.join("missing"), home.0.join(".twigpine")).unwrap(); + assert_eq!(default_dir(&home.0), home.0.join(".twigpine")); + } } diff --git a/crates/twigpine-core/src/legacy_env.rs b/crates/twigpine-core/src/legacy_env.rs new file mode 100644 index 00000000..2d7f05d6 --- /dev/null +++ b/crates/twigpine-core/src/legacy_env.rs @@ -0,0 +1,346 @@ +//! Settings were named `GITLAWB_*` before the rename to Twigpine. They are +//! `TWIGPINE_*` now, and the old names keep working. +//! +//! Rather than teach every read site two names, each binary calls [`adopt`] +//! once, first thing in `main`. After it returns, both names carry the same +//! value for every setting that was given under either, so the rest of the code +//! reads `TWIGPINE_*` only: +//! +//! - only the old name is set: the new name gets its value; +//! - both are set: the new name wins, and the old one is overwritten to match; +//! - only the new name is set: the old name gets its value too. +//! +//! The last two exist for child processes. `git` runs the remote helper, and the +//! helper on `PATH` may be an older build that reads only the old names. +//! +//! When choosing between the two names, an empty new-name value counts as +//! unset, so `TWIGPINE_KEY=` beside `GITLAWB_KEY=/k.pem` uses the old one (a +//! shell leaves `FOO=` behind for an unset variable expanded into a wrapper +//! script). +//! +//! That is the whole of the rule. This module only decides which name +//! supplies a value; it never removes a variable. A setting that is empty +//! under every name it was given reaches its reader empty, exactly as it did +//! before the rename: some settings treat that as "off", and a numeric one +//! such as the port rejects it at startup, as `GITLAWB_PORT=` always has. +//! +//! Everything about the old prefix lives in this module, so dropping it later +//! is one deletion. + +use std::ffi::{OsStr, OsString}; +use std::sync::OnceLock; + +/// Prefix of every setting. +pub const PREFIX: &str = "TWIGPINE_"; + +/// Prefix the settings had before the rename. +pub const LEGACY_PREFIX: &str = "GITLAWB_"; + +/// Defaults the container image sets, under the old names (see the Dockerfile +/// for why). An old name carrying exactly its image default is not something +/// the operator typed, so it is adopted without being reported: otherwise +/// every container start would list six "old names in use", and overriding one +/// with a `TWIGPINE_` setting would be reported as a conflict. +pub const IMAGE_DEFAULTS: [(&str, &str); 6] = [ + ("REPOS_DIR", "/data/repos"), + ("KEY", "/data/keys/identity.pem"), + ("P2P_KEY", "/data/keys/p2p.key"), + ("HOST", "0.0.0.0"), + ("PORT", "7545"), + ("P2P_PORT", "7546"), +]; + +/// Set by the container image, and only by it, to say the old-name defaults +/// above are present. Without it a `GITLAWB_PORT=7545` is something a person +/// configured, and a disagreement with `TWIGPINE_PORT` is reported. +pub const IMAGE_MARKER: &str = "TWIGPINE_CONTAINER_IMAGE"; + +fn is_image_default(in_image: bool, rest: &str, value: &OsStr) -> bool { + in_image + && IMAGE_DEFAULTS + .iter() + .any(|(name, default)| *name == rest && value == OsStr::new(default)) +} + +/// A setting under either name, current name first, an empty value counting as +/// unset. For code that runs without [`adopt`]: tests that read a setting +/// directly rather than through a binary's `main`. +pub fn read(rest: &str) -> Option { + [PREFIX, LEGACY_PREFIX] + .iter() + .filter_map(|prefix| std::env::var_os(format!("{prefix}{rest}"))) + .find(|value| !value.is_empty()) +} + +/// What [`adopt`] found. Names only, never values: settings include keys. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Report { + /// Settings given only under the old name, as their new names, sorted. + pub legacy_only: Vec, + /// Settings given under both names with different values, as their new + /// names, sorted. The new name's value was used. + pub conflicts: Vec, +} + +impl Report { + /// True when no old name was in use. + pub fn is_empty(&self) -> bool { + self.legacy_only.is_empty() && self.conflicts.is_empty() + } +} + +static REPORT: OnceLock = OnceLock::new(); + +/// Work out which variables to set so both prefixes agree. Pure, so the rules +/// are testable without touching the process environment. +pub fn plan(vars: I) -> (Vec<(String, OsString)>, Report) +where + I: IntoIterator, +{ + // Only names that are valid UTF-8 can carry either prefix. Windows treats + // variable names as case-insensitive, so `gitlawb_node` and `Twigpine_Node` + // are these settings there; fold them to the spelling the code reads. + let vars: Vec<(String, OsString)> = vars + .into_iter() + .filter_map(|(k, v)| k.into_string().ok().map(|k| (k, v))) + .map(|(k, v)| { + if cfg!(windows) { + (k.to_ascii_uppercase(), v) + } else { + (k, v) + } + }) + .collect(); + let get = |name: &str| -> Option<&OsStr> { + vars.iter() + .find(|(k, _)| k == name) + .map(|(_, v)| v.as_os_str()) + }; + + let mut sets: Vec<(String, OsString)> = Vec::new(); + let mut report = Report::default(); + let in_image = get(IMAGE_MARKER).is_some_and(|v| !v.is_empty()); + + for (name, value) in &vars { + if let Some(rest) = suffix(name, LEGACY_PREFIX) { + let new_name = format!("{PREFIX}{rest}"); + match get(&new_name).filter(|v| !v.is_empty()) { + None => { + sets.push((new_name.clone(), value.clone())); + if !is_image_default(in_image, rest, value) { + report.legacy_only.push(new_name); + } + } + Some(new_value) if new_value != value.as_os_str() => { + sets.push((name.clone(), new_value.to_os_string())); + if !is_image_default(in_image, rest, value) { + report.conflicts.push(new_name); + } + } + Some(_) => {} + } + } else if name == IMAGE_MARKER { + // The marker is not a setting; it has no old name to fill in. + } else if let Some(rest) = suffix(name, PREFIX) { + if !value.is_empty() && get(&format!("{LEGACY_PREFIX}{rest}")).is_none() { + sets.push((format!("{LEGACY_PREFIX}{rest}"), value.clone())); + } + } + } + + report.legacy_only.sort(); + report.conflicts.sort(); + (sets, report) +} + +/// The part of `name` after `prefix`, when there is one. +fn suffix<'a>(name: &'a str, prefix: &str) -> Option<&'a str> { + name.strip_prefix(prefix).filter(|rest| !rest.is_empty()) +} + +/// Make both prefixes agree in this process's environment. Call it once, first +/// thing in `main`, before any thread exists and before anything reads a +/// setting: changing the environment while another thread reads it is a data +/// race on most platforms. +/// +/// Later calls change nothing and return the first call's report. +pub fn adopt() -> &'static Report { + REPORT.get_or_init(|| { + let (sets, report) = plan(std::env::vars_os()); + for (name, value) in sets { + std::env::set_var(name, value); + } + report + }) +} + +/// What [`adopt`] found, or an empty report when it has not run (a test that +/// calls library code directly). +pub fn report() -> Report { + REPORT.get().cloned().unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env(pairs: &[(&str, &str)]) -> Vec<(OsString, OsString)> { + pairs + .iter() + .map(|(k, v)| (OsString::from(k), OsString::from(v))) + .collect() + } + + fn sets(pairs: &[(&str, &str)]) -> Vec<(String, OsString)> { + pairs + .iter() + .map(|(k, v)| (k.to_string(), OsString::from(v))) + .collect() + } + + #[test] + fn old_name_alone_feeds_the_new_name() { + let (s, r) = plan(env(&[("GITLAWB_NODE", "https://n.example")])); + assert_eq!(s, sets(&[("TWIGPINE_NODE", "https://n.example")])); + assert_eq!(r.legacy_only, vec!["TWIGPINE_NODE"]); + assert!(r.conflicts.is_empty()); + } + + #[test] + fn new_name_alone_feeds_the_old_name_for_older_child_processes() { + let (s, r) = plan(env(&[("TWIGPINE_NODE", "https://n.example")])); + assert_eq!(s, sets(&[("GITLAWB_NODE", "https://n.example")])); + assert!(r.is_empty()); + } + + #[test] + fn new_name_wins_and_the_old_one_is_made_to_match() { + let (s, r) = plan(env(&[("GITLAWB_PORT", "1"), ("TWIGPINE_PORT", "2")])); + assert_eq!(s, sets(&[("GITLAWB_PORT", "2")])); + assert!(r.legacy_only.is_empty()); + assert_eq!(r.conflicts, vec!["TWIGPINE_PORT"]); + } + + #[test] + fn equal_values_need_nothing_and_report_nothing() { + let (s, r) = plan(env(&[("GITLAWB_PORT", "7"), ("TWIGPINE_PORT", "7")])); + assert!(s.is_empty()); + assert!(r.is_empty()); + } + + #[test] + fn an_empty_new_name_counts_as_unset() { + let (s, r) = plan(env(&[("GITLAWB_KEY", "/k.pem"), ("TWIGPINE_KEY", "")])); + assert_eq!(s, sets(&[("TWIGPINE_KEY", "/k.pem")])); + assert_eq!(r.legacy_only, vec!["TWIGPINE_KEY"]); + + // And an empty new name on its own is not copied to the old one. + let (s, r) = plan(env(&[("TWIGPINE_KEY", "")])); + assert!(s.is_empty()); + assert!(r.is_empty()); + } + + #[test] + fn an_empty_old_name_is_still_carried_over() { + // `GITLAWB_KEY=` meant "unset" to the reader; it means the same under + // the new name. + let (s, _) = plan(env(&[("GITLAWB_KEY", "")])); + assert_eq!(s, sets(&[("TWIGPINE_KEY", "")])); + } + + #[test] + fn other_variables_and_bare_prefixes_are_left_alone() { + let (s, r) = plan(env(&[ + ("PATH", "/bin"), + ("GITLAWB_", "x"), + ("TWIGPINE_", "y"), + ("MY_GITLAWB_NODE", "z"), + ])); + assert!(s.is_empty()); + assert!(r.is_empty()); + } + + #[test] + fn the_report_is_sorted_and_names_no_values() { + let (_, r) = plan(env(&[ + ("GITLAWB_PORT", "1"), + ("GITLAWB_KEY", "/secret/path"), + ("GITLAWB_HOST", "a"), + ("TWIGPINE_HOST", "b"), + ])); + assert_eq!(r.legacy_only, vec!["TWIGPINE_KEY", "TWIGPINE_PORT"]); + assert_eq!(r.conflicts, vec!["TWIGPINE_HOST"]); + assert!(!format!("{r:?}").contains("secret")); + } + + #[test] + fn image_defaults_under_the_old_names_are_adopted_quietly() { + // A stock container: the image's six defaults and nothing else. + let image: Vec<(String, String)> = IMAGE_DEFAULTS + .iter() + .map(|(k, v)| (format!("GITLAWB_{k}"), v.to_string())) + .collect(); + let mut pairs: Vec<(&str, &str)> = image + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .collect(); + + // Outside the image the same values are a person's configuration: + // reported, and a disagreement with the new name is a conflict. + let (_, r) = plan(env(&pairs)); + assert_eq!(r.legacy_only.len(), 6, "{r:?}"); + let mut host = pairs.clone(); + host.push(("TWIGPINE_PORT", "8000")); + let (_, r) = plan(env(&host)); + assert_eq!(r.conflicts, vec!["TWIGPINE_PORT"]); + + // Inside the image, marked as such, they are adopted quietly. + pairs.push((IMAGE_MARKER, "1")); + let (s, r) = plan(env(&pairs)); + assert_eq!(s.len(), 6, "every default still reaches the new name"); + assert!( + s.iter().all(|(name, _)| name.starts_with(PREFIX)), + "the marker itself is not mirrored: {s:?}" + ); + assert!(r.is_empty(), "{r:?}"); + + // The operator overrides one with the new name: used, not a conflict. + let mut with_new = pairs.clone(); + with_new.push(("TWIGPINE_PORT", "8000")); + let (s, r) = plan(env(&with_new)); + assert!(s.contains(&("GITLAWB_PORT".to_string(), OsString::from("8000")))); + assert!(r.is_empty(), "{r:?}"); + + // The operator overrides one with the OLD name: that is theirs, so it + // is reported like any other old name. + let mut with_old: Vec<(&str, &str)> = pairs + .iter() + .copied() + .filter(|(k, _)| *k != "GITLAWB_PORT") + .collect(); + with_old.push(("GITLAWB_PORT", "9000")); + let (_, r) = plan(env(&with_old)); + assert_eq!(r.legacy_only, vec!["TWIGPINE_PORT"]); + } + + #[cfg(windows)] + #[test] + fn windows_names_match_whatever_their_case() { + let (s, r) = plan(env(&[("gitlawb_node", "https://n.example")])); + assert_eq!(s, sets(&[("TWIGPINE_NODE", "https://n.example")])); + assert_eq!(r.legacy_only, vec!["TWIGPINE_NODE"]); + + let (s, r) = plan(env(&[("Twigpine_Node", "a"), ("GITLAWB_NODE", "b")])); + assert_eq!(s, sets(&[("GITLAWB_NODE", "a")])); + assert_eq!(r.conflicts, vec!["TWIGPINE_NODE"]); + } + + #[cfg(unix)] + #[test] + fn a_non_utf8_value_is_carried_over_untouched() { + use std::os::unix::ffi::OsStringExt; + let raw = OsString::from_vec(vec![b'/', 0xff, b'k']); + let (s, _) = plan(vec![(OsString::from("GITLAWB_KEY"), raw.clone())]); + assert_eq!(s, vec![("TWIGPINE_KEY".to_string(), raw)]); + } +} diff --git a/crates/twigpine-core/src/legacy_headers.rs b/crates/twigpine-core/src/legacy_headers.rs new file mode 100644 index 00000000..01b84b2b --- /dev/null +++ b/crates/twigpine-core/src/legacy_headers.rs @@ -0,0 +1,54 @@ +//! Header names from before the rename to Twigpine, next to their new names. +//! +//! The node sends every one of these under both names, so a client or a +//! webhook receiver written against the old names keeps working. Clients in +//! this repo read the new name first and fall back to the old one, so they +//! also work against a node that predates the rename. +//! +//! Everything about the old names lives here, so dropping them later is one +//! deletion. + +/// Response header naming why the node refused a request. Lowercase, as HTTP +/// libraries normalise header names. +pub const ERROR: &str = "x-twigpine-error"; + +/// [`ERROR`] before the rename. +pub const LEGACY_ERROR: &str = "x-gitlawb-error"; + +/// Response header on git smart-HTTP answers. +pub const NODE: &str = "x-twigpine-node"; + +/// [`NODE`] before the rename. +pub const LEGACY_NODE: &str = "x-gitlawb-node"; + +/// The names to try, in order, when reading the error header from a node that +/// may be older than the rename: current name first. +pub const ERROR_READ_ORDER: [&str; 2] = [ERROR, LEGACY_ERROR]; + +/// Response headers the node sends under both names: `(name, old name)`. +pub const RESPONSE_PAIRS: [(&str, &str); 2] = [(ERROR, LEGACY_ERROR), (NODE, LEGACY_NODE)]; + +/// Webhook delivery headers, sent under both names: `(name, old name)`. +pub const WEBHOOK_EVENT: (&str, &str) = ("X-Twigpine-Event", "X-Gitlawb-Event"); +pub const WEBHOOK_DELIVERY: (&str, &str) = ("X-Twigpine-Delivery", "X-Gitlawb-Delivery"); +pub const WEBHOOK_SIGNATURE: (&str, &str) = ("X-Twigpine-Signature-256", "X-Gitlawb-Signature-256"); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_pair_differs_only_by_the_prefix() { + let webhook = [WEBHOOK_EVENT, WEBHOOK_DELIVERY, WEBHOOK_SIGNATURE]; + for (new, old) in RESPONSE_PAIRS.iter().chain(webhook.iter()) { + let new = new.to_ascii_lowercase(); + let old = old.to_ascii_lowercase(); + assert_eq!( + new.strip_prefix("x-twigpine-"), + old.strip_prefix("x-gitlawb-"), + "{new} / {old}" + ); + assert!(new.starts_with("x-twigpine-"), "{new}"); + } + } +} diff --git a/crates/twigpine-core/src/lib.rs b/crates/twigpine-core/src/lib.rs index 6d242953..66a61aa3 100644 --- a/crates/twigpine-core/src/lib.rs +++ b/crates/twigpine-core/src/lib.rs @@ -6,6 +6,8 @@ pub mod error; pub mod http_sig; pub mod identity; pub mod identity_path; +pub mod legacy_env; +pub mod legacy_headers; pub mod node_denial; // `url` is the one dependency here that drags a tail (idna, then the icu // crates), and twigpine-core is allowlisted to stay embeddable. Every client that @@ -21,13 +23,13 @@ pub mod scan_token; pub mod transport_policy; pub mod ucan; -/// Node URL the git transport falls back to when `GITLAWB_NODE` is unset. +/// Node URL the git transport falls back to when `TWIGPINE_NODE` is unset. /// /// `twigpine` defaults to the public node instead, so the two disagree on an install /// that never sets the variable. pub const DEFAULT_LOCAL_NODE: &str = "http://127.0.0.1:7545"; -/// The node `git clone` and `git push` will contact, given the raw `GITLAWB_NODE` +/// The node `git clone` and `git push` will contact, given the raw `TWIGPINE_NODE` /// value (`None` when the variable is absent). /// /// `git-remote-twigpine` calls this to pick its base URL and `twigpine doctor` calls it diff --git a/crates/twigpine-core/src/node_denial.rs b/crates/twigpine-core/src/node_denial.rs index 4e91cf05..d0fae4aa 100644 --- a/crates/twigpine-core/src/node_denial.rs +++ b/crates/twigpine-core/src/node_denial.rs @@ -1,6 +1,6 @@ -//! The denial codes the node puts in `X-Gitlawb-Error`, in one place. +//! The denial codes the node puts in `X-Twigpine-Error`, in one place. //! -//! When the node refuses a write it answers with an `X-Gitlawb-Error` header +//! When the node refuses a write it answers with an `X-Twigpine-Error` header //! and a matching `error` field in the JSON body. The `twigpine` client keys off that //! header to turn a denial into a hard error instead of handing the caller a //! response that pretty-prints like a success. @@ -48,10 +48,10 @@ //! [`from_code`]: NodeDenial::from_code //! [`RateLimited`]: NodeDenial::RateLimited -/// A refusal the node names in `X-Gitlawb-Error`. +/// A refusal the node names in `X-Twigpine-Error`. /// /// The `as_str` value is the wire contract: it appears verbatim in the -/// `X-Gitlawb-Error` response header and in the body's `error` field, and +/// `X-Twigpine-Error` response header and in the body's `error` field, and /// scripts match on it. Never change one. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum NodeDenial { @@ -96,7 +96,7 @@ impl NodeDenial { Self::RateLimited, ]; - /// The wire code, as it appears in `X-Gitlawb-Error` and in the body. + /// The wire code, as it appears in `X-Twigpine-Error` and in the body. pub const fn as_str(self) -> &'static str { match self { Self::NonceRequired => "signature_nonce_required", diff --git a/crates/twigpine-core/src/transport_policy.rs b/crates/twigpine-core/src/transport_policy.rs index deba72ec..1d667885 100644 --- a/crates/twigpine-core/src/transport_policy.rs +++ b/crates/twigpine-core/src/transport_policy.rs @@ -52,7 +52,7 @@ pub fn is_insecure_remote(url: &str) -> bool { true } -/// Whether a non-empty `GITLAWB_ALLOW_INSECURE_HTTP` value opts in: only `1` or +/// Whether a non-empty `TWIGPINE_ALLOW_INSECURE_HTTP` value opts in: only `1` or /// `true` (case-insensitive, after trim). Presence alone is not consent. pub fn allow_insecure_http_value(raw: &str) -> bool { let t = raw.trim(); diff --git a/crates/twigpine-node/Cargo.toml b/crates/twigpine-node/Cargo.toml index 62a6d7ab..47084708 100644 --- a/crates/twigpine-node/Cargo.toml +++ b/crates/twigpine-node/Cargo.toml @@ -82,7 +82,7 @@ async-compression = { version = "0.4", features = ["tokio", "zstd"] } tar = "0.4" zstd = "0.13" # Prometheus metrics. Used to expose a /metrics endpoint for ops/observability -# on the opt-in GITLAWB_METRICS_ADDR listener. The crate is also the de-facto +# on the opt-in TWIGPINE_METRICS_ADDR listener. The crate is also the de-facto # exposition format encoder in the Rust ecosystem. prometheus = { version = "0.13", default-features = false } alloy = { version = "1", default-features = false, features = [ diff --git a/crates/twigpine-node/src/admin.rs b/crates/twigpine-node/src/admin.rs index 438ca042..dc8590a1 100644 --- a/crates/twigpine-node/src/admin.rs +++ b/crates/twigpine-node/src/admin.rs @@ -923,7 +923,7 @@ mod db_tests { } /// A Postgres pool of a fixed size with a short acquire timeout and no ambient - /// reaping, so a purge exercised at GITLAWB_DB_MAX_CONNECTIONS=1 fails fast + /// reaping, so a purge exercised at TWIGPINE_DB_MAX_CONNECTIONS=1 fails fast /// (rather than stalling the whole test) if the single connection is pinned. /// min/idle/lifetime pinned so a held connection is never reclaimed /// mid-assertion. @@ -1100,7 +1100,7 @@ mod db_tests { assert!(!path.exists(), "on-disk bare repo dir must be removed too"); } - // U3 (R3/KTD3): a purge at GITLAWB_DB_MAX_CONNECTIONS=1 (app pool size 1) must + // U3 (R3/KTD3): a purge at TWIGPINE_DB_MAX_CONNECTIONS=1 (app pool size 1) must // still delete. U2 split the pools: the advisory-lock guard pins a connection // from the dedicated lock_pool while delete_repo_by_id runs on the app pool, so // the single app connection is free for the delete's begin() even while the guard diff --git a/crates/twigpine-node/src/api/ipfs.rs b/crates/twigpine-node/src/api/ipfs.rs index aa50faf1..07b7d433 100644 --- a/crates/twigpine-node/src/api/ipfs.rs +++ b/crates/twigpine-node/src/api/ipfs.rs @@ -120,7 +120,7 @@ pub(crate) const LEGACY_SCAN_PAGE_ROWS: usize = 128; /// count (private and quarantined rows included) to within one ceiling. At the 2048 /// default that is tolled and coarse; it sharpens as the ceiling is lowered. /// -/// Tunable via `GITLAWB_IPFS_MAX_LEGACY_SCAN_ROWS` / `AppState`. +/// Tunable via `TWIGPINE_IPFS_MAX_LEGACY_SCAN_ROWS` / `AppState`. pub(crate) const MAX_LEGACY_SCAN_ROWS_PER_REQUEST: usize = 2048; /// Hard per-request ceiling on the BYTES of visibility rules the legacy scan's pager may @@ -282,7 +282,7 @@ impl LegacyScanPager { tracing::warn!( budget_secs, "/ipfs list_repos_page_for_scan exceeded the request budget \ - (GITLAWB_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" + (TWIGPINE_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" ); return Err(budget_shed()); } @@ -326,7 +326,7 @@ impl LegacyScanPager { tracing::warn!( budget_secs, "/ipfs list_visibility_rules_for_repos exceeded the request budget \ - (GITLAWB_IPFS_REQUEST_BUDGET_SECS); denying (fail closed) and freeing the walk permit" + (TWIGPINE_IPFS_REQUEST_BUDGET_SECS); denying (fail closed) and freeing the walk permit" ); return Err(budget_shed()); } @@ -638,7 +638,7 @@ pub async fn get_by_cid( tracing::warn!( resolve_budget_secs = state.config.ipfs_resolve_budget_secs, "/ipfs oids_for_cid exceeded the pre-walk resolve budget \ - (GITLAWB_IPFS_RESOLVE_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" + (TWIGPINE_IPFS_RESOLVE_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" ); return Err(AppError::Overloaded(format!( "ipfs resolve incomplete (resolve budget) for CID {cid_str}; retry shortly" @@ -647,7 +647,7 @@ pub async fn get_by_cid( tracing::warn!( budget_secs = state.config.ipfs_request_budget_secs, "/ipfs oids_for_cid exceeded the request budget \ - (GITLAWB_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" + (TWIGPINE_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" ); return Err(budget_shed()); } @@ -789,7 +789,7 @@ pub async fn get_by_cid( tracing::warn!( budget_secs = state.config.ipfs_request_budget_secs, "/ipfs pin_sources_for_oid exceeded the request budget \ - (GITLAWB_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" + (TWIGPINE_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" ); return Err(budget_shed()); } @@ -819,7 +819,7 @@ pub async fn get_by_cid( tracing::warn!( budget_secs = state.config.ipfs_request_budget_secs, "/ipfs get_repo_by_id exceeded the request budget \ - (GITLAWB_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" + (TWIGPINE_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" ); return Err(budget_shed()); } @@ -836,7 +836,7 @@ pub async fn get_by_cid( tracing::warn!( budget_secs = state.config.ipfs_request_budget_secs, "/ipfs is_repo_quarantined exceeded the request budget \ - (GITLAWB_IPFS_REQUEST_BUDGET_SECS); denying (fail closed) and freeing the walk permit" + (TWIGPINE_IPFS_REQUEST_BUDGET_SECS); denying (fail closed) and freeing the walk permit" ); return Err(budget_shed()); } @@ -855,7 +855,7 @@ pub async fn get_by_cid( tracing::warn!( budget_secs = state.config.ipfs_request_budget_secs, "/ipfs per-source list_visibility_rules_for_repos exceeded the request budget \ - (GITLAWB_IPFS_REQUEST_BUDGET_SECS); denying (fail closed) and freeing the walk permit" + (TWIGPINE_IPFS_REQUEST_BUDGET_SECS); denying (fail closed) and freeing the walk permit" ); return Err(budget_shed()); } @@ -976,7 +976,7 @@ pub async fn get_by_cid( tracing::warn!( budget_secs = state.config.ipfs_request_budget_secs, "/ipfs pin_sources_at_cap exceeded the request budget \ - (GITLAWB_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" + (TWIGPINE_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" ); return Err(budget_shed()); } @@ -995,7 +995,7 @@ pub async fn get_by_cid( tracing::warn!( budget_secs = state.config.ipfs_request_budget_secs, "/ipfs pin_sources_incomplete exceeded the request budget \ - (GITLAWB_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" + (TWIGPINE_IPFS_REQUEST_BUDGET_SECS); shedding a retryable 503 and freeing the walk permit" ); return Err(budget_shed()); } @@ -1598,7 +1598,7 @@ impl WalkState { stage, budget_secs, "/ipfs request budget exhausted before the stage \ - (GITLAWB_IPFS_REQUEST_BUDGET_SECS); stopping without a verdict" + (TWIGPINE_IPFS_REQUEST_BUDGET_SECS); stopping without a verdict" ); self.taint("budget"); return None; @@ -1684,7 +1684,7 @@ async fn gate_and_serve( ceiling = state.config.ipfs_max_repo_visits, repo = %repo.name, "/ipfs request hit the per-request repo-visit ceiling \ - (GITLAWB_IPFS_MAX_REPO_VISITS); skipping repo without a verdict" + (TWIGPINE_IPFS_MAX_REPO_VISITS); skipping repo without a verdict" ); return GateOutcome::CeilingStop("visit-ceiling"); } @@ -1834,7 +1834,7 @@ async fn gate_and_serve( // candidates never consume budget. // Both parents bound this loop, under different knobs: #173's // `ipfs_max_history_walks` (an AppState field, seeded from config) and - // #174's `GITLAWB_IPFS_MAX_REPOS_WALKED`. Honor the tighter of the two, so + // #174's `TWIGPINE_IPFS_MAX_REPOS_WALKED`. Honor the tighter of the two, so // neither knob silently stops working after the merge. // // The cap is charged PER PHASE (#173 round 13, F3): the provenance path and @@ -3908,7 +3908,7 @@ mod tests { /// `AppState::ipfs_work_budget` floors the per-IP work bucket at /// `ipfs_max_legacy_probes + pages`, but the SAME bucket is debited once per /// provenance visibility walk, before the fallback the markers arm has run at all. - /// So with `GITLAWB_IPFS_RATE_LIMIT` below the floor (the only configuration where + /// So with `TWIGPINE_IPFS_RATE_LIMIT` below the floor (the only configuration where /// the floor is what sizes the bucket), the provenance phase eats into the budget /// the floor exists to reserve for the search, and the "one complete legacy search /// per window" guarantee stops holding: the search 429s short of its configured @@ -8437,7 +8437,7 @@ mod tests { assert!( body.contains("budget"), "the truncation body must name the budget taint so the operator can \ - map the shed to GITLAWB_IPFS_REQUEST_BUDGET_SECS; got: {body}" + map the shed to TWIGPINE_IPFS_REQUEST_BUDGET_SECS; got: {body}" ); } @@ -9290,7 +9290,7 @@ mod tests { /// a deny VERDICT) and the second is cut by the cap (no verdict), so the fake git's /// `rev-list` runs exactly once and the request sheds a retryable 503 + Retry-After /// — never the old false 404 (the blob genuinely sits in the second repo). - /// This drives the GITLAWB_IPFS_MAX_REPOS_WALKED knob specifically. The merge left + /// This drives the TWIGPINE_IPFS_MAX_REPOS_WALKED knob specifically. The merge left /// two walk caps in play, this one and the branch's own history-walk ceiling, and /// the gate takes the tighter of the two; setting this knob to 1 is what makes it /// the binding one here. A sibling case covers the ceiling. @@ -9576,7 +9576,7 @@ mod tests { assert!( body.contains("budget"), "the shed must name the budget taint so it maps to \ - GITLAWB_IPFS_REQUEST_BUDGET_SECS; got: {body}" + TWIGPINE_IPFS_REQUEST_BUDGET_SECS; got: {body}" ); // The scarce walk permit was RAII-dropped on the early return, not pinned for // the stall: the slot is free again the instant the request returns. @@ -9606,7 +9606,7 @@ mod tests { /// region, and pre-fix it was a bare await with no deadline. A query blocked in /// Postgres there pinned both walk permits for the whole stall, past the request /// budget, so later /ipfs requests took capacity 503s long after - /// GITLAWB_IPFS_REQUEST_BUDGET_SECS elapsed, reachable by any unauthenticated + /// TWIGPINE_IPFS_REQUEST_BUDGET_SECS elapsed, reachable by any unauthenticated /// caller. Here `pinned_cids` (the only table `oids_for_cid` reads) is held /// ACCESS EXCLUSIVE so the query blocks at lock acquisition. /// @@ -9669,7 +9669,7 @@ mod tests { assert!( body.contains("budget"), "the shed must name the budget taint so it maps to \ - GITLAWB_IPFS_REQUEST_BUDGET_SECS; got: {body}" + TWIGPINE_IPFS_REQUEST_BUDGET_SECS; got: {body}" ); assert_eq!( sem.available_permits(), @@ -9770,7 +9770,7 @@ mod tests { assert!( body.contains("resolve budget"), "the shed must name the RESOLVE budget so it maps to \ - GITLAWB_IPFS_RESOLVE_BUDGET_SECS; got: {body}" + TWIGPINE_IPFS_RESOLVE_BUDGET_SECS; got: {body}" ); assert!( !body.contains("request budget"), @@ -9959,7 +9959,7 @@ mod tests { assert!( body.contains("budget"), "the shed must name the budget taint so it maps to \ - GITLAWB_IPFS_REQUEST_BUDGET_SECS; got: {body}" + TWIGPINE_IPFS_REQUEST_BUDGET_SECS; got: {body}" ); assert_eq!( sem.available_permits(), @@ -10166,7 +10166,7 @@ mod tests { assert!( body.contains("budget"), "{label}: the shed must name the budget taint so it maps to \ - GITLAWB_IPFS_REQUEST_BUDGET_SECS; got: {body}" + TWIGPINE_IPFS_REQUEST_BUDGET_SECS; got: {body}" ); // The scarce walk permit was RAII-dropped on the early return, not pinned for // the stall: the slot is free again the instant the request returns. diff --git a/crates/twigpine-node/src/api/peers.rs b/crates/twigpine-node/src/api/peers.rs index c145efed..f89a755a 100644 --- a/crates/twigpine-node/src/api/peers.rs +++ b/crates/twigpine-node/src/api/peers.rs @@ -311,7 +311,7 @@ pub async fn announce( } else { tracing::warn!( did = %announced_did, - "accepted unsigned peer announce; set GITLAWB_REQUIRE_SIGNED_PEER_WRITES=true after all peers upgrade" + "accepted unsigned peer announce; set TWIGPINE_REQUIRE_SIGNED_PEER_WRITES=true after all peers upgrade" ); None }; @@ -504,7 +504,7 @@ pub async fn notify_sync( } else { tracing::warn!( did = %req.node_did, - "accepted unsigned sync notify; set GITLAWB_REQUIRE_SIGNED_PEER_WRITES=true after all peers upgrade" + "accepted unsigned sync notify; set TWIGPINE_REQUIRE_SIGNED_PEER_WRITES=true after all peers upgrade" ); } @@ -603,14 +603,22 @@ pub async fn ping_peer( }))) } -/// The `x-gitlawb-error` code a peer put on a rejection, if it sent one. +/// The `x-twigpine-error` code a peer put on a rejection, if it sent one. /// /// Kept verbatim: it is what separates a ledger rejection from a replay /// rejection on the same-ish status, and it is what an operator greps for. A /// peer behind a proxy that strips unknown `X-` headers returns `None`, which /// is why every caller logs the status too rather than relying on this alone. +/// +/// A peer that predates the rename sends the code under the header's old name +/// only, so that is read too. Missing it would turn that peer's "try again" +/// answers into permanent failures. pub(crate) fn peer_error_code(headers: &reqwest::header::HeaderMap) -> Option<&str> { - headers.get("x-gitlawb-error")?.to_str().ok() + twigpine_core::legacy_headers::ERROR_READ_ORDER + .iter() + .find_map(|name| headers.get(*name))? + .to_str() + .ok() } #[cfg(test)] @@ -620,9 +628,20 @@ mod tests { #[test] fn peer_error_code_reads_the_header_when_present() { + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert("x-twigpine-error", "signature_ledger_full".parse().unwrap()); + assert_eq!(peer_error_code(&headers), Some("signature_ledger_full")); + } + + #[test] + fn peer_error_code_reads_the_old_header_name_from_an_older_peer() { let mut headers = reqwest::header::HeaderMap::new(); headers.insert("x-gitlawb-error", "signature_ledger_full".parse().unwrap()); assert_eq!(peer_error_code(&headers), Some("signature_ledger_full")); + + // A peer that sends both: the current name is the one read. + headers.insert("x-twigpine-error", "rate_limited".parse().unwrap()); + assert_eq!(peer_error_code(&headers), Some("rate_limited")); } #[test] @@ -1636,7 +1655,7 @@ mod tests { // hit. Asserted end-to-end here, through the real router. assert_eq!( resp.headers() - .get("x-gitlawb-error") + .get("x-twigpine-error") .and_then(|v| v.to_str().ok()), Some("rate_limited"), ); diff --git a/crates/twigpine-node/src/api/repos.rs b/crates/twigpine-node/src/api/repos.rs index c78c2be3..a13cbb1e 100644 --- a/crates/twigpine-node/src/api/repos.rs +++ b/crates/twigpine-node/src/api/repos.rs @@ -1945,7 +1945,7 @@ pub async fn git_upload_pack( // — the safe direction, same tradeoff as `fail_closed_full_scan_objects` and // `build_filtered_pack`. The cost is honest: a genuinely slow walk on a large // repo 504s this clone instead of silently holding the pool for ~2x, so size - // `GITLAWB_GIT_SERVICE_TIMEOUT_SECS` so both phases normally fit. + // `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` so both phases normally fit. let deadline = std::time::Instant::now() + git_timeout; let (withheld, _permit, _caller_permit) = { let path = disk_path.clone(); @@ -2156,7 +2156,7 @@ fn owner_push_rejection( _ => Some(AppError::Forbidden( "push rejected — you must be the repo owner, or hold a valid \ owner-issued git/push delegation for this repository \ - (GITLAWB_ENFORCE_OWNER_PUSH is enabled)" + (TWIGPINE_ENFORCE_OWNER_PUSH is enabled)" .into(), )), } @@ -2254,7 +2254,7 @@ enum NotifyDisposition { /// Classify a peer's `/sync/notify` response. /// -/// The gate is the peer's `X-Gitlawb-Error` code, not the status. Only two +/// The gate is the peer's `X-Twigpine-Error` code, not the status. Only two /// codes mean "the write did not happen and another attempt can clear it": /// `signature_ledger_full` (the per-identity spent-signature cap, which drains /// as entries expire) and `signature_ledger_unavailable`. Everything else is @@ -2608,7 +2608,7 @@ pub async fn git_receive_pack( ref_count = ref_updates.len(), "parsed ref updates from pack" ); - // ── Owner-only push enforcement (on by default; GITLAWB_ENFORCE_OWNER_PUSH) ── + // ── Owner-only push enforcement (on by default; TWIGPINE_ENFORCE_OWNER_PUSH) ── // Runs before branch protection on purpose: when enabled, a non-owner is // rejected here regardless of whether the target branch is protected, so a // single rejection never yields two different error bodies. The identity is @@ -2857,12 +2857,12 @@ pub async fn git_receive_pack( // it. `body: Bytes` means axum has already buffered the whole pack before this handler // runs, and the park runs to steal_after (1260s at defaults), so an unbounded waiter // set would let same-repo pushes stack buffered bodies. `acquire` therefore counts its - // LIVE WAITERS against GITLAWB_REPO_LEASE_MAX_WAITERS and returns None past the cap, + // LIVE WAITERS against TWIGPINE_REPO_LEASE_MAX_WAITERS and returns None past the cap, // which sheds here as a 503 + Retry-After like the other admission paths. The cap is // per repo and counts only handlers actually parked, so it denies same-repo // concurrency on the contended repo alone: a push to any other repo, from any source, // is untouched. Taking a per-source or global admission permit above the park instead - // is what the F1 review rejected, since GITLAWB_TRUSTED_PROXY defaults to unset and + // is what the F1 review rejected, since TWIGPINE_TRUSTED_PROXY defaults to unset and // every pusher behind a proxy/NAT then resolves to ONE key, turning one contended repo // into a node-wide denial. // The stable disk identity, never record.id: the row id rotates on a @@ -2905,7 +2905,7 @@ pub async fn git_receive_pack( // pushes, hold every global slot on zero-byte lease-waiters, and shed 503 on every push // to every OTHER repo node-wide. The per-source sub-cap belongs below the park for the // same reason: its key is the resolved source IP, which collapses to one key for every - // pusher when GITLAWB_TRUSTED_PROXY is unset (the default), so above the park it sheds + // pusher when TWIGPINE_TRUSTED_PROXY is unset (the default), so above the park it sheds // cross-tenant too. Still before acquire_write, so the git op stays admission-gated // (INV-10) and a saturated pool sheds 503 before spawning git. // @@ -8838,14 +8838,14 @@ mod tests { let mock_a = server_a .mock("POST", SYNC_NOTIFY_PATH) .with_status(429) - .with_header("x-gitlawb-error", "signature_ledger_full") + .with_header("x-twigpine-error", "signature_ledger_full") .expect(6) .create_async() .await; let mock_b = server_b .mock("POST", SYNC_NOTIFY_PATH) .with_status(429) - .with_header("x-gitlawb-error", "signature_ledger_full") + .with_header("x-twigpine-error", "signature_ledger_full") .expect(1) .create_async() .await; @@ -8904,7 +8904,7 @@ mod tests { let rejected = server .mock("POST", SYNC_NOTIFY_PATH) .with_status(429) - .with_header("x-gitlawb-error", "signature_ledger_full") + .with_header("x-twigpine-error", "signature_ledger_full") .expect(2) .create_async() .await; @@ -8952,7 +8952,7 @@ mod tests { let mock = server .mock("POST", SYNC_NOTIFY_PATH) .with_status(429) - .with_header("x-gitlawb-error", "signature_ledger_full") + .with_header("x-twigpine-error", "signature_ledger_full") .expect(FAST_BACKOFF.len() + 1) .create_async() .await; @@ -9007,7 +9007,7 @@ mod tests { let mock = server .mock("POST", SYNC_NOTIFY_PATH) .with_status(429) - .with_header("x-gitlawb-error", "signature_ledger_full") + .with_header("x-twigpine-error", "signature_ledger_full") .expect(budgeted * (FAST_BACKOFF.len() + 1) + 1) .create_async() .await; @@ -9039,8 +9039,8 @@ mod tests { #[tokio::test] async fn notify_peer_does_not_retry_a_429_with_an_unrelated_code() { for headers in [ - vec![("x-gitlawb-error", "rate_limited")], - vec![("x-gitlawb-error", "some_code_from_a_newer_node")], + vec![("x-twigpine-error", "rate_limited")], + vec![("x-twigpine-error", "some_code_from_a_newer_node")], vec![], ] { let mut server = mockito::Server::new_async().await; @@ -9119,7 +9119,7 @@ mod tests { let mock = server .mock("POST", SYNC_NOTIFY_PATH) .with_status(409) - .with_header("x-gitlawb-error", "signature_replayed") + .with_header("x-twigpine-error", "signature_replayed") .expect(1) .create_async() .await; @@ -10081,7 +10081,7 @@ mod tests { /// The parser REFUSES at the cap instead of scanning and allocating the whole /// request and being refused afterwards. Git routes raise the body - /// limit to GITLAWB_MAX_PACK_BYTES — 2 GB by default — so the count check + /// limit to TWIGPINE_MAX_PACK_BYTES — 2 GB by default — so the count check /// lives inside `parse_ref_updates`'s command loop, which returns the 400 /// the first command past the cap rather than at the end of whatever the /// client sent. @@ -15723,7 +15723,7 @@ mod tests { let _ = tokio::time::timeout(std::time::Duration::from_secs(60), handle_b).await; } - /// #174 U1 scenario 3, THE CROSS-TENANT GUARD. `GITLAWB_TRUSTED_PROXY` is unset by + /// #174 U1 scenario 3, THE CROSS-TENANT GUARD. `TWIGPINE_TRUSTED_PROXY` is unset by /// default (`TrustedProxy::None`), so behind an edge proxy, a NAT, or a CI pool every /// pusher resolves to the SAME source key. A push parked on one repo's lease must not /// shed a DIFFERENT pusher's push to a DIFFERENT repo. This is the shape that made @@ -18391,7 +18391,7 @@ exit 0 ); } - // GITLAWB_WRITE_RATE_LIMIT=0 disables the brake end-to-end: no write is 429'd + // TWIGPINE_WRITE_RATE_LIMIT=0 disables the brake end-to-end: no write is 429'd // however many arrive from one IP. #[sqlx::test] async fn write_rate_limit_zero_disables_the_brake(pool: sqlx::PgPool) { @@ -18996,7 +18996,7 @@ exit 0 // create_repo must NOT take its serialization lock from the APP pool. Doing so // pins an app-pool connection in the lock guard while the create's own work // (get_repo / proof.consume / db.create_repo, all on state.db = the app pool) - // still needs an app connection. At GITLAWB_DB_MAX_CONNECTIONS=1 (a supported + // still needs an app connection. At TWIGPINE_DB_MAX_CONNECTIONS=1 (a supported // config) the guard holds the only app connection and get_repo self-deadlocks // (PoolTimedOut -> 500). Locking on the separate write lock_pool instead keeps // the lock and the work on different pools, so a size-1 app pool never wedges. @@ -19018,7 +19018,7 @@ exit 0 let mut state = crate::test_support::test_state(migrate_pool).await; // Now point state.db at an APP pool of MAX size 1 on the SAME database, the - // minimal supported config (GITLAWB_DB_MAX_CONNECTIONS=1). The schema is + // minimal supported config (TWIGPINE_DB_MAX_CONNECTIONS=1). The schema is // already applied, so this pool only serves create's work (get_repo -> insert). // A short acquire timeout makes the RED case (the lock guard pinning this one // connection while get_repo waits for another) fail fast instead of hanging. diff --git a/crates/twigpine-node/src/arweave.rs b/crates/twigpine-node/src/arweave.rs index 332226e4..0fe3e56c 100644 --- a/crates/twigpine-node/src/arweave.rs +++ b/crates/twigpine-node/src/arweave.rs @@ -8,7 +8,7 @@ //! Irys allows free uploads for data < 100 KiB on both devnet and mainnet //! (via Turbo). No wallet is required for payloads under the free threshold. //! -//! Set `GITLAWB_IRYS_URL` to override the default endpoint: +//! Set `TWIGPINE_IRYS_URL` to override the default endpoint: //! - devnet (free, no cost): https://devnet.irys.xyz //! - mainnet: https://node2.irys.xyz //! diff --git a/crates/twigpine-node/src/auth/mod.rs b/crates/twigpine-node/src/auth/mod.rs index c87d1736..2f53a752 100644 --- a/crates/twigpine-node/src/auth/mod.rs +++ b/crates/twigpine-node/src/auth/mod.rs @@ -79,7 +79,7 @@ pub struct SignatureMaterial { /// route that never stores the body has no use for a second handle to it. /// The unlike-sized field is this one: the three above are header-derived /// and bounded by the server's header limit, while a receive-pack POST - /// carries up to GITLAWB_MAX_PACK_BYTES (2 GB by default). `Bytes`, not + /// carries up to TWIGPINE_MAX_PACK_BYTES (2 GB by default). `Bytes`, not /// `Vec`, so the handle the marked routes do take is a refcount bump /// over the buffer the middleware already holds rather than a copy. pub body: Option, @@ -180,7 +180,7 @@ use twigpine_core::identity::verify; /// /// This is middleware state rather than a constant because a single number cannot /// serve both a 2 GB git push and a 2 MB profile update: the git write group -/// passes `GITLAWB_MAX_PACK_BYTES`, every other signed group passes +/// passes `TWIGPINE_MAX_PACK_BYTES`, every other signed group passes /// [`crate::server::SIGNED_BODY_LIMIT`]. Making it a required piece of state means /// a new signed route group cannot be wired up without choosing a limit. #[derive(Clone, Copy, Debug)] @@ -733,7 +733,7 @@ fn ledger_rejection(denial: NodeDenial, message: &str) -> Response { // which `denial_statuses_are_valid_http_codes` proves over every // variant. StatusCode::from_u16(denial.status()).expect("NodeDenial status is a valid HTTP code"), - [("X-Gitlawb-Error", code)], + [("X-Twigpine-Error", code)], Json(json!({ "error": code, "message": message })), ) .into_response() @@ -997,7 +997,7 @@ fn human_detected(message: &str) -> impl IntoResponse { "WWW-Authenticate", "Signature realm=\"gitlawb-alpha\", alg=\"ed25519\"", ), - ("X-Gitlawb-Error", "human_detected"), + ("X-Twigpine-Error", "human_detected"), ], Json(json!({ "error": "not_an_agent", @@ -1076,7 +1076,7 @@ mod tests { } /// The exact bytes `consume_signature` puts on the wire for each denial: - /// the `X-Gitlawb-Error` header, the body's `error` field, and the status + /// the `X-Twigpine-Error` header, the body's `error` field, and the status /// must all agree, because `twigpine` keys on the header and `twigpine init` keys on the /// body field. #[tokio::test] @@ -1085,7 +1085,7 @@ mod tests { let resp = ledger_rejection(denial, "why it was refused"); assert_eq!(resp.status().as_u16(), denial.status(), "{denial}"); assert_eq!( - resp.headers().get("X-Gitlawb-Error").unwrap(), + resp.headers().get("X-Twigpine-Error").unwrap(), denial.as_str(), "{denial}", ); diff --git a/crates/twigpine-node/src/bootstrap.rs b/crates/twigpine-node/src/bootstrap.rs index d9ef732c..92094093 100644 --- a/crates/twigpine-node/src/bootstrap.rs +++ b/crates/twigpine-node/src/bootstrap.rs @@ -4,7 +4,7 @@ //! merges its contents into the runtime config so a fresh `docker compose up` //! joins the network without any manual peer configuration. //! -//! Operators can opt out by setting `GITLAWB_BOOTSTRAP_DISABLE_SEEDS=true` in +//! Operators can opt out by setting `TWIGPINE_BOOTSTRAP_DISABLE_SEEDS=true` in //! their environment — useful for isolated dev networks or testing. //! //! Add a node to the canonical list via PR to `bootstrap-peers.json`. @@ -47,9 +47,9 @@ struct MergeCounts { p2p: usize, } -/// Returns true when `GITLAWB_BOOTSTRAP_DISABLE_SEEDS` is set to a truthy value. +/// Returns true when `TWIGPINE_BOOTSTRAP_DISABLE_SEEDS` is set to a truthy value. fn seeds_disabled() -> bool { - std::env::var("GITLAWB_BOOTSTRAP_DISABLE_SEEDS") + std::env::var("TWIGPINE_BOOTSTRAP_DISABLE_SEEDS") .ok() .filter(|v| !v.is_empty() && v != "0" && !v.eq_ignore_ascii_case("false")) .is_some() @@ -112,10 +112,10 @@ fn merge_into_vecs( /// - Appends any `http_url` to `config.bootstrap_peers` (used by gossip_task) /// - Appends any valid `p2p_multiaddr` to `config.p2p_bootstrap` (used by libp2p) /// - Dedupes against entries already present (env / CLI takes precedence) -/// - No-op when `GITLAWB_BOOTSTRAP_DISABLE_SEEDS` is set to a truthy value +/// - No-op when `TWIGPINE_BOOTSTRAP_DISABLE_SEEDS` is set to a truthy value pub fn merge_seeds(config: &mut Config) { if seeds_disabled() { - info!("bootstrap seed list disabled via GITLAWB_BOOTSTRAP_DISABLE_SEEDS"); + info!("bootstrap seed list disabled via TWIGPINE_BOOTSTRAP_DISABLE_SEEDS"); return; } diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index 112bfc6a..728ec717 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -50,11 +50,22 @@ pub struct Config { #[command(subcommand)] pub command: Option, + /// True when `--key-path` / `TWIGPINE_KEY` was given, even with the same + /// text as the default. A path someone wrote is taken as written; only an + /// omitted one goes through the default-folder rule. Set by + /// [`Config::parse_with_sources`]. + #[arg(skip)] + pub key_path_given: bool, + + /// The same, for `--p2p-key-path` / `TWIGPINE_P2P_KEY`. + #[arg(skip)] + pub p2p_key_path_given: bool, + /// Directory where bare git repositories are stored. `global` so it can /// follow a subcommand (e.g. `twigpine-node purge-spam --repos-dir …`). #[arg( long, - env = "GITLAWB_REPOS_DIR", + env = "TWIGPINE_REPOS_DIR", default_value = "./data/repos", global = true )] @@ -71,36 +82,36 @@ pub struct Config { pub database_url: String, /// Host to bind to - #[arg(long, env = "GITLAWB_HOST", default_value = "127.0.0.1")] + #[arg(long, env = "TWIGPINE_HOST", default_value = "127.0.0.1")] pub host: String, /// Port to listen on - #[arg(long, env = "GITLAWB_PORT", default_value_t = 7545)] + #[arg(long, env = "TWIGPINE_PORT", default_value_t = 7545)] pub port: u16, /// Path to the node's Ed25519 identity PEM key - #[arg(long, env = "GITLAWB_KEY", default_value = "~/.gitlawb/identity.pem")] + #[arg(long, env = "TWIGPINE_KEY", default_value = DEFAULT_KEY_PATH)] pub key_path: String, /// Reserved and currently inert: read access is enforced per repository /// through `is_public` and path-scoped visibility rules, not this flag. /// Setting it to false changes nothing; make a repo private through its /// own visibility instead. - #[arg(long, env = "GITLAWB_PUBLIC_READ", default_value_t = true)] + #[arg(long, env = "TWIGPINE_PUBLIC_READ", default_value_t = true)] pub public_read: bool, /// Public URL of this node (for peer announcements) - #[arg(long, env = "GITLAWB_PUBLIC_URL")] + #[arg(long, env = "TWIGPINE_PUBLIC_URL")] pub public_url: Option, /// Base URL for the web view of repos on this node (e.g. https://gitlawb.com). /// When set, `GET /` advertises it as `web_url` so the CLI can print a /// working `View:` link. Omit for nodes that have no web front-end. - #[arg(long, env = "GITLAWB_WEB_URL")] + #[arg(long, env = "TWIGPINE_WEB_URL")] pub web_url: Option, /// Comma-separated list of bootstrap peer URLs to announce to on startup - #[arg(long, env = "GITLAWB_BOOTSTRAP_PEERS", value_delimiter = ',')] + #[arg(long, env = "TWIGPINE_BOOTSTRAP_PEERS", value_delimiter = ',')] pub bootstrap_peers: Vec, /// Require a peer write to prove its DID on any transport: RFC 9421 @@ -109,7 +120,7 @@ pub struct Config { /// Keep false during rolling upgrades so existing live nodes can still gossip. #[arg( long, - env = "GITLAWB_REQUIRE_SIGNED_PEER_WRITES", + env = "TWIGPINE_REQUIRE_SIGNED_PEER_WRITES", default_value_t = false )] pub require_signed_peer_writes: bool, @@ -119,7 +130,11 @@ pub struct Config { /// keying the replay ledger on the signing-string hash without it, which /// rejects a byte-identical mutation repeated inside the same second. /// Enforced on write routes only, so signed reads are never affected. - #[arg(long, env = "GITLAWB_REQUIRE_SIGNATURE_NONCE", default_value_t = false)] + #[arg( + long, + env = "TWIGPINE_REQUIRE_SIGNATURE_NONCE", + default_value_t = false + )] pub require_signature_nonce: bool, /// Require the authenticated pusher to be the repo owner on `git-receive-pack`. @@ -128,7 +143,7 @@ pub struct Config { /// caller may push to every repository, private ones included. On by default. /// /// Turn it off only for a rolling upgrade whose pushers are not yet the repo - /// owner. Both `GITLAWB_ENFORCE_OWNER_PUSH=false` and `--enforce-owner-push + /// owner. Both `TWIGPINE_ENFORCE_OWNER_PUSH=false` and `--enforce-owner-push /// false` disable it, and the bare `--enforce-owner-push` form still means /// `true`. /// @@ -138,7 +153,7 @@ pub struct Config { /// hatch this buys, not the environment one. #[arg( long, - env = "GITLAWB_ENFORCE_OWNER_PUSH", + env = "TWIGPINE_ENFORCE_OWNER_PUSH", action = clap::ArgAction::Set, num_args = 0..=1, default_value_t = true, @@ -147,23 +162,23 @@ pub struct Config { pub enforce_owner_push: bool, /// URL of local IPFS/Kubo node HTTP API (e.g. http://127.0.0.1:5001) - #[arg(long, env = "GITLAWB_IPFS_API", default_value = "")] + #[arg(long, env = "TWIGPINE_IPFS_API", default_value = "")] pub ipfs_api: String, /// Pinata JWT for IPFS warm storage. Leave empty to disable (default). - #[arg(long, env = "GITLAWB_PINATA_JWT", default_value = "")] + #[arg(long, env = "TWIGPINE_PINATA_JWT", default_value = "")] pub pinata_jwt: String, /// Pinata v3 upload URL #[arg( long, - env = "GITLAWB_PINATA_UPLOAD_URL", + env = "TWIGPINE_PINATA_UPLOAD_URL", default_value = "https://uploads.pinata.cloud/v3/files" )] pub pinata_upload_url: String, /// libp2p QUIC/UDP port (0 = disabled) - #[arg(long, env = "GITLAWB_P2P_PORT", default_value_t = 7546)] + #[arg(long, env = "TWIGPINE_P2P_PORT", default_value_t = 7546)] pub p2p_port: u16, /// Path to the persistent libp2p identity key. A value that cannot name a @@ -175,23 +190,27 @@ pub struct Config { /// and write permissions) before using it. A 0755 key directory is tightened /// on start; rotate the key only if the directory was group/world-writable /// or the key was group/world-readable. - #[arg(long, env = "GITLAWB_P2P_KEY", default_value = "~/.gitlawb/p2p.key")] + #[arg(long, env = "TWIGPINE_P2P_KEY", default_value = DEFAULT_P2P_KEY_PATH)] pub p2p_key_path: String, /// libp2p bootstrap multiaddrs (comma-separated) /// Example: /ip4/1.2.3.4/udp/7546/quic-v1/p2p/12D3KooW... - #[arg(long, env = "GITLAWB_P2P_BOOTSTRAP", value_delimiter = ',')] + #[arg(long, env = "TWIGPINE_P2P_BOOTSTRAP", value_delimiter = ',')] pub p2p_bootstrap: Vec, /// Automatically mirror repos from peers when ref-update events arrive via Gossipsub. - #[arg(long, env = "GITLAWB_AUTO_SYNC", default_value_t = false)] + #[arg(long, env = "TWIGPINE_AUTO_SYNC", default_value_t = false)] pub auto_sync: bool, /// Periodically fetch configured INBOUND repositories from their external /// HTTPS upstream. Disabled by default: enabling this also requires - /// `GITLAWB_ENFORCE_OWNER_PUSH=true`, so an upstream-authoritative mirror + /// `TWIGPINE_ENFORCE_OWNER_PUSH=true`, so an upstream-authoritative mirror /// cannot accept writes from arbitrary signed identities between fetches. - #[arg(long, env = "GITLAWB_UPSTREAM_MIRROR_ENABLED", default_value_t = false)] + #[arg( + long, + env = "TWIGPINE_UPSTREAM_MIRROR_ENABLED", + default_value_t = false + )] pub upstream_mirror_enabled: bool, /// Pause between complete upstream-mirror scans. A scan is sequential and @@ -199,7 +218,7 @@ pub struct Config { /// slow forge cannot create overlapping worker cycles. #[arg( long, - env = "GITLAWB_UPSTREAM_MIRROR_INTERVAL_SECS", + env = "TWIGPINE_UPSTREAM_MIRROR_INTERVAL_SECS", default_value_t = 300, value_parser = clap::value_parser!(u64).range(5..=86_400) )] @@ -211,7 +230,7 @@ pub struct Config { /// do not consume this budget. #[arg( long, - env = "GITLAWB_UPSTREAM_MIRROR_FETCH_TIMEOUT_SECS", + env = "TWIGPINE_UPSTREAM_MIRROR_FETCH_TIMEOUT_SECS", default_value_t = 600, value_parser = clap::value_parser!(u64).range(1..=GIT_SERVICE_TIMEOUT_SECS_MAX) )] @@ -222,7 +241,7 @@ pub struct Config { /// permanently starving repositories beyond the first page. #[arg( long, - env = "GITLAWB_UPSTREAM_MIRROR_PAGE_SIZE", + env = "TWIGPINE_UPSTREAM_MIRROR_PAGE_SIZE", default_value_t = 100, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_000) )] @@ -232,7 +251,7 @@ pub struct Config { /// the sweep even when a pin backend (IPFS/Pinata) is configured. #[arg( long, - env = "GITLAWB_RECONCILIATION_SWEEP", + env = "TWIGPINE_RECONCILIATION_SWEEP", default_value_t = true, action = clap::ArgAction::Set )] @@ -240,21 +259,21 @@ pub struct Config { /// Irys URL for Arweave permanent anchoring. /// Leave empty to disable. Use https://devnet.irys.xyz for free devnet. - #[arg(long, env = "GITLAWB_IRYS_URL", default_value = "")] + #[arg(long, env = "TWIGPINE_IRYS_URL", default_value = "")] pub irys_url: String, /// Base L2 DID registry contract address (0x...) - #[arg(long, env = "GITLAWB_CONTRACT_DID_REGISTRY", default_value = "")] + #[arg(long, env = "TWIGPINE_CONTRACT_DID_REGISTRY", default_value = "")] pub contract_did_registry: String, /// Base L2 name registry contract address (0x...) - #[arg(long, env = "GITLAWB_CONTRACT_NAME_REGISTRY", default_value = "")] + #[arg(long, env = "TWIGPINE_CONTRACT_NAME_REGISTRY", default_value = "")] pub contract_name_registry: String, /// Base L2 RPC URL #[arg( long, - env = "GITLAWB_CHAIN_RPC_URL", + env = "TWIGPINE_CHAIN_RPC_URL", default_value = "https://sepolia.base.org" )] pub chain_rpc_url: String, @@ -262,40 +281,45 @@ pub struct Config { /// Base L2 node staking contract address (GitlawbNodeStaking). When set /// along with `operator_private_key`, the node verifies its stake on /// startup and posts a heartbeat on a fixed cadence. - #[arg(long, env = "GITLAWB_CONTRACT_NODE_STAKING", default_value = "")] + #[arg(long, env = "TWIGPINE_CONTRACT_NODE_STAKING", default_value = "")] pub contract_node_staking: String, /// Hex-encoded (0x-prefixed) private key for the operator wallet that /// posts heartbeats. Not required unless on-chain PoS is enabled. - #[arg(long, env = "GITLAWB_OPERATOR_PRIVATE_KEY", default_value = "")] + #[arg(long, env = "TWIGPINE_OPERATOR_PRIVATE_KEY", default_value = "")] pub operator_private_key: String, /// If true, the node refuses to start when it is not registered on-chain /// or is currently inactive (missed heartbeats). Use once your network is /// live and every operator is expected to have stake. - #[arg(long, env = "GITLAWB_OPERATOR_STRICT_MODE", default_value_t = false)] + #[arg(long, env = "TWIGPINE_OPERATOR_STRICT_MODE", default_value_t = false)] pub operator_strict_mode: bool, /// How often to post the operator heartbeat, in hours. Must be less than /// the contract's HEARTBEAT_WINDOW (24h) with headroom. Default: 20h. - #[arg(long, env = "GITLAWB_HEARTBEAT_INTERVAL_HOURS", default_value_t = 20)] + #[arg(long, env = "TWIGPINE_HEARTBEAT_INTERVAL_HOURS", default_value_t = 20)] pub heartbeat_interval_hours: u64, /// Tigris (S3-compatible) bucket for repo storage. /// Leave empty to disable Tigris and use local-only storage. - #[arg(long, env = "GITLAWB_TIGRIS_BUCKET", default_value = "", global = true)] + #[arg( + long, + env = "TWIGPINE_TIGRIS_BUCKET", + default_value = "", + global = true + )] pub tigris_bucket: String, /// Maximum pack body size for git-receive-pack and git-upload-pack, in bytes. /// Applies only to git smart-HTTP routes — all other API routes keep the 2 MB default. /// Default: 2 GB. Set lower on resource-constrained nodes. - #[arg(long, env = "GITLAWB_MAX_PACK_BYTES", default_value_t = 2_147_483_648)] + #[arg(long, env = "TWIGPINE_MAX_PACK_BYTES", default_value_t = 2_147_483_648)] pub max_pack_bytes: usize, /// Per-client-IP rate limit for `POST /api/v1/sync/trigger`, in requests per /// hour. `/sync/trigger` requires a signature and drives an O(peers) outbound /// fan-out per call, so it gets a tight bucket. `0` disables. Default: 60. - #[arg(long, env = "GITLAWB_SYNC_TRIGGER_RATE_LIMIT", default_value_t = 60)] + #[arg(long, env = "TWIGPINE_SYNC_TRIGGER_RATE_LIMIT", default_value_t = 60)] pub sync_trigger_rate_limit: usize, /// Per-client-IP rate limit for the peer-write routes (`/peers/announce`, @@ -303,20 +327,20 @@ pub struct Config { /// known peers and run at higher frequency, so the bucket is generous. Keeping /// it separate from the trigger bucket stops an unsigned notify flood from /// draining the signed trigger caller's quota. `0` disables. Default: 600. - #[arg(long, env = "GITLAWB_PEER_WRITE_RATE_LIMIT", default_value_t = 600)] + #[arg(long, env = "TWIGPINE_PEER_WRITE_RATE_LIMIT", default_value_t = 600)] pub peer_write_rate_limit: usize, /// Optional address to bind a Prometheus `/metrics` exposition endpoint on. /// Example: `127.0.0.1:9091`. Leave empty (default) to disable. /// Bind to localhost or a private interface — the metrics endpoint is /// unauthenticated. - #[arg(long, env = "GITLAWB_METRICS_ADDR", default_value = "")] + #[arg(long, env = "TWIGPINE_METRICS_ADDR", default_value = "")] pub metrics_addr: String, /// Shutdown grace setting, in seconds. Currently not enforced: the value /// is logged at startup and axum drains in-flight requests on the shutdown /// signal with no upper bound. Default: 30s. - #[arg(long, env = "GITLAWB_SHUTDOWN_GRACE_SECS", default_value_t = 30)] + #[arg(long, env = "TWIGPINE_SHUTDOWN_GRACE_SECS", default_value_t = 30)] pub shutdown_grace_secs: u64, /// Maximum number of creation requests (repo create, issue create, PR @@ -326,7 +350,7 @@ pub struct Config { /// creation request. #[arg( long, - env = "GITLAWB_RATE_LIMIT_MAX", + env = "TWIGPINE_RATE_LIMIT_MAX", default_value_t = 10, value_parser = clap::value_parser!(u32).range(1..) )] @@ -337,7 +361,7 @@ pub struct Config { /// timestamp would prune immediately, silently disabling the limiter. #[arg( long, - env = "GITLAWB_RATE_LIMIT_WINDOW_SECS", + env = "TWIGPINE_RATE_LIMIT_WINDOW_SECS", default_value_t = 3600, value_parser = clap::value_parser!(u64).range(1..) )] @@ -355,7 +379,7 @@ pub struct Config { /// teardown (#174). #[arg( long, - env = "GITLAWB_GIT_SERVICE_TIMEOUT_SECS", + env = "TWIGPINE_GIT_SERVICE_TIMEOUT_SECS", default_value_t = 600, value_parser = clap::value_parser!(u64).range(1..=GIT_SERVICE_TIMEOUT_SECS_MAX) )] @@ -376,7 +400,7 @@ pub struct Config { /// positive; set it very large to effectively disable the bound. Default: 30s. #[arg( long, - env = "GITLAWB_GIT_ACQUIRE_TIMEOUT_SECS", + env = "TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS", default_value_t = 30, value_parser = clap::value_parser!(u64).range(1..) )] @@ -389,7 +413,7 @@ pub struct Config { /// for ordinary request handlers and metadata paths (`DB_POOL_APP_HEADROOM`). #[arg( long, - env = "GITLAWB_DB_MAX_CONNECTIONS", + env = "TWIGPINE_DB_MAX_CONNECTIONS", default_value_t = 48, value_parser = clap::value_parser!(u32).range(1..) )] @@ -402,13 +426,13 @@ pub struct Config { /// writers, NOT small. Every in-flight repo write pins one connection here for /// its whole duration (the write, its metadata tail, and the bounded archive /// upload), so this value is a hard ceiling on simultaneous writes node-wide. - /// Keeping it separate from GITLAWB_DB_MAX_CONNECTIONS is what stops a push + /// Keeping it separate from TWIGPINE_DB_MAX_CONNECTIONS is what stops a push /// burst from starving ordinary request handlers; the cost is that /// (main pool + lock pool) must fit inside the database server's /// max_connections, times the number of nodes, plus admin tooling. #[arg( long, - env = "GITLAWB_DB_LOCK_POOL_MAX_CONNECTIONS", + env = "TWIGPINE_DB_LOCK_POOL_MAX_CONNECTIONS", default_value_t = 40, value_parser = clap::value_parser!(u32).range(1..) )] @@ -429,7 +453,7 @@ pub struct Config { /// This is the bound that keeps a stall from becoming an outage. #[arg( long, - env = "GITLAWB_LOCK_HELD_TRANSFER_TIMEOUT_SECS", + env = "TWIGPINE_LOCK_HELD_TRANSFER_TIMEOUT_SECS", default_value_t = 300, value_parser = clap::value_parser!(u64).range(1..) )] @@ -439,7 +463,7 @@ pub struct Config { /// 503, in seconds. Bounds queueing when the database is slow or down. #[arg( long, - env = "GITLAWB_DB_ACQUIRE_TIMEOUT_SECS", + env = "TWIGPINE_DB_ACQUIRE_TIMEOUT_SECS", default_value_t = 5, value_parser = clap::value_parser!(u64).range(1..) )] @@ -451,7 +475,7 @@ pub struct Config { /// attempt is retried (migrations are idempotent). #[arg( long, - env = "GITLAWB_DB_CONNECT_TIMEOUT_SECS", + env = "TWIGPINE_DB_CONNECT_TIMEOUT_SECS", default_value_t = 60, value_parser = clap::value_parser!(u64).range(1..) )] @@ -461,7 +485,7 @@ pub struct Config { /// seconds. Doubles each attempt up to --db-retry-max-secs. #[arg( long, - env = "GITLAWB_DB_RETRY_INITIAL_SECS", + env = "TWIGPINE_DB_RETRY_INITIAL_SECS", default_value_t = 5, value_parser = clap::value_parser!(u64).range(1..) )] @@ -470,7 +494,7 @@ pub struct Config { /// Ceiling on the startup retry delay, in seconds. #[arg( long, - env = "GITLAWB_DB_RETRY_MAX_SECS", + env = "TWIGPINE_DB_RETRY_MAX_SECS", default_value_t = 60, value_parser = clap::value_parser!(u64).range(1..) )] @@ -509,7 +533,7 @@ pub struct Config { /// clean CLI error rather than a boot-time panic. #[arg( long, - env = "GITLAWB_MAX_CONCURRENT_GIT_OPS", + env = "TWIGPINE_MAX_CONCURRENT_GIT_OPS", default_value_t = 128, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -529,17 +553,17 @@ pub struct Config { /// error rather than a boot-time panic). /// /// CONNECTION BUDGET. A push holds a Postgres connection from the node's separate - /// advisory-lock pool (`GITLAWB_DB_LOCK_POOL_MAX_CONNECTIONS`, default 40) for + /// advisory-lock pool (`TWIGPINE_DB_LOCK_POOL_MAX_CONNECTIONS`, default 40) for /// the whole receive-pack. That pool must be at least this value plus /// `DB_LOCK_POOL_NON_PUSH_HEADROOM` so admitted pushes and non-push mutations /// can each pin a lock-pool connection for their whole duration. Size BOTH /// pools against the database server's `max_connections`: the main pool - /// (`GITLAWB_DB_MAX_CONNECTIONS`, default 48) serves ordinary handlers, and the + /// (`TWIGPINE_DB_MAX_CONNECTIONS`, default 48) serves ordinary handlers, and the /// lock pool serves writes. Raising this knob does not raise the lock pool; - /// set `GITLAWB_DB_LOCK_POOL_MAX_CONNECTIONS` explicitly. + /// set `TWIGPINE_DB_LOCK_POOL_MAX_CONNECTIONS` explicitly. #[arg( long, - env = "GITLAWB_MAX_CONCURRENT_GIT_PUSHES", + env = "TWIGPINE_MAX_CONCURRENT_GIT_PUSHES", default_value_t = 32, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -563,7 +587,7 @@ pub struct Config { /// push pool does not raise this; set it explicitly. Must be between 1 and 1_048_576. #[arg( long, - env = "GITLAWB_REPO_LEASE_MAX_WAITERS", + env = "TWIGPINE_REPO_LEASE_MAX_WAITERS", default_value_t = 8, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -585,7 +609,7 @@ pub struct Config { /// Default: 8. Must be between 1 and 1_048_576. #[arg( long, - env = "GITLAWB_MAX_CONCURRENT_PIN_TASKS", + env = "TWIGPINE_MAX_CONCURRENT_PIN_TASKS", default_value_t = 8, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -596,17 +620,17 @@ pub struct Config { /// cannot monopolize the `max_concurrent_git_ops` read pool (#174). Callers are /// keyed on the RESOLVED SOURCE IP, never the DID — a signature does not move a /// caller off this cap, so an authenticated client cannot mint DIDs to escape it. - /// IMPORTANT: the source-IP key is only as granular as `GITLAWB_TRUSTED_PROXY`. + /// IMPORTANT: the source-IP key is only as granular as `TWIGPINE_TRUSTED_PROXY`. /// Left unset (the default), a node behind an edge/NAT keys all callers on the /// edge IP, so this cap collapses to a single global cap rather than per-client. - /// Set `GITLAWB_TRUSTED_PROXY` to key on the real client; a high-fanout caller (a + /// Set `TWIGPINE_TRUSTED_PROXY` to key on the real client; a high-fanout caller (a /// CI fleet behind one NAT) then needs the operator to raise this. Over-cap for a /// caller sheds a clean 503 + Retry-After. /// /// Default: 16. Must be between 1 and 1_048_576. #[arg( long, - env = "GITLAWB_MAX_CONCURRENT_READS_PER_CALLER", + env = "TWIGPINE_MAX_CONCURRENT_READS_PER_CALLER", default_value_t = 16, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -626,7 +650,7 @@ pub struct Config { /// is a clean CLI error rather than a boot-time panic. Default: 32. #[arg( long, - env = "GITLAWB_MAX_CONCURRENT_IPFS_WALKS", + env = "TWIGPINE_MAX_CONCURRENT_IPFS_WALKS", default_value_t = 32, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -634,7 +658,7 @@ pub struct Config { /// Maximum concurrent `/ipfs/{cid}` walk requests a single source may hold at /// once, so one source cannot monopolize `max_concurrent_ipfs_walks` (#174). - /// Callers are keyed on the RESOLVED SOURCE IP (`client_key`/`GITLAWB_TRUSTED_PROXY`), + /// Callers are keyed on the RESOLVED SOURCE IP (`client_key`/`TWIGPINE_TRUSTED_PROXY`), /// never the DID — `/ipfs` accepts any `did:key` via `optional_signature` with no /// admission step, so keying on the DID would let one host mint disposable DIDs to /// multiply its budget. A request with no resolvable key (no trusted header, no @@ -642,7 +666,7 @@ pub struct Config { /// clean 503 + Retry-After. Must be between 1 and 1_048_576. Default: 4. #[arg( long, - env = "GITLAWB_IPFS_WALK_PER_SOURCE", + env = "TWIGPINE_IPFS_WALK_PER_SOURCE", default_value_t = 4, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -659,7 +683,7 @@ pub struct Config { /// Must be between 1 and 1_048_576. Default: 256. #[arg( long, - env = "GITLAWB_IPFS_MAX_LEGACY_PROBES", + env = "TWIGPINE_IPFS_MAX_LEGACY_PROBES", default_value_t = crate::api::ipfs::MAX_LEGACY_PROBES_PER_REQUEST as usize, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -690,7 +714,7 @@ pub struct Config { /// Must be between 1 and 1_048_576. Default: 2048. #[arg( long, - env = "GITLAWB_IPFS_MAX_LEGACY_SCAN_ROWS", + env = "TWIGPINE_IPFS_MAX_LEGACY_SCAN_ROWS", default_value_t = crate::api::ipfs::MAX_LEGACY_SCAN_ROWS_PER_REQUEST, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -725,7 +749,7 @@ pub struct Config { /// remainder). #[arg( long, - env = "GITLAWB_IPFS_MAX_REPOS_WALKED", + env = "TWIGPINE_IPFS_MAX_REPOS_WALKED", default_value_t = 64, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -743,7 +767,7 @@ pub struct Config { /// Default: 1024. #[arg( long, - env = "GITLAWB_IPFS_MAX_REPO_VISITS", + env = "TWIGPINE_IPFS_MAX_REPO_VISITS", default_value_t = 1024, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1_048_576) )] @@ -785,7 +809,7 @@ pub struct Config { /// walk still fits. #[arg( long, - env = "GITLAWB_IPFS_REQUEST_BUDGET_SECS", + env = "TWIGPINE_IPFS_REQUEST_BUDGET_SECS", default_value_t = 600, value_parser = clap::value_parser!(u64).range(1..=GIT_SERVICE_TIMEOUT_SECS_MAX) )] @@ -819,7 +843,7 @@ pub struct Config { /// panics on overflow in release builds too. Default: 10s. #[arg( long, - env = "GITLAWB_IPFS_RESOLVE_BUDGET_SECS", + env = "TWIGPINE_IPFS_RESOLVE_BUDGET_SECS", default_value_t = 10, value_parser = clap::value_parser!(u64).range(1..=GIT_SERVICE_TIMEOUT_SECS_MAX) )] @@ -830,13 +854,13 @@ pub struct Config { /// a full-history git walk, so it carries a per-IP flood brake in addition to the /// concurrency cap above (a rate limit bounds request *rate*, the semaphore /// bounds concurrent slow holds — different axes). Keyed on the resolved client - /// IP via `GITLAWB_TRUSTED_PROXY`. `0` disables. Default: 600. + /// IP via `TWIGPINE_TRUSTED_PROXY`. `0` disables. Default: 600. /// /// This is the pure once-per-request ROUTE brake. The resolver's internal /// per-probe/per-walk WORK budget is a SEPARATE bucket whose capacity is DERIVED /// from this value (`AppState::ipfs_work_budget`), not a knob of its own; `0` here /// disables that derived bucket too. - #[arg(long, env = "GITLAWB_IPFS_RATE_LIMIT", default_value_t = 600)] + #[arg(long, env = "TWIGPINE_IPFS_RATE_LIMIT", default_value_t = 600)] pub ipfs_rate_limit: usize, /// Rows the legacy provider-CID repair sweep reads per batch (U4, #173). @@ -850,7 +874,7 @@ pub struct Config { /// work rather than one expensive burst. Must be between 1 and 100_000. #[arg( long, - env = "GITLAWB_PIN_REPAIR_SWEEP_BATCH", + env = "TWIGPINE_PIN_REPAIR_SWEEP_BATCH", default_value_t = 64, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=100_000) )] @@ -866,7 +890,7 @@ pub struct Config { /// Must be between 0 and 86_400. #[arg( long, - env = "GITLAWB_PIN_REPAIR_SWEEP_DELAY_SECS", + env = "TWIGPINE_PIN_REPAIR_SWEEP_DELAY_SECS", default_value_t = 60, value_parser = clap::builder::RangedU64ValueParser::::new().range(0..=86_400) )] @@ -880,7 +904,7 @@ pub struct Config { /// cheap regardless of the value. #[arg( long, - env = "GITLAWB_QUEUE_RETENTION_DAYS", + env = "TWIGPINE_QUEUE_RETENTION_DAYS", default_value_t = 7, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=365) )] @@ -893,7 +917,7 @@ pub struct Config { /// `main.rs` for the wiring. #[arg( long, - env = "GITLAWB_QUEUE_PURGE_BATCH", + env = "TWIGPINE_QUEUE_PURGE_BATCH", default_value_t = 1000, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=100_000) )] @@ -906,7 +930,7 @@ pub struct Config { /// lower in tests. #[arg( long, - env = "GITLAWB_EFFECTS_MAX_ATTEMPTS", + env = "TWIGPINE_EFFECTS_MAX_ATTEMPTS", default_value_t = 8, value_parser = clap::builder::RangedU64ValueParser::::new().range(1..=1000) )] @@ -919,21 +943,106 @@ pub struct Config { /// when the task is hidden or missing. These reads can require task, /// repository, and visibility-rule queries even when no task is returned, /// so the brake bounds the cost of anonymous probes. Keyed on the resolved - /// client IP via `GITLAWB_TRUSTED_PROXY`. `0` disables. Default: 1200 (a list page + /// client IP via `TWIGPINE_TRUSTED_PROXY`. `0` disables. Default: 1200 (a list page /// followed by per-task reads is a normal client pattern, so this sits above /// the `/ipfs` budget). GraphQL `tasks` / `task` queries, including WebSocket /// operations, share this per-IP budget with REST task reads. - #[arg(long, env = "GITLAWB_TASK_READ_RATE_LIMIT", default_value_t = 1200)] + #[arg(long, env = "TWIGPINE_TASK_READ_RATE_LIMIT", default_value_t = 1200)] pub task_read_rate_limit: usize, } +/// Default for `--key-path`. Resolved through [`default_key_location`]. +pub const DEFAULT_KEY_PATH: &str = "~/.twigpine/identity.pem"; + +/// Default for `--p2p-key-path`. Resolved through [`default_key_location`]. +pub const DEFAULT_P2P_KEY_PATH: &str = "~/.twigpine/p2p.key"; + +/// Where a key path left at its default lives: in `~/.twigpine`, or in an +/// existing `~/.gitlawb` from before the rename when there is no `~/.twigpine` +/// (see `twigpine_core::identity_path::default_dir`). `None` for any other +/// value, including an explicit `~/.gitlawb/...`, which is taken as written. +fn default_key_location(value: &str, default: &str) -> Option { + if value != default { + return None; + } + let file = Path::new(default).file_name()?; + let home = dirs_next::home_dir()?; + Some(twigpine_core::identity_path::default_dir(&home).join(file)) +} + impl Config { + /// `Config::parse()`, plus a record of which key paths were actually + /// given. Clap fills an omitted option with its default text, so the + /// parsed value alone cannot tell "left at the default" from "set to the + /// same text"; the value's source can. + pub fn parse_with_sources() -> Self { + use clap::parser::ValueSource; + use clap::{CommandFactory, FromArgMatches}; + let matches = Self::command().get_matches(); + let mut config = Self::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()); + let given = |id: &str| { + matches + .value_source(id) + .is_some_and(|source| source != ValueSource::DefaultValue) + }; + config.key_path_given = given("key_path"); + config.p2p_key_path_given = given("p2p_key_path"); + config + } + + /// Decide once where key paths left at their default live, and write the + /// answer back, so every later read agrees even if a folder appears while + /// the node is starting. + /// + /// Refuses to go on when the default folder is `~/.twigpine`, a key is + /// missing from it, and that key exists in `~/.gitlawb`. Starting anyway + /// would generate a new node identity or PeerId beside the real one. + fn settle_default_key_paths(&mut self) -> Result<(), String> { + let home = dirs_next::home_dir(); + // With p2p off (port 0) its key is never read, so a missing one must + // not stop the node. + let p2p_on = self.p2p_port > 0; + for (value, default, in_use) in [ + (&mut self.key_path, DEFAULT_KEY_PATH, !self.key_path_given), + ( + &mut self.p2p_key_path, + DEFAULT_P2P_KEY_PATH, + !self.p2p_key_path_given && p2p_on, + ), + ] { + if !in_use { + continue; + } + let Some(path) = default_key_location(value, default) else { + continue; + }; + if let Some(legacy) = + twigpine_core::identity_path::stranded_legacy_key(&path, home.as_deref()) + { + return Err(twigpine_core::identity_path::stranded_legacy_key_message( + &path, &legacy, + )); + } + // A home that is not valid UTF-8 cannot be written back into the + // string setting; it keeps resolving through the default each time. + if let Some(settled) = path.to_str() { + *value = settled.to_string(); + } + } + Ok(()) + } + pub fn bind_addr(&self) -> String { format!("{}:{}", self.host, self.port) } /// Resolve ~ in key_path pub fn resolved_key_path(&self) -> PathBuf { + if !self.key_path_given { + if let Some(path) = default_key_location(&self.key_path, DEFAULT_KEY_PATH) { + return path; + } + } if self.key_path.starts_with("~/") { let suffix = &self.key_path[2..]; if !crate::p2p::tilde_suffix_escapes_home(suffix) { @@ -947,6 +1056,11 @@ impl Config { /// Resolve ~ in p2p_key_path pub fn resolved_p2p_key_path(&self) -> PathBuf { + if !self.p2p_key_path_given { + if let Some(path) = default_key_location(&self.p2p_key_path, DEFAULT_P2P_KEY_PATH) { + return path; + } + } if self.p2p_key_path.starts_with("~/") { let suffix = &self.p2p_key_path[2..]; if !crate::p2p::tilde_suffix_escapes_home(suffix) { @@ -979,6 +1093,7 @@ impl Config { /// `config.web_url` later must see the same string that was actually /// validated. pub fn validate(&mut self) -> Result<(), String> { + self.settle_default_key_paths()?; // Concurrent git writes pin the dedicated lock pool for their whole // duration (connection-affine advisory lock in acquire_write). The main // pool no longer carries that occupancy. @@ -987,7 +1102,7 @@ impl Config { .saturating_add(Self::DB_LOCK_POOL_NON_PUSH_HEADROOM as usize); if (self.db_lock_pool_max_connections as usize) < lock_floor { return Err(format!( - "GITLAWB_DB_LOCK_POOL_MAX_CONNECTIONS ({}) must be at least \ + "TWIGPINE_DB_LOCK_POOL_MAX_CONNECTIONS ({}) must be at least \ max_concurrent_git_pushes ({}) plus {} for non-push mutations \ that share the lock pool", self.db_lock_pool_max_connections, @@ -997,7 +1112,7 @@ impl Config { } if self.upstream_mirror_enabled && !self.enforce_owner_push { return Err( - "GITLAWB_UPSTREAM_MIRROR_ENABLED requires GITLAWB_ENFORCE_OWNER_PUSH=true: \ + "TWIGPINE_UPSTREAM_MIRROR_ENABLED requires TWIGPINE_ENFORCE_OWNER_PUSH=true: \ an upstream-authoritative mirror must not accept writes from arbitrary signed identities" .to_string(), ); @@ -1005,7 +1120,7 @@ impl Config { let main_floor = Self::DB_POOL_APP_HEADROOM as u64; if (self.db_max_connections as u64) < main_floor { return Err(format!( - "GITLAWB_DB_MAX_CONNECTIONS ({}) must be at least {} for non-git \ + "TWIGPINE_DB_MAX_CONNECTIONS ({}) must be at least {} for non-git \ database paths", self.db_max_connections, main_floor )); @@ -1018,7 +1133,7 @@ impl Config { let suffix = &self.key_path[2..]; if crate::p2p::tilde_suffix_escapes_home(suffix) { return Err(format!( - "GITLAWB_KEY ({}) must stay inside the home directory after `~/` \ + "TWIGPINE_KEY ({}) must stay inside the home directory after `~/` \ expansion; rooted suffixes such as `~//etc/identity.pem`, drive-prefixed \ suffixes, and `..` traversal are refused", self.key_path @@ -1028,7 +1143,7 @@ impl Config { let identity_key_path = self.resolved_key_path(); if self.key_path.starts_with("~/") && identity_key_path == Path::new(&self.key_path) { return Err(format!( - "GITLAWB_KEY ({}) starts with `~/` but no home directory could be resolved, \ + "TWIGPINE_KEY ({}) starts with `~/` but no home directory could be resolved, \ so it would name a literal `~` directory relative to the working directory. \ Set an absolute path such as /data/keys/identity.pem.", self.key_path @@ -1040,14 +1155,14 @@ impl Config { .any(|c| matches!(c, std::path::Component::ParentDir)) { return Err(format!( - "GITLAWB_KEY ({}) must name a key file, not a directory; a trailing separator, \ + "TWIGPINE_KEY ({}) must name a key file, not a directory; a trailing separator, \ a final `.` or `..` component, and `..` traversal are refused so the path \ cannot retarget a parent", self.key_path )); } - // P2P is optional: an HTTP-only node with GITLAWB_P2P_PORT=0 never loads + // P2P is optional: an HTTP-only node with TWIGPINE_P2P_PORT=0 never loads // or creates this key, so refusing startup on an unused path would be a // silent outage with no security benefit. if self.p2p_port > 0 { @@ -1062,7 +1177,7 @@ impl Config { // green /health. // // Decided lexically on the resolved path: `canonicalize` would fail on a - // parent that does not exist yet (the shipped `~/.gitlawb` default, and + // parent that does not exist yet (the shipped `~/.twigpine` default, and // every container's first boot), and comparing against the process // working directory would reject `/data/p2p.key` under the image's // WORKDIR, an absolute directory the operator did name. @@ -1077,7 +1192,7 @@ impl Config { let suffix = &self.p2p_key_path[2..]; if crate::p2p::tilde_suffix_escapes_home(suffix) { return Err(format!( - "GITLAWB_P2P_KEY ({}) must stay inside the home directory after `~/` \ + "TWIGPINE_P2P_KEY ({}) must stay inside the home directory after `~/` \ expansion; rooted suffixes such as `~//etc/p2p.key`, drive-prefixed \ suffixes, and `..` traversal are refused", self.p2p_key_path @@ -1088,7 +1203,7 @@ impl Config { if self.p2p_key_path.starts_with("~/") && p2p_key_path == Path::new(&self.p2p_key_path) { return Err(format!( - "GITLAWB_P2P_KEY ({}) starts with `~/` but no home directory could be resolved, \ + "TWIGPINE_P2P_KEY ({}) starts with `~/` but no home directory could be resolved, \ so it would name a literal `~` directory relative to the working directory. \ Set an absolute path such as /data/keys/p2p.key.", self.p2p_key_path @@ -1102,7 +1217,7 @@ impl Config { .map_err(|e| e.to_string())?; } - // GITLAWB_WEB_URL is advertised in GET / so the CLI can print a working + // TWIGPINE_WEB_URL is advertised in GET / so the CLI can print a working // View: link. Clap maps "" to Some("") which would produce a broken URL; // reject early instead of serving a malformed link. Non-blank values must // additionally parse as an absolute http(s) URL — the CLI appends @@ -1113,7 +1228,7 @@ impl Config { Ok(()) => {} Err(reason) => { return Err(format!( - "GITLAWB_WEB_URL {reason} — \ + "TWIGPINE_WEB_URL {reason} — \ set it to an absolute URL like https://gitlawb.com or leave it unset." )); } @@ -1230,7 +1345,7 @@ mod tests { "false", ]); let error = unsafe_config.validate().unwrap_err(); - assert!(error.contains("GITLAWB_ENFORCE_OWNER_PUSH=true")); + assert!(error.contains("TWIGPINE_ENFORCE_OWNER_PUSH=true")); Config::parse_from([ "twigpine-node", @@ -1295,7 +1410,7 @@ mod tests { } /// Child half of [`nonce_flag_env_values_never_silently_enforce`]. It runs in - /// a subprocess with `GITLAWB_REQUIRE_SIGNATURE_NONCE` set, because setting + /// a subprocess with `TWIGPINE_REQUIRE_SIGNATURE_NONCE` set, because setting /// that variable in-process would race every other test that parses a /// `Config` and would take the whole binary down if the value were invalid. #[test] @@ -1308,7 +1423,7 @@ mod tests { } /// The flag is read as a boolean, not as "is the variable present". An - /// operator writing `GITLAWB_REQUIRE_SIGNATURE_NONCE=0` (or leaving it + /// operator writing `TWIGPINE_REQUIRE_SIGNATURE_NONCE=0` (or leaving it /// empty) must never end up enforcing. #[test] fn nonce_flag_env_values_never_silently_enforce() { @@ -1322,7 +1437,7 @@ mod tests { "--ignored", "--nocapture", ]) - .env("GITLAWB_REQUIRE_SIGNATURE_NONCE", value) + .env("TWIGPINE_REQUIRE_SIGNATURE_NONCE", value) .output() .expect("run the env probe"); let stdout = String::from_utf8_lossy(&out.stdout); @@ -1341,7 +1456,7 @@ mod tests { let observed = probe(value); assert_ne!( observed, "PROBE:ok:true", - "GITLAWB_REQUIRE_SIGNATURE_NONCE={value:?} must not enforce, got {observed}" + "TWIGPINE_REQUIRE_SIGNATURE_NONCE={value:?} must not enforce, got {observed}" ); } assert_eq!( @@ -1624,7 +1739,7 @@ mod tests { assert!(Config::try_parse_from(["twigpine-node", "--ipfs-max-repos-walked", "0"]).is_err()); } - /// The `GITLAWB_IPFS_MAX_LEGACY_PROBES` knob must actually reach the legacy-probe + /// The `TWIGPINE_IPFS_MAX_LEGACY_PROBES` knob must actually reach the legacy-probe /// budget it advertises: production seeds `ipfs_max_legacy_probes` from this helper, /// so the knob is a no-op unless the helper reflects it. RED while the helper returns /// the hardcoded `MAX_LEGACY_PROBES_PER_REQUEST` (256 regardless of the knob), GREEN @@ -2157,7 +2272,7 @@ mod tests { /// must match the canonical form actually validated, so every consumer /// (the regular and degraded `GET /` handlers, anyone who reads /// `config.web_url` directly) sees the same string. Without this, an - /// operator that sets `GITLAWB_WEB_URL=" https://git.example "` boots + /// operator that sets `TWIGPINE_WEB_URL=" https://git.example "` boots /// a node that advertises `" https://git.example "` on public /// metadata — different from what was validated, different from what /// any other consumer would parse. @@ -2189,7 +2304,7 @@ mod tests { /// The DECLARED default, read off the parser rather than out of a parse. /// /// `Config::parse_from` consults the process environment, so on a host that - /// exports `GITLAWB_ENFORCE_OWNER_PUSH=false` a parse-based assertion says + /// exports `TWIGPINE_ENFORCE_OWNER_PUSH=false` a parse-based assertion says /// nothing about what this crate declares — it reports the operator's setting. /// Asserting the declaration is the env-independent form, and it is the one that /// actually fails if someone flips `default_value_t` back. @@ -2209,7 +2324,7 @@ mod tests { ); } - /// #338: GITLAWB_PUBLIC_READ is inert, so its help must not claim read + /// #338: TWIGPINE_PUBLIC_READ is inert, so its help must not claim read /// enforcement is missing; it must tell the operator the flag changes /// nothing and where the real control lives. #[test] @@ -2352,7 +2467,7 @@ mod tests { }, Row { port: 7546, - path: "~/.gitlawb/p2p.key", + path: "~/.twigpine/p2p.key", expect: Expect::Accepted, needs_home: true, }, @@ -2399,7 +2514,7 @@ mod tests { }, Row { port: 7546, - path: "~/.gitlawb/.", + path: "~/.twigpine/.", expect: Expect::Rejected("must name a key file"), needs_home: true, }, @@ -2576,20 +2691,54 @@ mod tests { /// path beneath the selected home, and suffixes that would escape are /// left unexpanded (and then rejected by `validate`, as the matrix above /// asserts) rather than joined and repaired after. + #[test] + fn a_key_path_that_was_given_is_taken_as_written_even_when_it_equals_the_default() { + let Some(home) = dirs_next::home_dir() else { + return; + }; + // Left at the default: the folder rule decides (this machine may have + // a `~/.gitlawb` from before the rename). + let omitted = config_with_p2p_key(DEFAULT_P2P_KEY_PATH); + assert_eq!( + omitted.resolved_p2p_key_path(), + twigpine_core::identity_path::default_dir(&home).join("p2p.key") + ); + // The same text, but the operator wrote it: no redirect. + let mut given = config_with_p2p_key(DEFAULT_P2P_KEY_PATH); + given.p2p_key_path_given = true; + assert_eq!( + given.resolved_p2p_key_path(), + home.join(".twigpine").join("p2p.key") + ); + } + #[test] fn p2p_tilde_expansion_stays_beneath_home() { let Some(home) = dirs_next::home_dir() else { return; }; - let resolved = config_with_p2p_key("~/.gitlawb/p2p.key").resolved_p2p_key_path(); + let resolved = config_with_p2p_key("~/.twigpine/p2p.key").resolved_p2p_key_path(); assert!( resolved.starts_with(&home), "the resolved default must stay beneath home" ); - assert!( - resolved.ends_with(".gitlawb/p2p.key"), - "the resolved default must keep the configured suffix" + // The default folder is `~/.twigpine`, or an existing `~/.gitlawb` from + // before the rename, whichever this machine has. + assert_eq!( + resolved, + twigpine_core::identity_path::default_dir(&home).join("p2p.key"), + "the resolved default must be the key file in the default folder" + ); + // A path that is not the default keeps its own suffix. + assert_eq!( + config_with_p2p_key("~/keys/p2p.key").resolved_p2p_key_path(), + home.join("keys/p2p.key") + ); + assert_eq!( + config_with_p2p_key("~/.gitlawb/p2p.key").resolved_p2p_key_path(), + home.join(".gitlawb/p2p.key"), + "an explicit old folder is taken as written" ); for path in ["~//etc/p2p.key", "~/../etc/p2p.key"] { @@ -2645,7 +2794,7 @@ mod tests { "./keys/p2p.key", "/data/keys/p2p.key", "/data/p2p.key", - "~/.gitlawb/p2p.key", + "~/.twigpine/p2p.key", ] { assert!( config_with_p2p_key(path).validate().is_ok(), @@ -2709,7 +2858,7 @@ mod tests { .validate() .expect_err("a terminal `.` must be rejected as a directory"); assert!( - err.contains("GITLAWB_KEY") && err.contains("must name a key file"), + err.contains("TWIGPINE_KEY") && err.contains("must name a key file"), "{path:?} must be refused before Path can retarget it, got: {err}" ); } diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index f3263c13..87903f2b 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -989,7 +989,7 @@ impl Db { /// /// Kept separate from the main pool so a burst of lock-holding connections /// cannot starve ordinary request handlers. See - /// `GITLAWB_DB_LOCK_POOL_MAX_CONNECTIONS` for the sizing tradeoff. + /// `TWIGPINE_DB_LOCK_POOL_MAX_CONNECTIONS` for the sizing tradeoff. pub fn lock_pool( database_url: &str, max_connections: u32, diff --git a/crates/twigpine-node/src/error.rs b/crates/twigpine-node/src/error.rs index e51fb964..7e32bbc8 100644 --- a/crates/twigpine-node/src/error.rs +++ b/crates/twigpine-node/src/error.rs @@ -60,7 +60,7 @@ pub enum AppError { /// The signature replay ledger refused a write whose handler spends the /// signature itself (see `auth::LedgerTicket`). Carries the shared /// [`NodeDenial`](twigpine_core::node_denial::NodeDenial) so the status, the - /// `X-Gitlawb-Error` header and the body code are exactly what the + /// `X-Twigpine-Error` header and the body code are exactly what the /// `consume_signature` layer answers on every other route. #[error("signature ledger refused: {message}")] LedgerDenial { @@ -341,13 +341,13 @@ impl IntoResponse for AppError { use axum::http::HeaderValue; let code = twigpine_core::node_denial::NodeDenial::RateLimited.as_str(); if let Ok(v) = HeaderValue::from_str(code) { - resp.headers_mut().insert("X-Gitlawb-Error", v); + resp.headers_mut().insert("X-Twigpine-Error", v); } } if let AppError::LedgerDenial { denial, .. } = &self { use axum::http::HeaderValue; if let Ok(v) = HeaderValue::from_str(denial.as_str()) { - resp.headers_mut().insert("X-Gitlawb-Error", v); + resp.headers_mut().insert("X-Twigpine-Error", v); } } // Both retryable 503s advertise when to retry: Overloaded (capacity shed) and @@ -412,7 +412,7 @@ mod tests { let resp = AppError::TooManyRequests("slow down".into()).into_response(); assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS); assert_eq!( - resp.headers().get("X-Gitlawb-Error"), + resp.headers().get("X-Twigpine-Error"), Some(&HeaderValue::from_static("rate_limited")) ); } @@ -423,7 +423,7 @@ mod tests { let resp = AppError::RateLimited(std::time::Duration::from_secs(7)).into_response(); assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS); assert_eq!( - resp.headers().get("X-Gitlawb-Error"), + resp.headers().get("X-Twigpine-Error"), Some(&HeaderValue::from_static("rate_limited")) ); assert_eq!( diff --git a/crates/twigpine-node/src/git/push_delta.rs b/crates/twigpine-node/src/git/push_delta.rs index 4a545f8b..d48dc0db 100644 --- a/crates/twigpine-node/src/git/push_delta.rs +++ b/crates/twigpine-node/src/git/push_delta.rs @@ -36,7 +36,7 @@ use anyhow::Result; /// Env var that forces the push path to always full-scan, bypassing the delta /// optimization (KTD7 kill-switch). Reuses the already-tested fallback branch /// rather than introducing a second enumeration path. Does not gate the sweep. -const FORCE_FULL_SCAN_ENV: &str = "GITLAWB_PIN_FORCE_FULLSCAN"; +const FORCE_FULL_SCAN_ENV: &str = "TWIGPINE_PIN_FORCE_FULLSCAN"; /// The objects a push introduced, or a signal that the delta could not be /// computed safely and the caller should fall back to a full scan. diff --git a/crates/twigpine-node/src/git/repo_store.rs b/crates/twigpine-node/src/git/repo_store.rs index b91c17ef..986aa391 100644 --- a/crates/twigpine-node/src/git/repo_store.rs +++ b/crates/twigpine-node/src/git/repo_store.rs @@ -60,7 +60,7 @@ pub struct RepoStore { /// separate from the pool serving ordinary request handlers. Each write guard /// pins one connection here for its whole lifetime, so a push burst consumes /// this pool rather than starving application queries. Sized by - /// `GITLAWB_DB_LOCK_POOL_MAX_CONNECTIONS`. + /// `TWIGPINE_DB_LOCK_POOL_MAX_CONNECTIONS`. lock_pool: PgPool, /// Bound on any object-storage transfer that runs while the lock is HELD. lock_held_transfer_timeout: Duration, @@ -553,7 +553,7 @@ impl RepoStore { pool_idle = self.lock_pool.num_idle(), err = %e, "advisory-lock pool acquire failed — writes are being shed; \ - raise GITLAWB_DB_LOCK_POOL_MAX_CONNECTIONS or investigate long-held write locks" + raise TWIGPINE_DB_LOCK_POOL_MAX_CONNECTIONS or investigate long-held write locks" ); return Err(anyhow::Error::new(LockPoolBusy)) .context(format!("advisory-lock pool exhausted or unreachable: {e}")); diff --git a/crates/twigpine-node/src/git/smart_http.rs b/crates/twigpine-node/src/git/smart_http.rs index a59d44ee..13a99eee 100644 --- a/crates/twigpine-node/src/git/smart_http.rs +++ b/crates/twigpine-node/src/git/smart_http.rs @@ -131,7 +131,7 @@ pub async fn info_refs( .status(StatusCode::OK) .header("Content-Type", content_type) .header("Cache-Control", "no-cache") - .header("X-Gitlawb-Node", "v0.1.0") + .header("X-Twigpine-Node", "v0.1.0") .body(Body::from(body))?) } diff --git a/crates/twigpine-node/src/git/tigris.rs b/crates/twigpine-node/src/git/tigris.rs index 374c8775..20e4ba88 100644 --- a/crates/twigpine-node/src/git/tigris.rs +++ b/crates/twigpine-node/src/git/tigris.rs @@ -792,7 +792,12 @@ mod tests { /// to real AWS S3, and a probe that passed there would say nothing about /// Tigris. fn probe_env() -> Option { - if std::env::var("GITLAWB_TIGRIS_PROBE").ok().as_deref() != Some("1") { + // Read under either name: a test never runs the startup step that + // carries a setting's old name over, and a probe that silently skips + // looks exactly like one that passed. + let setting = + |rest: &str| twigpine_core::legacy_env::read(rest).and_then(|v| v.into_string().ok()); + if setting("TIGRIS_PROBE").as_deref() != Some("1") { return None; } for name in [ @@ -805,11 +810,11 @@ mod tests { return None; } } - match std::env::var("GITLAWB_TIGRIS_BUCKET") { - Ok(b) if !b.is_empty() => Some(b), + match setting("TIGRIS_BUCKET") { + Some(b) => Some(b), _ => { eprintln!( - "tigris conditional-write probe: GITLAWB_TIGRIS_BUCKET is unset, skipping" + "tigris conditional-write probe: TWIGPINE_TIGRIS_BUCKET is unset, skipping" ); None } @@ -943,20 +948,20 @@ mod tests { /// operations as supported on Single-region and Multi-region buckets only. /// Global and Dual-region buckets are eventually consistent, and a /// conditional PUT evaluated against a stale replica would make the fence a - /// silent no-op rather than an error. So point `GITLAWB_TIGRIS_BUCKET` at a + /// silent no-op rather than an error. So point `TWIGPINE_TIGRIS_BUCKET` at a /// throwaway bucket of the SAME type production uses. /// - /// Ignored by default and additionally gated on `GITLAWB_TIGRIS_PROBE=1`, + /// Ignored by default and additionally gated on `TWIGPINE_TIGRIS_PROBE=1`, /// because it writes to a real bucket and costs real requests. Run with: - /// `GITLAWB_TIGRIS_PROBE=1 cargo test -p twigpine-node --lib + /// `TWIGPINE_TIGRIS_PROBE=1 cargo test -p twigpine-node --lib /// tigris_honors_conditional_writes -- --ignored --nocapture` #[tokio::test] - #[ignore = "writes to a real Tigris bucket; needs GITLAWB_TIGRIS_PROBE=1 plus credentials"] + #[ignore = "writes to a real Tigris bucket; needs TWIGPINE_TIGRIS_PROBE=1 plus credentials"] async fn tigris_honors_conditional_writes() { let Some(bucket) = probe_env() else { eprintln!( - "tigris conditional-write probe: skipped. Set GITLAWB_TIGRIS_PROBE=1, \ - GITLAWB_TIGRIS_BUCKET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and \ + "tigris conditional-write probe: skipped. Set TWIGPINE_TIGRIS_PROBE=1, \ + TWIGPINE_TIGRIS_BUCKET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and \ AWS_ENDPOINT_URL_S3 to run it." ); return; diff --git a/crates/twigpine-node/src/git/visibility_pack.rs b/crates/twigpine-node/src/git/visibility_pack.rs index 5f579304..adbb9da1 100644 --- a/crates/twigpine-node/src/git/visibility_pack.rs +++ b/crates/twigpine-node/src/git/visibility_pack.rs @@ -32,7 +32,7 @@ type BlobTreeSets = ( /// permit on the upload-pack serve path, the write permit on the receive-pack /// post-push replication path) past the deadline. Every caller funnels through /// `blob_paths`, so bounding here bounds both paths at one seam. Production callers -/// pass the operator-configured `GITLAWB_GIT_SERVICE_TIMEOUT_SECS` instead; this +/// pass the operator-configured `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` instead; this /// fixed budget only backs the `git_bin`-less test wrappers. #[cfg(test)] const WALK_TIMEOUT: Duration = Duration::from_secs(600); @@ -1545,7 +1545,7 @@ pub fn withheld_blob_oids( /// [`withheld_blob_oids`] with an injectable `git_bin` and walk `timeout`. Served /// handlers call this with the operator-configured git binary and -/// `GITLAWB_GIT_SERVICE_TIMEOUT_SECS`, so the whole walk is bounded by the same +/// `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS`, so the whole walk is bounded by the same /// budget as the other served-git ops and a fake `git` can drive its teardown in /// tests. The `git_bin`-less wrapper above keeps the fixed [`WALK_TIMEOUT`] for the /// classification tests that run against real git. @@ -3119,7 +3119,7 @@ esac\n"; /// the stdout drain returns EOF early, `done_tx.send` stands the watchdog down /// before it ever fires (`recv` gets `Ok` -> `false`, no kill), and `child.wait()` /// then blocks on the still-alive leader — pinning the walk thread and its read/ - /// write permit past the deadline, bypassing GITLAWB_GIT_SERVICE_TIMEOUT_SECS. + /// write permit past the deadline, bypassing TWIGPINE_GIT_SERVICE_TIMEOUT_SECS. /// This is distinct from the descendant case above: there the leader sleeps until /// the deadline so the watchdog DOES time out; here the drain-EOF races ahead of /// the deadline. The fix keeps the watchdog armed until the child is actually diff --git a/crates/twigpine-node/src/ipfs_pin.rs b/crates/twigpine-node/src/ipfs_pin.rs index 5aaccccd..8490baaa 100644 --- a/crates/twigpine-node/src/ipfs_pin.rs +++ b/crates/twigpine-node/src/ipfs_pin.rs @@ -1654,7 +1654,7 @@ pub async fn pin_git_object( // Kubo returns newline-delimited JSON; we only care about the last object // (there's typically just one for a single-file add). // - // The response MUST carry a real `Hash`: a misconfigured `GITLAWB_IPFS_API` + // The response MUST carry a real `Hash`: a misconfigured `TWIGPINE_IPFS_API` // (proxy returning HTML, health check on the wrong port, truncated gateway) // can otherwise answer 2xx with no JSON, and falling back to the locally // computed `expected_cid` would record a row for bytes the backend never @@ -1693,7 +1693,7 @@ pub async fn pin_git_object( None => { return Err(anyhow::anyhow!( "IPFS /api/v0/add returned 2xx without a Hash field; refusing to record \ - a CID the backend never acknowledged (misconfigured GITLAWB_IPFS_API?)" + a CID the backend never acknowledged (misconfigured TWIGPINE_IPFS_API?)" )); } }; @@ -2622,7 +2622,7 @@ mod tests { ); } - /// The misconfigured-`GITLAWB_IPFS_API` false positive (P3): a 2xx response + /// The misconfigured-`TWIGPINE_IPFS_API` false positive (P3): a 2xx response /// that carries no `Hash` field (proxy returning HTML, health check on the /// wrong port, truncated gateway) must FAIL the pin, not fall back to the /// locally computed `expected_cid`. Falling back records a `pinned_cids` diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index 410b8649..2173aa00 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -44,7 +44,6 @@ use axum::http::StatusCode; use axum::response::IntoResponse; use axum::routing::get; use axum::{Json, Router}; -use clap::Parser; use std::collections::HashSet; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Arc; @@ -101,7 +100,29 @@ pub async fn run() -> Result<()> { ) .init(); - let mut config = Config::parse(); + let mut config = Config::parse_with_sources(); + + // Settings given under their names from before the rename still work + // (`main` copied them over before anything read a setting). Say which, by + // name only, so an operator can update the unit file at leisure. + let legacy = twigpine_core::legacy_env::report(); + if !legacy.legacy_only.is_empty() { + info!( + settings = %legacy.legacy_only.join(", "), + "these settings were given under their old GITLAWB_ names, which still work; \ + the names are TWIGPINE_ now" + ); + } + if !legacy.conflicts.is_empty() { + // A warning: the value in use may not be the one the operator meant, + // for example a GITLAWB_ setting in an override file that a TWIGPINE_ + // default now outranks. (The image's own defaults are not counted.) + warn!( + settings = %legacy.conflicts.join(", "), + "these settings have a different value under their old GITLAWB_ name; \ + the TWIGPINE_ value is used. Remove or rename the GITLAWB_ one" + ); + } // Admin subcommands run out-of-band and exit, never starting the node. The // no-subcommand path below is the unchanged daemon startup. @@ -110,7 +131,7 @@ pub async fn run() -> Result<()> { } // Merge the embedded seed list of public network nodes into the runtime - // bootstrap peers. Operators can opt out via GITLAWB_BOOTSTRAP_DISABLE_SEEDS. + // bootstrap peers. Operators can opt out via TWIGPINE_BOOTSTRAP_DISABLE_SEEDS. bootstrap::merge_seeds(&mut config); // Fail fast on config combinations that are individually in-range but jointly @@ -122,7 +143,7 @@ pub async fn run() -> Result<()> { if !config.public_read { warn!( - "GITLAWB_PUBLIC_READ=false has no effect; reads are gated per repository by is_public and path-scoped visibility rules, not this flag" + "TWIGPINE_PUBLIC_READ=false has no effect; reads are gated per repository by is_public and path-scoped visibility rules, not this flag" ); } @@ -136,7 +157,7 @@ pub async fn run() -> Result<()> { // One-time metrics init. Must run before any handler that calls into // `metrics::record_*` so the registry exists when the first event fires. - // Safe to call even when GITLAWB_METRICS_ADDR is unset — those helpers + // Safe to call even when TWIGPINE_METRICS_ADDR is unset — those helpers // are simply no-ops until something reads from the registry. metrics::init(env!("CARGO_PKG_VERSION"), &node_did.to_string()); @@ -186,7 +207,7 @@ pub async fn run() -> Result<()> { } } } else { - info!("metrics endpoint disabled (GITLAWB_METRICS_ADDR not set)"); + info!("metrics endpoint disabled (TWIGPINE_METRICS_ADDR not set)"); None }; @@ -398,8 +419,8 @@ pub async fn run() -> Result<()> { // Per-DID limiter for the creation endpoints. Keyed on the authenticated // DID (attacker-varied), so bound its key set to cap memory. Max and window - // are operator-configurable via GITLAWB_RATE_LIMIT_MAX / - // GITLAWB_RATE_LIMIT_WINDOW_SECS; both reject 0 at parse time. + // are operator-configurable via TWIGPINE_RATE_LIMIT_MAX / + // TWIGPINE_RATE_LIMIT_WINDOW_SECS; both reject 0 at parse time. let rate_limiter = rate_limit::RateLimiter::new_bounded( config.rate_limit_max_requests as usize, std::time::Duration::from_secs(config.rate_limit_window_secs), @@ -411,9 +432,9 @@ pub async fn run() -> Result<()> { // exactly how the recurring spam-repo floods get past both it and the // iCaptcha gate. Keyed on the resolved client IP so a single-source flood is // capped regardless of how many identities it mints. Sized well above any - // legitimate per-IP creation rate; GITLAWB_CREATE_RATE_LIMIT overrides, 0 + // legitimate per-IP creation rate; TWIGPINE_CREATE_RATE_LIMIT overrides, 0 // disables. Bounded key set — the key is a client-influenced IP. - let create_ip_rate_limiter = build_ip_limiter("GITLAWB_CREATE_RATE_LIMIT", 120, "creation"); + let create_ip_rate_limiter = build_ip_limiter("TWIGPINE_CREATE_RATE_LIMIT", 120, "creation"); // Per-IP brake for the authenticated non-creation write surface (issue/PR // comments, issue close, labels, stars, merges, protect, replicas, webhook @@ -423,20 +444,20 @@ pub async fn run() -> Result<()> { // creation brake, so a write flood cannot drain the creation budget and vice // versa (same rationale as the sync_trigger / peer_write split). Sized above // any legitimate per-IP write rate — real agent automation makes many small - // writes per hour. GITLAWB_WRITE_RATE_LIMIT overrides; 0 disables. Bounded + // writes per hour. TWIGPINE_WRITE_RATE_LIMIT overrides; 0 disables. Bounded // key set — the key is a client-influenced IP. - let write_rate_limiter = build_ip_limiter("GITLAWB_WRITE_RATE_LIMIT", 600, "write"); + let write_rate_limiter = build_ip_limiter("TWIGPINE_WRITE_RATE_LIMIT", 600, "write"); // Push-path flood brake: max git-receive-pack requests per client IP per // hour (counts both the info/refs advertisement and the push POST). Sized // for heavy agent automation while still stopping flood traffic (the June - // 2026 attack pushed several times per second per IP). GITLAWB_PUSH_RATE_LIMIT + // 2026 attack pushed several times per second per IP). TWIGPINE_PUSH_RATE_LIMIT // overrides; 0 disables. Bounded key set — the key is a client-influenced IP. - let push_rate_limiter = build_ip_limiter("GITLAWB_PUSH_RATE_LIMIT", 600, "push"); + let push_rate_limiter = build_ip_limiter("TWIGPINE_PUSH_RATE_LIMIT", 600, "push"); // close_issue drives a full archive download for non-owner author pre-checks. // Keep it on its own bucket so it cannot drain the receive-pack limit. - let close_issue_limit = std::env::var("GITLAWB_CLOSE_ISSUE_RATE_LIMIT") + let close_issue_limit = std::env::var("TWIGPINE_CLOSE_ISSUE_RATE_LIMIT") .ok() .and_then(|v| v.trim().parse::().ok()) .unwrap_or(120); @@ -447,15 +468,15 @@ pub async fn run() -> Result<()> { ); if close_issue_limit == 0 { tracing::warn!( - "GITLAWB_CLOSE_ISSUE_RATE_LIMIT=0 — per-IP close_issue rate limiting disabled" + "TWIGPINE_CLOSE_ISSUE_RATE_LIMIT=0 — per-IP close_issue rate limiting disabled" ); } // Which forwarded header the edge is trusted to set. Default None (trust - // nothing, key on the socket peer). Fly nodes set GITLAWB_TRUSTED_PROXY=fly; + // nothing, key on the socket peer). Fly nodes set TWIGPINE_TRUSTED_PROXY=fly; // a node behind Caddy/NGINX sets it to x-forwarded-for. let push_limiter_trust = rate_limit::TrustedProxy::from_env_value( - &std::env::var("GITLAWB_TRUSTED_PROXY").unwrap_or_default(), + &std::env::var("TWIGPINE_TRUSTED_PROXY").unwrap_or_default(), ); tracing::info!(trust = ?push_limiter_trust, "push rate limiter trust configured"); @@ -477,11 +498,11 @@ pub async fn run() -> Result<()> { rate_limit::RateLimiter::new_bounded(12, std::time::Duration::from_secs(60), 10_000); if config.sync_trigger_rate_limit == 0 { tracing::warn!( - "GITLAWB_SYNC_TRIGGER_RATE_LIMIT=0 — /sync/trigger IP rate limiting disabled" + "TWIGPINE_SYNC_TRIGGER_RATE_LIMIT=0 — /sync/trigger IP rate limiting disabled" ); } if config.peer_write_rate_limit == 0 { - tracing::warn!("GITLAWB_PEER_WRITE_RATE_LIMIT=0 — peer-write IP rate limiting disabled"); + tracing::warn!("TWIGPINE_PEER_WRITE_RATE_LIMIT=0 — peer-write IP rate limiting disabled"); } // Initialize the iCaptcha proof gate (inert unless ICAPTCHA_MODE is set). @@ -619,10 +640,10 @@ pub async fn run() -> Result<()> { } if config.ipfs_rate_limit == 0 { - tracing::warn!("GITLAWB_IPFS_RATE_LIMIT=0 — per-IP /ipfs rate limiting disabled"); + tracing::warn!("TWIGPINE_IPFS_RATE_LIMIT=0 — per-IP /ipfs rate limiting disabled"); } if config.task_read_rate_limit == 0 { - tracing::warn!("GITLAWB_TASK_READ_RATE_LIMIT=0 — per-IP task read rate limiting disabled"); + tracing::warn!("TWIGPINE_TASK_READ_RATE_LIMIT=0 — per-IP task read rate limiting disabled"); } // Periodic peer-count poll for the metrics gauge. If p2p is disabled @@ -811,7 +832,7 @@ pub async fn run() -> Result<()> { } } } else { - info!("on-chain PoS disabled (GITLAWB_CONTRACT_NODE_STAKING or GITLAWB_OPERATOR_PRIVATE_KEY unset)"); + info!("on-chain PoS disabled (TWIGPINE_CONTRACT_NODE_STAKING or TWIGPINE_OPERATOR_PRIVATE_KEY unset)"); } // axum's `with_graceful_shutdown` waits for in-flight requests to @@ -924,7 +945,7 @@ fn resolve_rate_limit(raw: Option<&str>, default: usize) -> (usize, bool) { } /// Read a rate-limit env var, warning on a present-but-unparseable value. A typo -/// like `GITLAWB_WRITE_RATE_LIMIT=5O` must not silently revert to the default and +/// like `TWIGPINE_WRITE_RATE_LIMIT=5O` must not silently revert to the default and /// leave the operator believing a stricter cap is in force. fn rate_limit_from_env(var: &str, default: usize) -> usize { let raw = std::env::var(var).ok(); @@ -986,7 +1007,7 @@ async fn run_admin_command(command: config::Command, config: &Config) -> Result< // on a Tigris deployment is the stale-view delete this // guards against. Refuse to run rather than fall back. anyhow::bail!( - "purge-spam: GITLAWB_TIGRIS_BUCKET is set but the object-store client failed to initialize ({e}); refusing to run a local-only purge on a Tigris deployment" + "purge-spam: TWIGPINE_TIGRIS_BUCKET is set but the object-store client failed to initialize ({e}); refusing to run a local-only purge on a Tigris deployment" ); } } @@ -994,7 +1015,7 @@ async fn run_admin_command(command: config::Command, config: &Config) -> Result< // Give the purge-spam store a dedicated advisory-lock pool, separate // from `db`'s app pool. The guard then holds a lock-pool connection // while `delete_repo_by_id` runs on the app pool, so a purge at - // GITLAWB_DB_MAX_CONNECTIONS=1 does not self-deadlock (KTD3). + // TWIGPINE_DB_MAX_CONNECTIONS=1 does not self-deadlock (KTD3). let lock_pool = Db::lock_pool( &config.database_url, config.db_lock_pool_max_connections, @@ -1223,7 +1244,7 @@ async fn connect_db_with_retry( { Ok(result) => result, Err(_) => Err(anyhow!( - "connect + migrate attempt exceeded {}s (GITLAWB_DB_CONNECT_TIMEOUT_SECS); \ + "connect + migrate attempt exceeded {}s (TWIGPINE_DB_CONNECT_TIMEOUT_SECS); \ is another instance holding the migration lock?", attempt_timeout.as_secs() )), @@ -1393,6 +1414,7 @@ fn build_degraded_router( Router::new() .route("/", get(degraded_node_info)) .fallback(degraded_unavailable) + .layer(axum::middleware::from_fn(server::send_legacy_header_names)) .with_state(state) } @@ -1429,7 +1451,7 @@ fn degraded_body(db_startup: &DbStartupStatus) -> serde_json::Value { async fn degraded_node_info(State(state): State) -> impl IntoResponse { let mut body = degraded_body(&state.db_startup); if let Some(obj) = body.as_object_mut() { - obj.insert("name".into(), "gitlawb-node".into()); + obj.insert("name".into(), "twigpine-node".into()); obj.insert("version".into(), env!("CARGO_PKG_VERSION").into()); obj.insert("did".into(), state.node_did.clone().into()); if let Some(web_url) = &state.web_url { @@ -1889,7 +1911,7 @@ fn load_or_create_keypair_at(key_path: &std::path::Path) -> Result { .any(|c| matches!(c, std::path::Component::ParentDir)) { anyhow::bail!( - "GITLAWB_KEY ({}) must name a key file, not a directory; a trailing separator, \ + "TWIGPINE_KEY ({}) must name a key file, not a directory; a trailing separator, \ a final `.` or `..` component, and `..` traversal are refused so the path \ cannot retarget a parent", key_path.display() @@ -2575,7 +2597,7 @@ mod identity_key_storage_tests { /// Fixture: one (layout, umask, phase) row of the identity lifecycle /// matrix. /// - /// `~/.gitlawb` holds BOTH keys, and `load_or_create_keypair` runs before + /// `~/.twigpine` holds BOTH keys, and `load_or_create_keypair` runs before /// the listener binds, so a mask that strips owner bits here takes the /// whole node down before any p2p code is reached. `umask` is /// process-global, so every row is a child. Double-gated like the p2p @@ -2584,20 +2606,20 @@ mod identity_key_storage_tests { /// a process-global umask inside the shared test process. #[cfg(unix)] #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=identity-key-umask"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=identity-key-umask"] fn fixture_identity_key_under_hostile_umask() { use std::os::unix::fs::PermissionsExt; - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() != Some("identity-key-umask") { + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("identity-key-umask") { return; } let base = std::path::PathBuf::from( - std::env::var("GITLAWB_TEST_BASE").expect("GITLAWB_TEST_BASE"), + std::env::var("TWIGPINE_TEST_BASE").expect("TWIGPINE_TEST_BASE"), ); let umask_val = - u32::from_str_radix(&std::env::var("GITLAWB_TEST_UMASK").unwrap(), 8).unwrap(); - let layout = std::env::var("GITLAWB_TEST_LAYOUT").expect("GITLAWB_TEST_LAYOUT"); - let phase = std::env::var("GITLAWB_TEST_PHASE").expect("GITLAWB_TEST_PHASE"); + u32::from_str_radix(&std::env::var("TWIGPINE_TEST_UMASK").unwrap(), 8).unwrap(); + let layout = std::env::var("TWIGPINE_TEST_LAYOUT").expect("TWIGPINE_TEST_LAYOUT"); + let phase = std::env::var("TWIGPINE_TEST_PHASE").expect("TWIGPINE_TEST_PHASE"); // SAFETY: `umask` only reads and replaces the process-wide value, and // this process exists solely for this probe. No restore: the value dies @@ -2608,7 +2630,7 @@ mod identity_key_storage_tests { match layout.as_str() { "one-missing" => { - let dir = base.join(".gitlawb"); + let dir = base.join(".twigpine"); let key = dir.join("identity.pem"); let did = run_identity_success_row(&base, &key, &key, &[dir], &phase); println!("identity-key-umask: asserted did={did}"); @@ -2852,10 +2874,11 @@ mod identity_key_storage_tests { // only it knows the race has finished. "concurrent-first-boot" => { let barrier = std::path::PathBuf::from( - std::env::var("GITLAWB_TEST_BARRIER").expect("GITLAWB_TEST_BARRIER"), + std::env::var("TWIGPINE_TEST_BARRIER").expect("TWIGPINE_TEST_BARRIER"), ); - let id = std::env::var("GITLAWB_TEST_RACE_ID").expect("GITLAWB_TEST_RACE_ID"); - let role = std::env::var("GITLAWB_TEST_RACE_ROLE").expect("GITLAWB_TEST_RACE_ROLE"); + let id = std::env::var("TWIGPINE_TEST_RACE_ID").expect("TWIGPINE_TEST_RACE_ID"); + let role = + std::env::var("TWIGPINE_TEST_RACE_ROLE").expect("TWIGPINE_TEST_RACE_ROLE"); let key = base.join("one").join("two").join("identity.pem"); // Two-phase rendezvous: each child announces itself with @@ -2931,14 +2954,14 @@ mod identity_key_storage_tests { } } - /// GITLAWB_KEY names a PEM file, not a dedicated key directory. An existing + /// TWIGPINE_KEY names a PEM file, not a dedicated key directory. An existing /// 0755 parent is usable (no group/world write) and must not be chmodded. #[cfg(unix)] #[test] fn existing_identity_parent_is_not_chmodded() { use std::os::unix::fs::PermissionsExt; - for parent_name in [".gitlawb", "shared"] { + for parent_name in [".twigpine", "shared"] { let base = tempfile::tempdir().unwrap(); std::fs::set_permissions(base.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); let dir = base.path().join(parent_name); @@ -2978,7 +3001,7 @@ mod identity_key_storage_tests { let base = tempfile::tempdir().unwrap(); std::fs::set_permissions(base.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); - let dir = base.path().join(".gitlawb"); + let dir = base.path().join(".twigpine"); let key = dir.join("identity.pem"); load_or_create_keypair_at(&key).expect("first boot creates the identity parent"); let mode = std::fs::symlink_metadata(&dir) @@ -3028,7 +3051,7 @@ mod identity_key_storage_tests { let base = tempfile::tempdir().unwrap(); std::fs::set_permissions(base.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); - let key = base.path().join(".gitlawb").join("identity.pem"); + let key = base.path().join(".twigpine").join("identity.pem"); let created = load_or_create_keypair_at(&key).expect("first boot"); let before = std::fs::read(&key).unwrap(); @@ -3090,18 +3113,18 @@ mod identity_key_storage_tests { // Both filters are optional and both panic on a value that names // nothing: a typo that quietly ran no child would be an empty green, // which is the failure this matrix exists to rule out. - let layout_only = std::env::var("GITLAWB_TEST_LAYOUT_ONLY").ok(); - let umask_only = std::env::var("GITLAWB_TEST_UMASK_ONLY").ok(); + let layout_only = std::env::var("TWIGPINE_TEST_LAYOUT_ONLY").ok(); + let umask_only = std::env::var("TWIGPINE_TEST_UMASK_ONLY").ok(); if let Some(l) = layout_only.as_deref() { assert!( rows.iter().any(|r| r.0 == l), - "GITLAWB_TEST_LAYOUT_ONLY={l} names no row in the matrix" + "TWIGPINE_TEST_LAYOUT_ONLY={l} names no row in the matrix" ); } if let Some(u) = umask_only.as_deref() { assert!( ALL_UMASKS.contains(&u), - "GITLAWB_TEST_UMASK_ONLY={u} names no umask in the matrix" + "TWIGPINE_TEST_UMASK_ONLY={u} names no umask in the matrix" ); } @@ -3120,11 +3143,11 @@ mod identity_key_storage_tests { "--ignored", "--nocapture", ]) - .env("GITLAWB_TEST_FIXTURE", "identity-key-umask") - .env("GITLAWB_TEST_BASE", base) - .env("GITLAWB_TEST_UMASK", umask) - .env("GITLAWB_TEST_LAYOUT", layout) - .env("GITLAWB_TEST_PHASE", phase); + .env("TWIGPINE_TEST_FIXTURE", "identity-key-umask") + .env("TWIGPINE_TEST_BASE", base) + .env("TWIGPINE_TEST_UMASK", umask) + .env("TWIGPINE_TEST_LAYOUT", layout) + .env("TWIGPINE_TEST_PHASE", phase); let output = cmd.output().expect("spawn the identity-key fixture"); let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); @@ -3244,11 +3267,11 @@ mod identity_key_storage_tests { // A single run of a nondeterministic test proves very little, so the // default loops the whole race; raise it through the env for a longer // shake without editing the test. - let iterations: usize = std::env::var("GITLAWB_TEST_RACE_ITERATIONS") + let iterations: usize = std::env::var("TWIGPINE_TEST_RACE_ITERATIONS") .ok() .map(|v| { v.parse() - .expect("GITLAWB_TEST_RACE_ITERATIONS must be a count") + .expect("TWIGPINE_TEST_RACE_ITERATIONS must be a count") }) .unwrap_or(50); assert!(iterations > 0, "a race run zero times proves nothing"); @@ -3288,14 +3311,14 @@ mod identity_key_storage_tests { "--ignored", "--nocapture", ]) - .env("GITLAWB_TEST_FIXTURE", "identity-key-umask") - .env("GITLAWB_TEST_BASE", base.path()) - .env("GITLAWB_TEST_UMASK", RACE_UMASK) - .env("GITLAWB_TEST_LAYOUT", "concurrent-first-boot") - .env("GITLAWB_TEST_PHASE", "create") - .env("GITLAWB_TEST_BARRIER", barrier.path()) - .env("GITLAWB_TEST_RACE_ID", id.to_string()) - .env("GITLAWB_TEST_RACE_ROLE", *role) + .env("TWIGPINE_TEST_FIXTURE", "identity-key-umask") + .env("TWIGPINE_TEST_BASE", base.path()) + .env("TWIGPINE_TEST_UMASK", RACE_UMASK) + .env("TWIGPINE_TEST_LAYOUT", "concurrent-first-boot") + .env("TWIGPINE_TEST_PHASE", "create") + .env("TWIGPINE_TEST_BARRIER", barrier.path()) + .env("TWIGPINE_TEST_RACE_ID", id.to_string()) + .env("TWIGPINE_TEST_RACE_ROLE", *role) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()); children.push(cmd.spawn().expect("spawn a racing identity boot")); @@ -3447,25 +3470,25 @@ mod identity_key_storage_tests { } } - /// Bare `GITLAWB_KEY=identity.pem` (and `./identity.pem`) must still create + /// Bare `TWIGPINE_KEY=identity.pem` (and `./identity.pem`) must still create /// the identity in the working directory. The p2p key refuses that form on /// purpose; the node identity has always allowed it. #[cfg(unix)] #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=identity-key-bare"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=identity-key-bare"] fn fixture_bare_identity_key_in_cwd() { use std::os::unix::fs::PermissionsExt; - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() != Some("identity-key-bare") { + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("identity-key-bare") { return; } let cwd = std::path::PathBuf::from( - std::env::var("GITLAWB_TEST_BASE").expect("GITLAWB_TEST_BASE"), + std::env::var("TWIGPINE_TEST_BASE").expect("TWIGPINE_TEST_BASE"), ); std::env::set_current_dir(&cwd).expect("chdir into isolated tempdir"); let cwd_mode_before = std::fs::symlink_metadata(".").unwrap().permissions().mode() & 0o7777; - let name = std::env::var("GITLAWB_TEST_KEY_NAME").expect("GITLAWB_TEST_KEY_NAME"); + let name = std::env::var("TWIGPINE_TEST_KEY_NAME").expect("TWIGPINE_TEST_KEY_NAME"); let kp = load_or_create_keypair_at(std::path::Path::new(&name)) .unwrap_or_else(|e| panic!("bare identity path {name:?} must create, got: {e:#}")); assert!( @@ -3511,9 +3534,9 @@ mod identity_key_storage_tests { "--ignored", "--nocapture", ]) - .env("GITLAWB_TEST_FIXTURE", "identity-key-bare") - .env("GITLAWB_TEST_BASE", base.path()) - .env("GITLAWB_TEST_KEY_NAME", name); + .env("TWIGPINE_TEST_FIXTURE", "identity-key-bare") + .env("TWIGPINE_TEST_BASE", base.path()) + .env("TWIGPINE_TEST_KEY_NAME", name); let output = cmd.output().expect("spawn the bare-identity fixture"); let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); @@ -3547,17 +3570,17 @@ mod identity_key_storage_tests { /// cwd must fail, and must not leave a key behind. Do not chmod cwd. #[cfg(unix)] #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=identity-key-bare-writable"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=identity-key-bare-writable"] fn fixture_bare_identity_key_in_writable_cwd_is_refused() { use std::os::unix::fs::PermissionsExt; - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("identity-key-bare-writable") { return; } let cwd = std::path::PathBuf::from( - std::env::var("GITLAWB_TEST_BASE").expect("GITLAWB_TEST_BASE"), + std::env::var("TWIGPINE_TEST_BASE").expect("TWIGPINE_TEST_BASE"), ); std::env::set_current_dir(&cwd).expect("chdir into isolated tempdir"); std::fs::set_permissions(&cwd, std::fs::Permissions::from_mode(0o777)).unwrap(); @@ -3597,8 +3620,8 @@ mod identity_key_storage_tests { "--ignored", "--nocapture", ]) - .env("GITLAWB_TEST_FIXTURE", "identity-key-bare-writable") - .env("GITLAWB_TEST_BASE", base.path()); + .env("TWIGPINE_TEST_FIXTURE", "identity-key-bare-writable") + .env("TWIGPINE_TEST_BASE", base.path()); let output = cmd .output() .expect("spawn the writable-cwd identity fixture"); @@ -3898,15 +3921,15 @@ mod identity_key_storage_tests { /// process. #[cfg(unix)] #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=identity-symlink-relative"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=identity-symlink-relative"] fn fixture_identity_relative_path_with_interior_symlink() { - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("identity-symlink-relative") { return; } let base = std::path::PathBuf::from( - std::env::var("GITLAWB_TEST_BASE").expect("GITLAWB_TEST_BASE"), + std::env::var("TWIGPINE_TEST_BASE").expect("TWIGPINE_TEST_BASE"), ); let evil = plant_interior_symlink_layout(&base); std::env::set_current_dir(&base).expect("chdir into the row's base"); @@ -3949,8 +3972,8 @@ mod identity_key_storage_tests { "--ignored", "--nocapture", ]) - .env("GITLAWB_TEST_FIXTURE", "identity-symlink-relative") - .env("GITLAWB_TEST_BASE", base.path()); + .env("TWIGPINE_TEST_FIXTURE", "identity-symlink-relative") + .env("TWIGPINE_TEST_BASE", base.path()); let output = cmd .output() .expect("spawn the relative-path symlink fixture"); diff --git a/crates/twigpine-node/src/main.rs b/crates/twigpine-node/src/main.rs index a845c99e..f54ac94a 100644 --- a/crates/twigpine-node/src/main.rs +++ b/crates/twigpine-node/src/main.rs @@ -1,7 +1,14 @@ //! Thin binary entry point. All boot logic lives in the library crate //! (`src/lib.rs`) so out-of-crate integration tests can link the same code. +fn main() -> anyhow::Result<()> { + // Before the runtime starts its threads, and before anything reads a + // setting: accept the names settings had before the rename. + twigpine_core::legacy_env::adopt(); + run() +} + #[tokio::main] -async fn main() -> anyhow::Result<()> { +async fn run() -> anyhow::Result<()> { twigpine_node::run().await } diff --git a/crates/twigpine-node/src/metrics.rs b/crates/twigpine-node/src/metrics.rs index 9e8a6b7f..64d780e1 100644 --- a/crates/twigpine-node/src/metrics.rs +++ b/crates/twigpine-node/src/metrics.rs @@ -35,7 +35,7 @@ //! are no-ops until [`init`] has been called, so unit tests and benchmarks //! that don't go through `main()` don't need to do anything special. //! -//! The endpoint is opt-in via `GITLAWB_METRICS_ADDR`; if unset, no listener +//! The endpoint is opt-in via `TWIGPINE_METRICS_ADDR`; if unset, no listener //! is bound and no exposition happens. Increments are atomic and effectively //! free. //! diff --git a/crates/twigpine-node/src/p2p/mod.rs b/crates/twigpine-node/src/p2p/mod.rs index fe457f6c..da4e9630 100644 --- a/crates/twigpine-node/src/p2p/mod.rs +++ b/crates/twigpine-node/src/p2p/mod.rs @@ -1456,7 +1456,7 @@ pub(crate) async fn ingest_ref_update( if unsigned { warn!( did = %event.node_did, - "accepted unsigned gossip ref-update; set GITLAWB_REQUIRE_SIGNED_PEER_WRITES=true after all peers upgrade" + "accepted unsigned gossip ref-update; set TWIGPINE_REQUIRE_SIGNED_PEER_WRITES=true after all peers upgrade" ); } @@ -1981,7 +1981,7 @@ const MAX_P2P_KEY_BYTES: usize = 4096; /// [`load_or_create_p2p_keypair`]): a `~/`-prefixed path must stay beneath the /// resolved home directory. `PathBuf::join` does not guarantee that on its /// own — an absolute right-hand operand *replaces* the left-hand side, so -/// `home.join("/etc/p2p.key")` (from `GITLAWB_P2P_KEY=~//etc/p2p.key`, whose +/// `home.join("/etc/p2p.key")` (from `TWIGPINE_P2P_KEY=~//etc/p2p.key`, whose /// doubled separator leaves a rooted suffix after the `~/` is stripped) is /// `/etc/p2p.key`. On Windows a drive or UNC prefix replaces the base the same /// way even without a root, and `..` walks back out of home lexically. So the @@ -2017,9 +2017,9 @@ fn foreign_ownership_error(what: &str, path: &Path, owner_uid: u32, euid: u32) - owner_uid, euid, if what == "key directory" { - "GITLAWB_P2P_KEY's directory" + "TWIGPINE_P2P_KEY's directory" } else { - "GITLAWB_P2P_KEY" + "TWIGPINE_P2P_KEY" } )) } @@ -2492,7 +2492,7 @@ fn nofollow_component_error(e: std::io::Error, component: &Path) -> std::io::Err /// target while its own key stays untouched on disk. /// /// Resolution only. No component is created here, and an existing one is -/// adopted with NO ownership or mode judgment: `GITLAWB_KEY` is a file path +/// adopted with NO ownership or mode judgment: `TWIGPINE_KEY` is a file path /// rather than a dedicated-directory setting, so its ancestors are allowed to /// be a shared volume or owned by another uid, and the p2p `verify_component` /// predicate deliberately does not apply. The single refusal this adds is a @@ -2786,7 +2786,7 @@ pub(crate) fn path_denotes_a_directory(key_path: &Path, configured_raw: Option<& /// Validate the resolved key path before creating or chmodding anything. /// -/// `configured_raw` is the operator's `GITLAWB_P2P_KEY` string when available. +/// `configured_raw` is the operator's `TWIGPINE_P2P_KEY` string when available. /// A key path that cannot name a securable key file, whatever is on disk. /// /// A distinct type rather than a `String` so the two failure domains cannot be @@ -2813,7 +2813,7 @@ pub(crate) fn validate_p2p_key_config( if names_no_usable_directory(key_path) { return Err(P2pKeyConfigError(format!( - "GITLAWB_P2P_KEY ({display}) must include a directory that does not walk back through \ + "TWIGPINE_P2P_KEY ({display}) must include a directory that does not walk back through \ `..`, such as ./keys/p2p.key or /data/keys/p2p.key: the node will not store its p2p \ identity key in the working directory, where the directory holding it cannot be secured." ))); @@ -2821,14 +2821,14 @@ pub(crate) fn validate_p2p_key_config( if key_parent_is_filesystem_root(key_path) { return Err(P2pKeyConfigError(format!( - "GITLAWB_P2P_KEY ({display}) must not place the key in the filesystem root; use a \ + "TWIGPINE_P2P_KEY ({display}) must not place the key in the filesystem root; use a \ dedicated directory such as /data/keys/p2p.key" ))); } if path_denotes_a_directory(key_path, configured_raw) { return Err(P2pKeyConfigError(format!( - "GITLAWB_P2P_KEY ({display}) must name a key file, not a directory" + "TWIGPINE_P2P_KEY ({display}) must name a key file, not a directory" ))); } @@ -2845,7 +2845,7 @@ pub(crate) fn validate_p2p_key_config( .filter(|n| !n.is_empty()) .ok_or_else(|| { P2pKeyConfigError(format!( - "GITLAWB_P2P_KEY ({display}) must name a key file, not a directory" + "TWIGPINE_P2P_KEY ({display}) must name a key file, not a directory" )) })?; Ok(P2pKeyTarget { @@ -2860,7 +2860,7 @@ pub(crate) fn validate_p2p_key_config( /// This is the enforcement point for the key-storage contract. Rules 1 and 2 /// live in configuration, rules 3–5 here: /// -/// 1. Disabled p2p (`GITLAWB_P2P_PORT=0`) never resolves, inspects, or +/// 1. Disabled p2p (`TWIGPINE_P2P_PORT=0`) never resolves, inspects, or /// mutates key storage at all (`Config::validate` gates on the port). /// 2. A `~/`-relative path is parsed exactly once, and the suffix is proven /// relative before it is joined, so expansion cannot land outside home @@ -2978,7 +2978,7 @@ impl KeyDirHandle { /// Publish into an already-existing directory without creating or chmodding /// it. Identity-key paths use this for cwd, `/`, and any nominated parent /// that already exists, so the p2p key's dedicated-directory contract (pin - /// to 0700) is not imported onto `GITLAWB_KEY`. Write-authority is still + /// to 0700) is not imported onto `TWIGPINE_KEY`. Write-authority is still /// checked: a 0600 key is unprotected if this directory is group/world /// writable, so [`pin::verify_trusted_parent`] runs on the held descriptor /// before the handle is returned. @@ -3230,7 +3230,7 @@ fn describe_unusable_key_dir(dir: &Path, e: std::io::Error) -> anyhow::Error { match e.raw_os_error() { Some(code) if code == libc::ELOOP => { return anyhow::anyhow!( - "GITLAWB_P2P_KEY's directory {} must be a real directory, not a symlink", + "TWIGPINE_P2P_KEY's directory {} must be a real directory, not a symlink", dir.display() ); } @@ -3243,18 +3243,18 @@ fn describe_unusable_key_dir(dir: &Path, e: std::io::Error) -> anyhow::Error { // for. if std::fs::symlink_metadata(dir).is_ok_and(|md| md.is_symlink()) { return anyhow::anyhow!( - "GITLAWB_P2P_KEY's directory {} must be a real directory, not a symlink", + "TWIGPINE_P2P_KEY's directory {} must be a real directory, not a symlink", dir.display() ); } return anyhow::anyhow!( - "GITLAWB_P2P_KEY's directory {} must be a directory, not another file type", + "TWIGPINE_P2P_KEY's directory {} must be a directory, not another file type", dir.display() ); } Some(code) if code == libc::EACCES => { return anyhow::anyhow!( - "GITLAWB_P2P_KEY's directory {} cannot be opened by this node; run \ + "TWIGPINE_P2P_KEY's directory {} cannot be opened by this node; run \ `chmod 700 {}` if it should own it. Check the directory's current mode \ first: two node processes starting at once can produce this transiently, \ in which case the directory is already 0700 and the next start succeeds.", @@ -3268,7 +3268,7 @@ fn describe_unusable_key_dir(dir: &Path, e: std::io::Error) -> anyhow::Error { #[cfg(not(unix))] if e.kind() == std::io::ErrorKind::InvalidInput { return anyhow::anyhow!( - "GITLAWB_P2P_KEY's directory {} must be a real directory, not a symlink \ + "TWIGPINE_P2P_KEY's directory {} must be a real directory, not a symlink \ or another file type", dir.display() ); @@ -3301,7 +3301,7 @@ fn dir_mode_allows_untrusted_replace(mode: u32) -> bool { /// run by hand. Failure to tighten is fatal, since at that point the key cannot /// be protected. /// -/// `~/.gitlawb/identity.pem` lives in this directory too, so this covers both +/// `~/.twigpine/identity.pem` lives in this directory too, so this covers both /// keys. Issue #231 owns the sibling gap in `main.rs`'s own creation path for /// that file; nothing here touches it. #[cfg(unix)] @@ -3597,11 +3597,11 @@ fn identity_parent_step(p: &Path) -> &Path { /// what stops an attacker who can repoint a single interior component from /// redirecting the walk into a tree of their choosing. Ancestors above the /// anchor are still neither judged nor mutated: the resolver applies no -/// ownership or mode predicate, because `GITLAWB_KEY` names a file rather than +/// ownership or mode predicate, because `TWIGPINE_KEY` names a file rather than /// a dedicated directory and its ancestors are allowed to be a shared volume or /// owned by another uid. That is the difference from /// [`verify_and_create_ancestor_chain`], which walks the same way but applies -/// the full `GITLAWB_P2P_KEY` ancestor policy and creates what is missing. +/// the full `TWIGPINE_P2P_KEY` ancestor policy and creates what is missing. /// /// Pass 2 walks back down calling [`pin::create_dir_pinned_at`] per component /// against the descriptor of the one before it, so from the anchor down no @@ -3686,7 +3686,7 @@ fn create_missing_identity_parents( /// Every component below the deepest existing ancestor is created pinned to /// 0700 on one descriptor chain, so a two-deep missing prefix lands at the /// mode this process chose rather than at the ambient umask. A pre-existing -/// ancestor is adopted as-is and never chmodded: `GITLAWB_KEY` is a file path, +/// ancestor is adopted as-is and never chmodded: `TWIGPINE_KEY` is a file path, /// not a dedicated-directory setting. Write-authority is still required on the /// directory each component is created in. Anything this invocation created is /// removed again if the boot fails past it, except a directory that has since @@ -3702,7 +3702,7 @@ pub(crate) fn create_pinned_dir_and_publish(key_path: &Path, bytes: &[u8]) -> Re // A bare filename (`identity.pem` / `./identity.pem`) or a root-adjacent // path (`/identity.pem`) publishes into an already-nominated directory. - // That form is legal for GITLAWB_KEY and illegal for GITLAWB_P2P_KEY; this + // That form is legal for TWIGPINE_KEY and illegal for TWIGPINE_P2P_KEY; this // helper must not chmod cwd or `/` as if they were a nominated key // directory. let parent = key_parent(key_path); @@ -3720,7 +3720,7 @@ pub(crate) fn create_pinned_dir_and_publish(key_path: &Path, bytes: &[u8]) -> Re .file_name() .ok_or_else(|| anyhow::anyhow!("{} names no final directory component", dir.display()))?; - // An existing nominated parent is used as-is. GITLAWB_KEY is a file path, + // An existing nominated parent is used as-is. TWIGPINE_KEY is a file path, // not a dedicated-directory setting, so this must not chmod `/etc` or a // shared 0755 volume. Write-authority still refuses a group/world-writable // parent. A missing parent is created at 0700 below. @@ -5011,15 +5011,15 @@ mod tests { #[cfg(unix)] fn fixture_command_with_env(fixture_test: &str, fixture_name: &str) -> std::process::Command { let mut cmd = fixture_command(fixture_test); - cmd.env("GITLAWB_TEST_FIXTURE", fixture_name); + cmd.env("TWIGPINE_TEST_FIXTURE", fixture_name); cmd } /// Fixture: refuse key paths that name no directory inside an isolated cwd. #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=p2p-key-backstop"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=p2p-key-backstop"] fn fixture_p2p_key_backstop_refuses_no_directory() { - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-backstop") { + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-backstop") { return; } @@ -5106,11 +5106,11 @@ mod tests { /// zero the umask inside the shared test process. #[cfg(unix)] #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=p2p-key-perms"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=p2p-key-perms"] fn fixture_p2p_key_perms_under_zero_umask() { use std::os::unix::fs::PermissionsExt; - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-perms") { + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-perms") { return; } @@ -5164,11 +5164,11 @@ mod tests { /// component at 0700 and verify it. #[cfg(unix)] #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=p2p-key-multilevel"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=p2p-key-multilevel"] fn fixture_p2p_key_multilevel_ancestors_under_zero_umask() { use std::os::unix::fs::PermissionsExt; - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-multilevel") { + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-multilevel") { return; } @@ -5434,19 +5434,19 @@ mod tests { /// inside the shared test process. #[cfg(unix)] #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=p2p-key-umask"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=p2p-key-umask"] fn fixture_p2p_key_umask_lifecycle() { - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-umask") { + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-umask") { return; } let base = std::path::PathBuf::from( - std::env::var("GITLAWB_TEST_BASE").expect("GITLAWB_TEST_BASE"), + std::env::var("TWIGPINE_TEST_BASE").expect("TWIGPINE_TEST_BASE"), ); - let umask_str = std::env::var("GITLAWB_TEST_UMASK").expect("GITLAWB_TEST_UMASK"); + let umask_str = std::env::var("TWIGPINE_TEST_UMASK").expect("TWIGPINE_TEST_UMASK"); let umask_val = u32::from_str_radix(&umask_str, 8).expect("octal umask"); - let layout = std::env::var("GITLAWB_TEST_LAYOUT").expect("GITLAWB_TEST_LAYOUT"); - let phase = std::env::var("GITLAWB_TEST_PHASE").expect("GITLAWB_TEST_PHASE"); + let layout = std::env::var("TWIGPINE_TEST_LAYOUT").expect("TWIGPINE_TEST_LAYOUT"); + let phase = std::env::var("TWIGPINE_TEST_PHASE").expect("TWIGPINE_TEST_PHASE"); // The EACCES rows are meaningless as root, which bypasses mode checks. // Fail loudly rather than skipping: a silent skip here would make the @@ -5577,17 +5577,17 @@ mod tests { /// term alone and watching it go red is the INV-21(i) precondition. #[cfg(unix)] #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=p2p-key-skip-pin"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=p2p-key-skip-pin"] fn fixture_p2p_key_skip_pin_is_caught_by_the_verify() { - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-skip-pin") { + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-skip-pin") { return; } let base = std::path::PathBuf::from( - std::env::var("GITLAWB_TEST_BASE").expect("GITLAWB_TEST_BASE"), + std::env::var("TWIGPINE_TEST_BASE").expect("TWIGPINE_TEST_BASE"), ); - let target = std::env::var("GITLAWB_TEST_TARGET").expect("GITLAWB_TEST_TARGET"); + let target = std::env::var("TWIGPINE_TEST_TARGET").expect("TWIGPINE_TEST_TARGET"); let umask_val = - u32::from_str_radix(&std::env::var("GITLAWB_TEST_UMASK").unwrap(), 8).unwrap(); + u32::from_str_radix(&std::env::var("TWIGPINE_TEST_UMASK").unwrap(), 8).unwrap(); // SAFETY: `umask` only reads and replaces the process-wide value, and // this process exists solely for this probe. @@ -5634,9 +5634,9 @@ mod tests { "p2p::tests::fixture_p2p_key_skip_pin_is_caught_by_the_verify", "p2p-key-skip-pin", ) - .env("GITLAWB_TEST_BASE", base.path()) - .env("GITLAWB_TEST_TARGET", target) - .env("GITLAWB_TEST_UMASK", umask) + .env("TWIGPINE_TEST_BASE", base.path()) + .env("TWIGPINE_TEST_TARGET", target) + .env("TWIGPINE_TEST_UMASK", umask) .output() .expect("spawn the skip-pin fixture"); let stdout = String::from_utf8_lossy(&output.stdout); @@ -5826,10 +5826,10 @@ mod tests { "p2p::tests::fixture_p2p_key_umask_lifecycle", "p2p-key-umask", ) - .env("GITLAWB_TEST_BASE", base) - .env("GITLAWB_TEST_UMASK", umask) - .env("GITLAWB_TEST_LAYOUT", layout) - .env("GITLAWB_TEST_PHASE", phase) + .env("TWIGPINE_TEST_BASE", base) + .env("TWIGPINE_TEST_UMASK", umask) + .env("TWIGPINE_TEST_LAYOUT", layout) + .env("TWIGPINE_TEST_PHASE", phase) .output() .expect("spawn the lifecycle fixture"); let stdout = String::from_utf8_lossy(&output.stdout); @@ -5917,11 +5917,11 @@ mod tests { /// be refused before anything is created. #[cfg(unix)] #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=p2p-key-cwd-writable"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=p2p-key-cwd-writable"] fn fixture_p2p_key_relative_under_writable_cwd_is_refused() { use std::os::unix::fs::PermissionsExt; - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-cwd-writable") { + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-cwd-writable") { return; } @@ -5955,11 +5955,11 @@ mod tests { /// the same PeerId. #[cfg(unix)] #[test] - #[ignore = "self-exec fixture: only runs under GITLAWB_TEST_FIXTURE=p2p-key-cwd-safe"] + #[ignore = "self-exec fixture: only runs under TWIGPINE_TEST_FIXTURE=p2p-key-cwd-safe"] fn fixture_p2p_key_relative_under_safe_cwd_boots() { use std::os::unix::fs::PermissionsExt; - if std::env::var("GITLAWB_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-cwd-safe") { + if std::env::var("TWIGPINE_TEST_FIXTURE").ok().as_deref() != Some("p2p-key-cwd-safe") { return; } @@ -6137,7 +6137,7 @@ mod tests { ("a/../p2p.key", "must include a directory"), ("/data/keys/.", "must name a key file"), ("/data/keys/./.", "must name a key file"), - ("~/.gitlawb/.", "must name a key file"), + ("~/.twigpine/.", "must name a key file"), ] { let err = validate_p2p_key_config(Path::new(raw), Some(raw)) .expect_err("a lexically invalid key path must be refused"); @@ -6600,7 +6600,7 @@ mod tests { /// back out lexically, so those are exactly the rejected classes. #[test] fn tilde_suffix_escapes_home_matches_the_join_invariant() { - let accepted = [".gitlawb/p2p.key", "keys/p2p.key", "./keys/p2p.key"]; + let accepted = [".twigpine/p2p.key", "keys/p2p.key", "./keys/p2p.key"]; for suffix in accepted { assert!( !tilde_suffix_escapes_home(suffix), diff --git a/crates/twigpine-node/src/pinata.rs b/crates/twigpine-node/src/pinata.rs index 0ff86e9f..6090a0e7 100644 --- a/crates/twigpine-node/src/pinata.rs +++ b/crates/twigpine-node/src/pinata.rs @@ -3,7 +3,7 @@ //! After git objects land on the node, this module uploads them to Pinata //! so they are pinned off-node and available via the public IPFS gateway. //! -//! Set `GITLAWB_PINATA_JWT` to enable. Leave empty and every call is a +//! Set `TWIGPINE_PINATA_JWT` to enable. Leave empty and every call is a //! no-op, so nodes without Pinata backing work fine. use anyhow::Result; @@ -12,7 +12,7 @@ use std::time::{Duration, Instant}; /// Pin a single git object's raw bytes on Pinata (v3 API). /// /// - `client`: shared reqwest client -/// - `upload_url`: Pinata v3 upload URL (configured via `GITLAWB_PINATA_UPLOAD_URL`) +/// - `upload_url`: Pinata v3 upload URL (configured via `TWIGPINE_PINATA_UPLOAD_URL`) /// - `jwt`: Pinata bearer JWT; returns `Ok("")` immediately if empty /// - `sha`: git object hash hex (used as the pin name) /// - `data`: raw git object bytes diff --git a/crates/twigpine-node/src/rate_limit.rs b/crates/twigpine-node/src/rate_limit.rs index 742bdc56..c38247f4 100644 --- a/crates/twigpine-node/src/rate_limit.rs +++ b/crates/twigpine-node/src/rate_limit.rs @@ -383,7 +383,7 @@ pub async fn rate_limit_by_did(request: Request, next: Next) -> Response { /// a proxy the operator controls may be believed; a raw client can put any /// value in `Fly-Client-IP` / `X-Forwarded-For`, so trusting them unconditionally /// lets a flooder rotate the header and never fill a bucket. Configured via -/// `GITLAWB_TRUSTED_PROXY`. +/// `TWIGPINE_TRUSTED_PROXY`. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum TrustedProxy { /// No trusted proxy: ignore forwarded headers, key on the socket peer IP. @@ -398,7 +398,7 @@ pub enum TrustedProxy { } impl TrustedProxy { - /// Parse `GITLAWB_TRUSTED_PROXY`. Unknown/empty → `None` (trust nothing). + /// Parse `TWIGPINE_TRUSTED_PROXY`. Unknown/empty → `None` (trust nothing). pub fn from_env_value(s: &str) -> Self { match s.trim().to_ascii_lowercase().as_str() { "fly" | "fly-client-ip" => TrustedProxy::Fly, @@ -487,7 +487,7 @@ pub const RATE_LIMIT_MESSAGE: &str = "rate limit exceeded — try again later"; /// alike). Route-agnostic: the message stays generic (the offending path, when /// logged, is recorded at the call site). /// -/// Carries `X-Gitlawb-Error: rate_limited` and the same JSON shape the ledger's +/// Carries `X-Twigpine-Error: rate_limited` and the same JSON shape the ledger's /// `ledger_rejection` uses, because the brake shares 429 with the ledger's /// `signature_ledger_full` on every route group the write brake covers. Without a /// code the only discriminator between two unrelated conditions is the @@ -500,7 +500,7 @@ pub fn too_many_requests(retry_after: Duration) -> Response { StatusCode::TOO_MANY_REQUESTS, [ ("retry-after", retry_after.as_secs().to_string()), - ("X-Gitlawb-Error", code.to_string()), + ("X-Twigpine-Error", code.to_string()), ], Json(json!({ "error": code, "message": RATE_LIMIT_MESSAGE })), ) @@ -585,7 +585,7 @@ mod tests { /// The brake shares 429 with the spent-signature ledger's /// `signature_ledger_full`, so it has to be told apart by something other /// than the status. It carries the same shape the ledger uses: an - /// `X-Gitlawb-Error` header and a JSON body whose `error` matches it. + /// `X-Twigpine-Error` header and a JSON body whose `error` matches it. #[tokio::test] async fn brake_429_carries_a_machine_readable_code_and_json_body() { let resp = too_many_requests(Duration::from_secs(60)); @@ -598,7 +598,7 @@ mod tests { ); assert_eq!( resp.headers() - .get("x-gitlawb-error") + .get("x-twigpine-error") .and_then(|v| v.to_str().ok()), Some("rate_limited"), "a brake 429 must be distinguishable from a ledger 429 by its code", diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index 614deff8..64c6f56a 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -405,7 +405,7 @@ pub fn build_router(state: AppState) -> Router { auth::optional_signature, )); - // Body limit is raised to GITLAWB_MAX_PACK_BYTES (default 2 GB) for git + // Body limit is raised to TWIGPINE_MAX_PACK_BYTES (default 2 GB) for git // routes only — all other API routes keep axum's default 2 MB cap. // HTTP Signature is enforced on receive-pack (push) — the git-remote-twigpine // helper signs requests with RFC 9421 signatures using the agent's keypair. @@ -804,9 +804,36 @@ pub fn build_router(state: AppState) -> Router { .on_response(DefaultOnResponse::new().level(Level::DEBUG)) .on_failure(DefaultOnFailure::new().level(Level::ERROR)), ) + // Outermost, so it sees every response, including the ones the layers + // above build themselves (auth, rate limits, body limits). + .layer(middleware::from_fn(send_legacy_header_names)) .with_state(state) } +/// Send each renamed response header under its old name too. +/// +/// Handlers set only the current name. A client written before the rename +/// reads the old one, and for the error header that read is what turns a +/// refusal into an error instead of something that looks like success. +pub(crate) async fn send_legacy_header_names( + request: axum::extract::Request, + next: middleware::Next, +) -> axum::response::Response { + let mut response = next.run(request).await; + for (name, legacy) in twigpine_core::legacy_headers::RESPONSE_PAIRS { + let values: Vec<_> = response.headers().get_all(name).iter().cloned().collect(); + if values.is_empty() { + continue; + } + let legacy = axum::http::HeaderName::from_static(legacy); + response.headers_mut().remove(&legacy); + for value in values { + response.headers_mut().append(legacy.clone(), value); + } + } + response +} + async fn health() -> Json { Json(json!({ "status": "ok" })) } @@ -834,7 +861,7 @@ async fn ready(State(state): State) -> axum::response::Response { async fn node_info(State(state): State) -> Json { let p2p_peer_id = state.p2p.as_ref().map(|h| h.local_peer_id.to_string()); let mut body = json!({ - "name": "gitlawb-node", + "name": "twigpine-node", "version": env!("CARGO_PKG_VERSION"), "did": state.node_did.to_string(), "network": "alpha", @@ -1271,10 +1298,82 @@ mod tests { use axum::body::Body; use axum::http::{Request, StatusCode}; + + /// Every response carries the renamed headers under their old names too, + /// with the same values, and an old-name header a handler might still set + /// cannot disagree with the current one. + #[tokio::test] + async fn renamed_response_headers_also_go_out_under_their_old_names() { + let app = Router::new() + .route( + "/refused", + get(|| async { + ( + StatusCode::CONFLICT, + [ + ("X-Twigpine-Error", "signature_replayed"), + ("X-Gitlawb-Error", "stale"), + ], + ) + }), + ) + .route("/plain", get(|| async { StatusCode::OK })) + .layer(middleware::from_fn(send_legacy_header_names)); + + let refused = app + .clone() + .oneshot(Request::get("/refused").body(Body::empty()).unwrap()) + .await + .unwrap(); + let h = refused.headers(); + assert_eq!(h.get("x-twigpine-error").unwrap(), "signature_replayed"); + let old: Vec<_> = h.get_all("x-gitlawb-error").iter().collect(); + assert_eq!(old, ["signature_replayed"]); + + let plain = app + .oneshot(Request::get("/plain").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert!(plain.headers().get("x-gitlawb-error").is_none()); + assert!(plain.headers().get("x-twigpine-error").is_none()); + } use tower::ServiceExt; use crate::db::RepoRecord; + /// The real router, not a hand-built one: a refusal carries its code under + /// the error header's current name and under the name from before the + /// rename. Removing the layer from `build_router` fails this. + #[sqlx::test] + async fn a_refusal_through_build_router_carries_both_error_header_names(pool: PgPool) { + let state = test_state(pool).await; + let router = build_router(state); + // An unsigned write: refused by the auth layer before any handler runs. + let resp = router + .oneshot( + Request::post("/api/v1/bounties/some-id/claim") + .header("content-type", "application/json") + .body(Body::from("{}")) + .unwrap(), + ) + .await + .unwrap(); + assert!(resp.status().is_client_error(), "{}", resp.status()); + let code = resp + .headers() + .get("x-twigpine-error") + .and_then(|v| v.to_str().ok()) + .map(str::to_owned) + .expect("the refusal names its reason in x-twigpine-error"); + assert_eq!( + resp.headers() + .get("x-gitlawb-error") + .and_then(|v| v.to_str().ok()), + Some(code.as_str()), + "the old header name must carry the same code" + ); + } + /// Regression: anonymous callers must not see the pin/anchor index (#121, #134). #[sqlx::test] async fn unsigned_get_pins_and_anchors_is_401_through_build_router(pool: PgPool) { diff --git a/crates/twigpine-node/src/state.rs b/crates/twigpine-node/src/state.rs index 2d077674..56fd7b91 100644 --- a/crates/twigpine-node/src/state.rs +++ b/crates/twigpine-node/src/state.rs @@ -105,7 +105,7 @@ pub struct AppState { /// (its own budget, per the `sync_trigger`/`peer_write` precedent) so a /// write flood cannot drain the creation budget and vice versa. Per-DID is /// deliberately NOT paired here: a DID farm never trips it, and busy - /// legitimate agents would false-positive. `GITLAWB_WRITE_RATE_LIMIT` + /// legitimate agents would false-positive. `TWIGPINE_WRITE_RATE_LIMIT` /// overrides the default, 0 disables. Keyed by `push_limiter_trust`. pub write_rate_limiter: RateLimiter, /// Per-client-IP rate limiter for git-receive-pack. Per-DID limits cannot @@ -118,7 +118,7 @@ pub struct AppState { pub close_issue_rate_limiter: RateLimiter, /// Per-client-IP ROUTE brake for `GET /ipfs/{cid}`: charged ONCE per request by the /// `rate_limit_by_ip` middleware (server.rs), never inside the handler. It bounds - /// request RATE (the "requests per hour" contract of `GITLAWB_IPFS_RATE_LIMIT`) on + /// request RATE (the "requests per hour" contract of `TWIGPINE_IPFS_RATE_LIMIT`) on /// the non-farmable source IP, so an anonymous flood of the public route is capped. /// The per-probe/per-walk WORK accounting the resolver does WITHIN a request draws /// from the SEPARATE `ipfs_work_rate_limiter` below — the two cannot share one bucket @@ -158,7 +158,7 @@ pub struct AppState { pub ipfs_legacy_scan_page_rows: usize, /// Per-request ceiling on how many repo ROWS the CID resolver's legacy scan may /// fetch (default `api::ipfs::MAX_LEGACY_SCAN_ROWS_PER_REQUEST`, operator-tunable via - /// `GITLAWB_IPFS_MAX_LEGACY_SCAN_ROWS`). `ipfs_max_legacy_probes` bounds the PROBE + /// `TWIGPINE_IPFS_MAX_LEGACY_SCAN_ROWS`). `ipfs_max_legacy_probes` bounds the PROBE /// fan-out but only starts counting once a probe runs, and quarantine plus a /// root-scope visibility deny both return before a probe or a visit is spent, so an /// all-denying inventory paged the whole repo table at zero probes (#173 round 13, F2). @@ -214,7 +214,7 @@ pub struct AppState { /// A field for the same test-seam reason as the sibling caps. pub ipfs_max_served_object_bytes: u64, /// Which forwarded header (if any) the edge is trusted to set, for - /// resolving the push limiter's client-IP key. See `GITLAWB_TRUSTED_PROXY`. + /// resolving the push limiter's client-IP key. See `TWIGPINE_TRUSTED_PROXY`. /// Node-wide; also keys the two peer-sync limiters below. pub push_limiter_trust: crate::rate_limit::TrustedProxy, /// Per-client-IP limiter for `POST /api/v1/sync/trigger` (tight). The route @@ -429,7 +429,7 @@ impl AppState { self.federated_rate_limiter.cleanup().await; } - /// Legacy-probe budget wired from the `GITLAWB_IPFS_MAX_LEGACY_PROBES` operator + /// Legacy-probe budget wired from the `TWIGPINE_IPFS_MAX_LEGACY_PROBES` operator /// knob. The knob seeds `ipfs_max_legacy_probes` at construction so it controls the /// per-request legacy (NULL-provenance) probe fan-out it advertises. It deliberately /// does NOT feed the history-walk ceiling: that is governed by @@ -441,7 +441,7 @@ impl AppState { config.ipfs_max_legacy_probes as u32 } - /// Legacy-scan ROW budget wired from the `GITLAWB_IPFS_MAX_LEGACY_SCAN_ROWS` knob, + /// Legacy-scan ROW budget wired from the `TWIGPINE_IPFS_MAX_LEGACY_SCAN_ROWS` knob, /// the same helper shape as the probe budget above so the knob cannot become a /// silent no-op if a struct literal drifts back to the bare constant. pub(crate) fn ipfs_legacy_scan_row_budget(config: &crate::config::Config) -> usize { @@ -521,7 +521,7 @@ impl AppState { /// resolution per window, the provenance phase's walks plus a full legacy search /// (probes plus page tolls), so a single default-config resolution cannot /// self-throttle part-way and recreate the admit-then-429 for a legitimate caller. - /// `GITLAWB_IPFS_RATE_LIMIT=0` + /// `TWIGPINE_IPFS_RATE_LIMIT=0` /// disables the route brake and this derived bucket alike (a 0-capacity limiter admits /// everything). /// @@ -831,7 +831,7 @@ pub struct RepoWriteLeases { // context, never across an await — the semaphore wait happens OUTSIDE this lock. repos: Arc>>, /// Most handlers allowed to be PARKED on one repo's lease at once - /// (`GITLAWB_REPO_LEASE_MAX_WAITERS`). Past it `acquire` sheds instead of queueing. + /// (`TWIGPINE_REPO_LEASE_MAX_WAITERS`). Past it `acquire` sheds instead of queueing. max_waiters: usize, } diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index a4e478bf..f1cb7e80 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -1,6 +1,6 @@ //! Multi-node repo sync worker. //! -//! When `GITLAWB_AUTO_SYNC=true`, this background task polls the `sync_queue` +//! When `TWIGPINE_AUTO_SYNC=true`, this background task polls the `sync_queue` //! table and mirrors repos from peer nodes after receiving Gossipsub ref-update //! events. Each sync item represents one ref update that arrived from a peer. //! diff --git a/crates/twigpine-node/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index 3873a797..15f44283 100644 --- a/crates/twigpine-node/src/test_support.rs +++ b/crates/twigpine-node/src/test_support.rs @@ -35,7 +35,7 @@ mod git_shim; /// Runs the schema migrations first, because the per-test database starts empty. /// /// **The config here is parsed from the process environment.** `Config` sources 47 -/// fields from `GITLAWB_*` variables, so a developer or CI environment that sets one +/// fields from `TWIGPINE_*` variables, so a developer or CI environment that sets one /// silently changes what this state does. Never assert a behaviour that a config /// field controls on top of this state — use [`test_state_with`] and set the field, /// so the test states the configuration it is about instead of inheriting it. @@ -6145,7 +6145,7 @@ mod tests { /// The gate's own unit tests pass `enforce` as a literal and never exercise the /// handler, so this is what proves the flag is actually consulted on the request /// path. It sets the field EXPLICITLY rather than leaning on the default: on a - /// host exporting `GITLAWB_ENFORCE_OWNER_PUSH=false` — which is exactly what the + /// host exporting `TWIGPINE_ENFORCE_OWNER_PUSH=false` — which is exactly what the /// rolling-upgrade guidance tells operators to set — an ambient config would /// build a disabled state, let the push through to git, and fail this test for a /// reason that has nothing to do with the code under test. @@ -16064,7 +16064,7 @@ mod tests { ); } - /// T2b (R5, KTD5): the `GITLAWB_IPFS_MAX_REPOS_WALKED` knob drives the legacy-probe + /// T2b (R5, KTD5): the `TWIGPINE_IPFS_MAX_REPOS_WALKED` knob drives the legacy-probe /// budget end to end. With the knob at 1 (fed through the same production helper the /// state seeding uses) and two candidate repos that miss, the first repo spends the /// single probe and the second is skipped at the cap → truncated → 503. If the knob @@ -22392,7 +22392,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::CONFLICT); assert_eq!( resp.headers() - .get("x-gitlawb-error") + .get("x-twigpine-error") .and_then(|v| v.to_str().ok()), Some("signature_replayed"), "the 409 must be told apart by header, not only by body" @@ -22477,7 +22477,7 @@ mod tests { ); assert_eq!( resp.headers() - .get("x-gitlawb-error") + .get("x-twigpine-error") .and_then(|v| v.to_str().ok()), Some("signature_ledger_full") ); @@ -22599,7 +22599,7 @@ mod tests { assert_eq!( retry .headers() - .get("x-gitlawb-error") + .get("x-twigpine-error") .and_then(|v| v.to_str().ok()), None, "the retry must not be rejected by the ledger" @@ -22701,7 +22701,7 @@ mod tests { ); assert_eq!( resp.headers() - .get("x-gitlawb-error") + .get("x-twigpine-error") .and_then(|v| v.to_str().ok()), Some("signature_nonce_required"), "the denial must be distinguishable by header from every other ledger rejection" @@ -22824,7 +22824,7 @@ mod tests { ); assert_eq!( resp.headers() - .get("x-gitlawb-error") + .get("x-twigpine-error") .and_then(|v| v.to_str().ok()), Some("signature_nonce_too_short"), "nonce={nonce:?} must be told apart from a nonce-less signer by header" @@ -24472,7 +24472,7 @@ mod tests { /// Scenario 1, the regression test for the probe that found this: an UNSIGNED /// POST to `/{owner}/{repo}/git-receive-pack` with a body far larger than the - /// configured `GITLAWB_MAX_PACK_BYTES`. Before the fix this drained all 4 MiB + /// configured `TWIGPINE_MAX_PACK_BYTES`. Before the fix this drained all 4 MiB /// into memory and then returned 401 (no DID, no signature, no repo needed). #[tokio::test] async fn unsigned_oversize_push_is_not_drained_into_memory() { diff --git a/crates/twigpine-node/src/webhook_secret.rs b/crates/twigpine-node/src/webhook_secret.rs index 27ddce6e..d3c782bd 100644 --- a/crates/twigpine-node/src/webhook_secret.rs +++ b/crates/twigpine-node/src/webhook_secret.rs @@ -2,7 +2,7 @@ //! //! Webhook secrets are signing keys: whoever holds one can forge delivery //! payloads to the receiver the hook points at. They are persisted in the -//! `webhooks.secret` column and used to compute the `X-Gitlawb-Signature-256` +//! `webhooks.secret` column and used to compute the `X-Twigpine-Signature-256` //! header on each delivery. That secret needs two properties: //! //! * It must never reach a log line or an API response. [`WebhookSecret`] diff --git a/crates/twigpine-node/src/webhooks.rs b/crates/twigpine-node/src/webhooks.rs index d235913f..13a6e155 100644 --- a/crates/twigpine-node/src/webhooks.rs +++ b/crates/twigpine-node/src/webhooks.rs @@ -9,9 +9,9 @@ //! //! Payload headers: //! Content-Type: application/json -//! X-Gitlawb-Event: -//! X-Gitlawb-Delivery: -//! X-Gitlawb-Signature-256: sha256= (only if secret set) +//! X-Twigpine-Event: +//! X-Twigpine-Delivery: +//! X-Twigpine-Signature-256: sha256= (only if secret set) use std::sync::Arc; @@ -19,6 +19,7 @@ use hmac::{Hmac, Mac}; use sha2::Sha256; use crate::db::Db; +use twigpine_core::legacy_headers; type HmacSha256 = Hmac; @@ -307,12 +308,12 @@ async fn fire_event_async_occurrence( let mut req = client .post(&hook.url) .header("Content-Type", "application/json") - .header("X-Gitlawb-Event", &event_name) - .header("X-Gitlawb-Delivery", &delivery_id) .body(bytes); - - if let Some(sig) = signature { - req = req.header("X-Gitlawb-Signature-256", sig); + // Every header goes out under its current name and the name it had + // before the rename: receivers verify the signature header by + // name, and they are not ours to update. + for (name, value) in delivery_headers(&event_name, &delivery_id, signature.as_deref()) { + req = req.header(name, value); } match req.send().await { @@ -348,9 +349,51 @@ async fn fire_event_async_occurrence( } } +/// The headers one delivery carries: each under its current name and under +/// the name it had before the rename, with the same value. The signature pair +/// is present only when the hook has a secret. +fn delivery_headers<'a>( + event: &'a str, + delivery_id: &'a str, + signature: Option<&'a str>, +) -> Vec<(&'static str, &'a str)> { + let mut headers = Vec::with_capacity(6); + for (pair, value) in [ + (legacy_headers::WEBHOOK_EVENT, Some(event)), + (legacy_headers::WEBHOOK_DELIVERY, Some(delivery_id)), + (legacy_headers::WEBHOOK_SIGNATURE, signature), + ] { + if let Some(value) = value { + headers.push((pair.0, value)); + headers.push((pair.1, value)); + } + } + headers +} + #[cfg(test)] mod tests { use super::*; + + #[test] + fn a_delivery_carries_every_header_under_both_names() { + let signed = delivery_headers("push", "d-1", Some("sha256=abc")); + assert_eq!( + signed, + vec![ + ("X-Twigpine-Event", "push"), + ("X-Gitlawb-Event", "push"), + ("X-Twigpine-Delivery", "d-1"), + ("X-Gitlawb-Delivery", "d-1"), + ("X-Twigpine-Signature-256", "sha256=abc"), + ("X-Gitlawb-Signature-256", "sha256=abc"), + ] + ); + // No secret: no signature header under either name. + let unsigned = delivery_headers("push", "d-1", None); + assert_eq!(unsigned.len(), 4); + assert!(unsigned.iter().all(|(name, _)| !name.contains("Signature"))); + } use rand::Rng; fn key() -> [u8; 32] { diff --git a/crates/twigpine-node/tests/inv22_gates.rs b/crates/twigpine-node/tests/inv22_gates.rs index a8bd889d..7a2f4694 100644 --- a/crates/twigpine-node/tests/inv22_gates.rs +++ b/crates/twigpine-node/tests/inv22_gates.rs @@ -306,7 +306,7 @@ fn f6_ipfs_metadata_queries_are_deadline_wrapped() { "F6 gate missing: occurrence {n} of `{call}` (of {occurrences}) is not \ wrapped in tokio::time::timeout(...) clamped to the remaining request \ budget. An unwrapped await pins the held walk permit for the whole DB \ - stall, past GITLAWB_IPFS_REQUEST_BUDGET_SECS." + stall, past TWIGPINE_IPFS_REQUEST_BUDGET_SECS." ); } } diff --git a/crates/twigpine-node/tests/owner_push_default_docs.rs b/crates/twigpine-node/tests/owner_push_default_docs.rs index 836e2293..fd358c9c 100644 --- a/crates/twigpine-node/tests/owner_push_default_docs.rs +++ b/crates/twigpine-node/tests/owner_push_default_docs.rs @@ -1,4 +1,4 @@ -//! #26 Split PR 4 — `GITLAWB_ENFORCE_OWNER_PUSH` default is consistent across surfaces. +//! #26 Split PR 4 — `TWIGPINE_ENFORCE_OWNER_PUSH` default is consistent across surfaces. //! //! Reviewer 2 (2026-08-28) closed PR #224 with a P2 finding: SECURITY.md and //! README.md both stated the default was `false`, while `Config::enforce_owner_push` @@ -15,7 +15,7 @@ //! 1. `SECURITY.md` says the default is `true`. //! 2. `README.md` says the default is `true` in the known-limitations prose. //! 3. `README.md` says the default is `true` in the env-var table row. -//! 4. `.env.example` sets `GITLAWB_ENFORCE_OWNER_PUSH=true`. +//! 4. `.env.example` sets `TWIGPINE_ENFORCE_OWNER_PUSH=true`. //! //! The runtime declared default (`Config::enforce_owner_push`'s //! `default_value_t = true`) is protected by the @@ -42,7 +42,7 @@ fn read(rel: &str) -> String { std::fs::read_to_string(&p).unwrap_or_else(|e| panic!("read {}: {e}", p.display())) } -/// Pin the prose mentions of `GITLAWB_ENFORCE_OWNER_PUSH` so a future doc +/// Pin the prose mentions of `TWIGPINE_ENFORCE_OWNER_PUSH` so a future doc /// edit cannot reintroduce the "defaults to false" wording the reviewer /// flagged. The wording in the test is what the docs MUST say about the /// default; absence of any prose mention is also a fail because operators @@ -76,10 +76,10 @@ fn readme_known_limitations_states_owner_push_default_is_true() { // the claim, not a substring of unrelated text. let line = limitations .lines() - .find(|l| l.contains("GITLAWB_ENFORCE_OWNER_PUSH")) + .find(|l| l.contains("TWIGPINE_ENFORCE_OWNER_PUSH")) .unwrap_or_else(|| { panic!( - "README.md Known limitations must mention GITLAWB_ENFORCE_OWNER_PUSH.\n\ + "README.md Known limitations must mention TWIGPINE_ENFORCE_OWNER_PUSH.\n\ Got:\n{limitations}" ) }); @@ -101,19 +101,19 @@ fn readme_env_var_table_states_owner_push_default_is_true() { let readme = read("README.md"); let line = readme .lines() - .find(|l| l.contains("GITLAWB_ENFORCE_OWNER_PUSH") && l.contains("|")) + .find(|l| l.contains("TWIGPINE_ENFORCE_OWNER_PUSH") && l.contains("|")) .unwrap_or_else(|| { - panic!("README.md is missing the env-var-table row for GITLAWB_ENFORCE_OWNER_PUSH") + panic!("README.md is missing the env-var-table row for TWIGPINE_ENFORCE_OWNER_PUSH") }); assert!( line.contains("Defaults to `true`") || line.contains("defaults to `true`"), - "README env-var-table row for GITLAWB_ENFORCE_OWNER_PUSH must state the default is true. \ + "README env-var-table row for TWIGPINE_ENFORCE_OWNER_PUSH must state the default is true. \ Found:\n{line}" ); assert!( !section_claims_default_is_false(line), - "README env-var-table row for GITLAWB_ENFORCE_OWNER_PUSH must not claim the default is false. \ + "README env-var-table row for TWIGPINE_ENFORCE_OWNER_PUSH must not claim the default is false. \ Found:\n{line}" ); } @@ -123,12 +123,12 @@ fn env_example_sets_owner_push_true() { let env = read(".env.example"); let line = env .lines() - .find(|l| l.trim_start().starts_with("GITLAWB_ENFORCE_OWNER_PUSH")) - .unwrap_or_else(|| panic!(".env.example is missing GITLAWB_ENFORCE_OWNER_PUSH")); + .find(|l| l.trim_start().starts_with("TWIGPINE_ENFORCE_OWNER_PUSH")) + .unwrap_or_else(|| panic!(".env.example is missing TWIGPINE_ENFORCE_OWNER_PUSH")); assert!( line.contains("=true"), - ".env.example GITLAWB_ENFORCE_OWNER_PUSH must be set to true. Found:\n{line}" + ".env.example TWIGPINE_ENFORCE_OWNER_PUSH must be set to true. Found:\n{line}" ); } diff --git a/crates/twigpine-node/tests/p2p_key_startup_policy.rs b/crates/twigpine-node/tests/p2p_key_startup_policy.rs index 04274bb8..f7f7e154 100644 --- a/crates/twigpine-node/tests/p2p_key_startup_policy.rs +++ b/crates/twigpine-node/tests/p2p_key_startup_policy.rs @@ -107,7 +107,7 @@ impl Row { // harness set up. std::fs::create_dir_all(home.path().join("repos")).expect("repos dir"); // The p2p key tree lives in its own subdirectory so the no-mutation - // assertions can watch exactly it. HOME also holds `.gitlawb`, which + // assertions can watch exactly it. HOME also holds `.twigpine`, which // the node creates for its NODE identity on every start; measuring the // whole home would read that legitimate write as a p2p storage // mutation. @@ -140,16 +140,16 @@ impl Row { // fixture, not incidental setup. .env("RUST_LOG", "info") .env("HOME", self.home.path()) - .env("GITLAWB_REPOS_DIR", &repos) - .env("GITLAWB_HOST", "127.0.0.1") + .env("TWIGPINE_REPOS_DIR", &repos) + .env("TWIGPINE_HOST", "127.0.0.1") // Ephemeral: the real port is read back from the ready log. - .env("GITLAWB_PORT", "0") + .env("TWIGPINE_PORT", "0") // A closed port, so the node stays on the degraded path for the // whole row instead of ever reaching a database. .env("DATABASE_URL", "postgres://127.0.0.1:1/nonexistent") - .env("GITLAWB_P2P_PORT", p2p_port) - .env("GITLAWB_P2P_KEY", p2p_key) - .env("GITLAWB_METRICS_ADDR", "") + .env("TWIGPINE_P2P_PORT", p2p_port) + .env("TWIGPINE_P2P_KEY", p2p_key) + .env("TWIGPINE_METRICS_ADDR", "") .current_dir(cwd) .stdout(Stdio::piped()) .stderr(Stdio::piped()); @@ -512,7 +512,7 @@ fn terminal_dot_key_path_is_fatal_and_does_not_mutate() { } } -/// GITLAWB_KEY has the same Path-retarget hole as GITLAWB_P2P_KEY: a terminal +/// TWIGPINE_KEY has the same Path-retarget hole as TWIGPINE_P2P_KEY: a terminal /// `.` would publish a file named `keys` under `data`. Fatal before bind, and /// the parent tree is unchanged. p2p is off so it cannot chmod a shared dir. #[test] @@ -523,19 +523,19 @@ fn identity_terminal_dot_is_fatal_and_does_not_mutate() { std::fs::set_permissions(&data, std::fs::Permissions::from_mode(0o755)).unwrap(); let key = format!("{}/keys/.", data.display()); let cwd = row.home.path().to_path_buf(); - let mut child = row.spawn_env("p2p.key", "0", &cwd, &[("GITLAWB_KEY", key.as_str())]); + let mut child = row.spawn_env("p2p.key", "0", &cwd, &[("TWIGPINE_KEY", key.as_str())]); let (status, err) = wait_for_exit(&mut child); assert!( !status.success(), - "GITLAWB_KEY={key:?} must exit non-zero\n--- stderr ---\n{err}" + "TWIGPINE_KEY={key:?} must exit non-zero\n--- stderr ---\n{err}" ); assert!( err.contains("invalid configuration"), - "GITLAWB_KEY={key:?} must fail as invalid configuration\n--- stderr ---\n{err}" + "TWIGPINE_KEY={key:?} must fail as invalid configuration\n--- stderr ---\n{err}" ); assert!( !err.contains("binding HTTP listener"), - "GITLAWB_KEY={key:?} must be refused BEFORE the listener binds\n--- stderr ---\n{err}" + "TWIGPINE_KEY={key:?} must be refused BEFORE the listener binds\n--- stderr ---\n{err}" ); let mode = std::fs::metadata(&data).unwrap().permissions().mode() & 0o7777; assert_eq!(mode, 0o755, "rejection must not chmod the parent"); @@ -546,7 +546,7 @@ fn identity_terminal_dot_is_fatal_and_does_not_mutate() { } /// An existing 0755 identity parent is usable and must not be chmodded. p2p is -/// off so a default `~/.gitlawb/p2p.key` cannot tighten the same directory. +/// off so a default `~/.twigpine/p2p.key` cannot tighten the same directory. #[test] fn identity_existing_0755_parent_is_not_chmodded_on_boot() { let row = Row::new(); @@ -559,7 +559,7 @@ fn identity_existing_0755_parent_is_not_chmodded_on_boot() { "p2p.key", "0", &cwd, - &[("GITLAWB_KEY", key.to_str().unwrap())], + &[("TWIGPINE_KEY", key.to_str().unwrap())], ); let (found, log) = read_until(&mut child, "degraded HTTP server ready"); assert!( @@ -593,7 +593,7 @@ fn identity_writable_parent_is_fatal_and_unchanged() { "p2p.key", "0", &cwd, - &[("GITLAWB_KEY", key.to_str().unwrap())], + &[("TWIGPINE_KEY", key.to_str().unwrap())], ); let (status, err) = wait_for_exit(&mut child); assert!( diff --git a/docker-compose.yml b/docker-compose.yml index 9cd5064b..516aebfc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,14 @@ # Run a Twigpine node + Postgres locally. For on-chain PoS operation, supply # the operator key + contract addresses via a .env file or shell environment. +# Settings are TWIGPINE_*. A .env written before the rename, with GITLAWB_* +# names, still works: each value below falls back to the old name. +# +# An override file is different. A GITLAWB_* entry under `environment:` in +# docker-compose.override.yml no longer replaces the entry below, because the +# two now have different names, and the node uses the TWIGPINE_* one. Rename +# such entries to TWIGPINE_*. The node logs a warning naming each setting it +# was given under both names with different values. services: postgres: image: postgres:16-alpine @@ -31,36 +39,36 @@ services: postgres: condition: service_healthy ports: - - "${GITLAWB_PORT:-7545}:${GITLAWB_PORT:-7545}" # HTTP API + git smart-HTTP - - "${GITLAWB_P2P_PORT:-7546}:${GITLAWB_P2P_PORT:-7546}/udp" # libp2p QUIC + - "${TWIGPINE_PORT:-${GITLAWB_PORT:-7545}}:${TWIGPINE_PORT:-${GITLAWB_PORT:-7545}}" # HTTP API + git smart-HTTP + - "${TWIGPINE_P2P_PORT:-${GITLAWB_P2P_PORT:-7546}}:${TWIGPINE_P2P_PORT:-${GITLAWB_P2P_PORT:-7546}}/udp" # libp2p QUIC volumes: - gitlawb-data:/data environment: DATABASE_URL: postgresql://gitlawb:${POSTGRES_PASSWORD:-changeme}@postgres:5432/gitlawb - GITLAWB_HOST: 0.0.0.0 - GITLAWB_PORT: ${GITLAWB_PORT:-7545} - GITLAWB_PUBLIC_URL: ${GITLAWB_PUBLIC_URL:-http://localhost:7545} - GITLAWB_P2P_PORT: ${GITLAWB_P2P_PORT:-7546} - GITLAWB_BOOTSTRAP_PEERS: ${GITLAWB_BOOTSTRAP_PEERS:-} - GITLAWB_BOOTSTRAP_DISABLE_SEEDS: ${GITLAWB_BOOTSTRAP_DISABLE_SEEDS:-false} - GITLAWB_REQUIRE_SIGNED_PEER_WRITES: ${GITLAWB_REQUIRE_SIGNED_PEER_WRITES:-false} + TWIGPINE_HOST: 0.0.0.0 + TWIGPINE_PORT: ${TWIGPINE_PORT:-${GITLAWB_PORT:-7545}} + TWIGPINE_PUBLIC_URL: ${TWIGPINE_PUBLIC_URL:-${GITLAWB_PUBLIC_URL:-http://localhost:7545}} + TWIGPINE_P2P_PORT: ${TWIGPINE_P2P_PORT:-${GITLAWB_P2P_PORT:-7546}} + TWIGPINE_BOOTSTRAP_PEERS: ${TWIGPINE_BOOTSTRAP_PEERS:-${GITLAWB_BOOTSTRAP_PEERS:-}} + TWIGPINE_BOOTSTRAP_DISABLE_SEEDS: ${TWIGPINE_BOOTSTRAP_DISABLE_SEEDS:-${GITLAWB_BOOTSTRAP_DISABLE_SEEDS:-false}} + TWIGPINE_REQUIRE_SIGNED_PEER_WRITES: ${TWIGPINE_REQUIRE_SIGNED_PEER_WRITES:-${GITLAWB_REQUIRE_SIGNED_PEER_WRITES:-false}} # Owner-only push. The default matches the node's own, so the container path # behaves like a source build; forwarding it is what makes the documented # rolling-upgrade opt-out reachable for an operator running compose. - GITLAWB_ENFORCE_OWNER_PUSH: ${GITLAWB_ENFORCE_OWNER_PUSH:-true} - GITLAWB_P2P_BOOTSTRAP: ${GITLAWB_P2P_BOOTSTRAP:-} - GITLAWB_PUBLIC_READ: ${GITLAWB_PUBLIC_READ:-true} - GITLAWB_MAX_PACK_BYTES: ${GITLAWB_MAX_PACK_BYTES:-2147483648} + TWIGPINE_ENFORCE_OWNER_PUSH: ${TWIGPINE_ENFORCE_OWNER_PUSH:-${GITLAWB_ENFORCE_OWNER_PUSH:-true}} + TWIGPINE_P2P_BOOTSTRAP: ${TWIGPINE_P2P_BOOTSTRAP:-${GITLAWB_P2P_BOOTSTRAP:-}} + TWIGPINE_PUBLIC_READ: ${TWIGPINE_PUBLIC_READ:-${GITLAWB_PUBLIC_READ:-true}} + TWIGPINE_MAX_PACK_BYTES: ${TWIGPINE_MAX_PACK_BYTES:-${GITLAWB_MAX_PACK_BYTES:-2147483648}} # Sync - GITLAWB_AUTO_SYNC: ${GITLAWB_AUTO_SYNC:-false} + TWIGPINE_AUTO_SYNC: ${TWIGPINE_AUTO_SYNC:-${GITLAWB_AUTO_SYNC:-false}} # On-chain PoS (optional — leave unset for local/dev) - GITLAWB_CHAIN_RPC_URL: ${GITLAWB_CHAIN_RPC_URL:-} - GITLAWB_CONTRACT_NODE_STAKING: ${GITLAWB_CONTRACT_NODE_STAKING:-} - GITLAWB_OPERATOR_PRIVATE_KEY: ${GITLAWB_OPERATOR_PRIVATE_KEY:-} - GITLAWB_OPERATOR_STRICT_MODE: ${GITLAWB_OPERATOR_STRICT_MODE:-false} - GITLAWB_HEARTBEAT_INTERVAL_HOURS: ${GITLAWB_HEARTBEAT_INTERVAL_HOURS:-20} + TWIGPINE_CHAIN_RPC_URL: ${TWIGPINE_CHAIN_RPC_URL:-${GITLAWB_CHAIN_RPC_URL:-}} + TWIGPINE_CONTRACT_NODE_STAKING: ${TWIGPINE_CONTRACT_NODE_STAKING:-${GITLAWB_CONTRACT_NODE_STAKING:-}} + TWIGPINE_OPERATOR_PRIVATE_KEY: ${TWIGPINE_OPERATOR_PRIVATE_KEY:-${GITLAWB_OPERATOR_PRIVATE_KEY:-}} + TWIGPINE_OPERATOR_STRICT_MODE: ${TWIGPINE_OPERATOR_STRICT_MODE:-${GITLAWB_OPERATOR_STRICT_MODE:-false}} + TWIGPINE_HEARTBEAT_INTERVAL_HOURS: ${TWIGPINE_HEARTBEAT_INTERVAL_HOURS:-${GITLAWB_HEARTBEAT_INTERVAL_HOURS:-20}} # Optional shared storage (leave unset to use local disk only) - GITLAWB_TIGRIS_BUCKET: ${GITLAWB_TIGRIS_BUCKET:-} + TWIGPINE_TIGRIS_BUCKET: ${TWIGPINE_TIGRIS_BUCKET:-${GITLAWB_TIGRIS_BUCKET:-}} AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID:-} AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY:-} AWS_ENDPOINT_URL_S3: ${AWS_ENDPOINT_URL_S3:-} diff --git a/docs/MAINTAINER-ROADMAP.md b/docs/MAINTAINER-ROADMAP.md index 8c2c5cd7..587487f2 100644 --- a/docs/MAINTAINER-ROADMAP.md +++ b/docs/MAINTAINER-ROADMAP.md @@ -19,7 +19,7 @@ Owner focus: maintainers. - Keep CI green on `main`: format, clippy, workspace tests, release build. - Add PR Docker smoke testing so quickstart regressions are caught before merge. - Add installer smoke tests for release archive names and extraction layout. -- Publish a short operator notice for `GITLAWB_REQUIRE_SIGNED_PEER_WRITES`: leave it `false` until all known peers upgrade, then flip it. +- Publish a short operator notice for `TWIGPINE_REQUIRE_SIGNED_PEER_WRITES`: leave it `false` until all known peers upgrade, then flip it. - Add a live-node checklist: health endpoint, database backup, data volume backup, public URL, reverse proxy/TLS, peer reachability. - Track known public nodes and their version so coordinated upgrades are possible. @@ -30,7 +30,7 @@ Owner focus: node reliability. - Add versioned database migrations instead of implicit startup schema changes. - Add graceful shutdown and startup logging that clearly distinguishes database, repos, P2P, and operator-loop failures. - Add bounded request/concurrency settings for git pack operations. -- Add operator docs for lowering `GITLAWB_MAX_PACK_BYTES` on small nodes. +- Add operator docs for lowering `TWIGPINE_MAX_PACK_BYTES` on small nodes. - Add recovery docs for a broken repo cache, missing data volume, or failed Tigris/S3 sync. - Add basic metrics for pushes, fetches, pack sizes, peer sync queue, failed auth, and webhook failures. diff --git a/docs/RUN-A-NODE.md b/docs/RUN-A-NODE.md index 7a193ee7..01fb488c 100644 --- a/docs/RUN-A-NODE.md +++ b/docs/RUN-A-NODE.md @@ -38,10 +38,10 @@ This is your **node DID** — it's distinct from your Ethereum wallet. This stakes $GITLAWB and links your node DID to your operator wallet: ```bash -export GITLAWB_OPERATOR_PRIVATE_KEY=0xYOUR_KEY -export GITLAWB_TOKEN=0x5F980Dcfc4c0fa3911554cf5ab288ed0eb13DBa3 -export GITLAWB_CONTRACT_NODE_STAKING=0xNODE_STAKING_ADDR -export GITLAWB_CHAIN_RPC_URL=https://mainnet.base.org +export TWIGPINE_OPERATOR_PRIVATE_KEY=0xYOUR_KEY +export TWIGPINE_TOKEN=0x5F980Dcfc4c0fa3911554cf5ab288ed0eb13DBa3 +export TWIGPINE_CONTRACT_NODE_STAKING=0xNODE_STAKING_ADDR +export TWIGPINE_CHAIN_RPC_URL=https://mainnet.base.org twigpine node register \ --stake 10000 \ @@ -65,11 +65,11 @@ docker run -d \ -p 7546:7546/udp \ -v gitlawb-data:/data \ -e DATABASE_URL=postgresql://user:pass@host/gitlawb \ - -e GITLAWB_PUBLIC_URL=https://my-node.example.com \ - -e GITLAWB_OPERATOR_PRIVATE_KEY=$GITLAWB_OPERATOR_PRIVATE_KEY \ - -e GITLAWB_CONTRACT_NODE_STAKING=$GITLAWB_CONTRACT_NODE_STAKING \ - -e GITLAWB_CHAIN_RPC_URL=$GITLAWB_CHAIN_RPC_URL \ - -e GITLAWB_OPERATOR_STRICT_MODE=true \ + -e TWIGPINE_PUBLIC_URL=https://my-node.example.com \ + -e TWIGPINE_OPERATOR_PRIVATE_KEY=$TWIGPINE_OPERATOR_PRIVATE_KEY \ + -e TWIGPINE_CONTRACT_NODE_STAKING=$TWIGPINE_CONTRACT_NODE_STAKING \ + -e TWIGPINE_CHAIN_RPC_URL=$TWIGPINE_CHAIN_RPC_URL \ + -e TWIGPINE_OPERATOR_STRICT_MODE=true \ ghcr.io/twigpine/node:latest ``` @@ -84,14 +84,14 @@ cargo run -p twigpine-node --release ``` Required env for on-chain PoS mode: -- `GITLAWB_CONTRACT_NODE_STAKING` — contract address -- `GITLAWB_OPERATOR_PRIVATE_KEY` — key that posts heartbeats -- `GITLAWB_CHAIN_RPC_URL` — Base RPC URL (default Sepolia) +- `TWIGPINE_CONTRACT_NODE_STAKING` — contract address +- `TWIGPINE_OPERATOR_PRIVATE_KEY` — key that posts heartbeats +- `TWIGPINE_CHAIN_RPC_URL` — Base RPC URL (default Sepolia) Optional: -- `GITLAWB_OPERATOR_STRICT_MODE=true` — refuse to start if not registered or not currently active -- `GITLAWB_HEARTBEAT_INTERVAL_HOURS=20` — how often to post heartbeats (must be < 24) -- `GITLAWB_RECONCILIATION_SWEEP=true` — enable the hourly durability sweep that re-pins/backstops missing objects (default `true`; disabled when no IPFS/Pinata backend is configured). Public pin repair runs against any configured backend. Encrypted recovery repair requires local IPFS (`GITLAWB_IPFS_API`); Pinata-only nodes reconcile public pins only. Set `=false` to disable. +- `TWIGPINE_OPERATOR_STRICT_MODE=true` — refuse to start if not registered or not currently active +- `TWIGPINE_HEARTBEAT_INTERVAL_HOURS=20` — how often to post heartbeats (must be < 24) +- `TWIGPINE_RECONCILIATION_SWEEP=true` — enable the hourly durability sweep that re-pins/backstops missing objects (default `true`; disabled when no IPFS/Pinata backend is configured). Public pin repair runs against any configured backend. Encrypted recovery repair requires local IPFS (`TWIGPINE_IPFS_API`); Pinata-only nodes reconcile public pins only. Set `=false` to disable. ## 5. Verify @@ -181,7 +181,7 @@ repository, the delegate must also be a reader — see *Private repositories and ### Turning it off ```bash -GITLAWB_ENFORCE_OWNER_PUSH=false +TWIGPINE_ENFORCE_OWNER_PUSH=false ``` Both the environment variable and `--enforce-owner-push false` disable it; the @@ -204,7 +204,7 @@ from anyone who can generate a keypair. The owner issues a capability, the agent stores it, and the git helper presents it automatically on every push: -Before anything below, set `GITLAWB_KEY` to an **absolute** path to the +Before anything below, set `TWIGPINE_KEY` to an **absolute** path to the identity PEM (`twigpine identity new` prints it). `twigpine ucan import` and `git-remote-twigpine` both resolve the delegation store from that key's parent directory, so do not pass `import --dir` pointing anywhere else: an import that @@ -299,9 +299,11 @@ short lifetimes reissued often are safer than one long-lived grant. **"insufficient $GITLAWB balance"** — fund the operator wallet with at least 10,000 $GITLAWB. -**Node refuses to start with "strict-mode operator check failed"** — either `twigpine node register` first, or unset `GITLAWB_OPERATOR_STRICT_MODE`. +**Node refuses to start with "strict-mode operator check failed"** — either `twigpine node register` first, or set `TWIGPINE_OPERATOR_STRICT_MODE=false`. Unsetting it is not enough if the setting is also present under its old name, `GITLAWB_OPERATOR_STRICT_MODE`. -**Node refuses to start with "GITLAWB_DB_MAX_CONNECTIONS (20) must be at least max_concurrent_git_pushes (32) + 8 headroom"**: raise `GITLAWB_DB_MAX_CONNECTIONS` to at least the push cap plus 8 (40 with the default cap of 32; 48 is the shipped default and the recommended value), or lower `GITLAWB_MAX_CONCURRENT_GIT_PUSHES`. This bites a node upgraded in place that still sets the old pool size of 20. The check is deliberate: each concurrent push pins one pooled connection for its whole receive-pack, so a pool that does not clear the push cap lets a burst of slow pushes starve every other database path. +**Node refuses to start with "TWIGPINE_DB_LOCK_POOL_MAX_CONNECTIONS (20) must be at least max_concurrent_git_pushes (32) plus 8 for non-push mutations that share the lock pool"**: raise `TWIGPINE_DB_LOCK_POOL_MAX_CONNECTIONS` to at least the push cap plus 8 (40 with the default cap of 32, which is also the shipped default), or lower `TWIGPINE_MAX_CONCURRENT_GIT_PUSHES`. The check is deliberate: each concurrent push pins one connection from the lock pool for its whole receive-pack, so a lock pool that does not clear the push cap lets a burst of slow pushes starve every other mutation that needs a lock. + +**Node refuses to start with "TWIGPINE_DB_MAX_CONNECTIONS (4) must be at least 8 for non-git database paths"**: raise `TWIGPINE_DB_MAX_CONNECTIONS` to 8 or more (48 is the shipped default). This is the main pool, which serves everything other than held write locks; pushes no longer count against it. **Rewards are 0 after a week** — run `twigpine node onchain-status`. If `currentlyActive: false`, check your heartbeat loop (node logs for `operator heartbeat sent`). diff --git a/docs/STORAGE-AND-PINNING.md b/docs/STORAGE-AND-PINNING.md index a6dd0a18..df9ede4e 100644 --- a/docs/STORAGE-AND-PINNING.md +++ b/docs/STORAGE-AND-PINNING.md @@ -3,8 +3,8 @@ How a gitlawb node's **optional post-push pinning tiers** work. This documents the behavior implemented in `crates/twigpine-node/src/ipfs_pin.rs` and `crates/twigpine-node/src/pinata.rs`; it does not change any behavior. Primary -git storage for clone/fetch lives in bare repos under `GITLAWB_REPOS_DIR` -(with optional `GITLAWB_TIGRIS_BUCKET` backing), covered in the README +git storage for clone/fetch lives in bare repos under `TWIGPINE_REPOS_DIR` +(with optional `TWIGPINE_TIGRIS_BUCKET` backing), covered in the README Configuration table. ## Two-tier model @@ -29,19 +29,19 @@ scope. | Tier | Sink | Module | Enabled by | Purpose | |------|------|--------|-----------|---------| -| Hot | Local Kubo (IPFS) | `ipfs_pin.rs` | `GITLAWB_IPFS_API` set | Node-local availability; the node is an HTTP client of a co-located Kubo daemon | -| Warm | Pinata (IPFS) | `pinata.rs` | `GITLAWB_PINATA_JWT` set | Off-node durability + public IPFS gateway reachability | +| Hot | Local Kubo (IPFS) | `ipfs_pin.rs` | `TWIGPINE_IPFS_API` set | Node-local availability; the node is an HTTP client of a co-located Kubo daemon | +| Warm | Pinata (IPFS) | `pinata.rs` | `TWIGPINE_PINATA_JWT` set | Off-node durability + public IPFS gateway reachability | If a sink's config value is empty, its **upload** step is a no-op, so leaving -`GITLAWB_PINATA_JWT` unset disables warm-tier *uploads*. The tail's cost is +`TWIGPINE_PINATA_JWT` unset disables warm-tier *uploads*. The tail's cost is conditional on the same admission gates above: only when the push was admitted to replication does the warm worker still take a global pin permit and run the full object-list re-derivation walk before the upload step returns empty, because its gate is the announce/walk state, not the JWT. On a push that was not admitted, no warm worker runs at all. Note the no-op applies to pinning only, not reads: the hot-tier read path (`ipfs_pin::cat`) returns an error rather -than a no-op when `GITLAWB_IPFS_API` is unset, so a node that serves the -encrypted-blob read endpoint needs Kubo configured. An empty `GITLAWB_IPFS_API` +than a no-op when `TWIGPINE_IPFS_API` is unset, so a node that serves the +encrypted-blob read endpoint needs Kubo configured. An empty `TWIGPINE_IPFS_API` can still briefly touch the pin pool: the hot worker may take a permit when the built object list is non-empty even though the upload call returns immediately. @@ -49,10 +49,10 @@ built object list is non-empty even though the upload call returns immediately. | Env var | Default | Meaning | |---------|---------|---------| -| `GITLAWB_IPFS_API` | `""` (disabled) | Base URL of the local Kubo HTTP API, e.g. `http://127.0.0.1:5001` | -| `GITLAWB_PINATA_JWT` | `""` (disabled) | Pinata bearer JWT enabling the warm tier | -| `GITLAWB_PINATA_UPLOAD_URL` | `https://uploads.pinata.cloud/v3/files` | Pinata v3 upload endpoint | -| `GITLAWB_MAX_CONCURRENT_PIN_TASKS` | `8` | Cap on concurrent post-push pin loops across all repos | +| `TWIGPINE_IPFS_API` | `""` (disabled) | Base URL of the local Kubo HTTP API, e.g. `http://127.0.0.1:5001` | +| `TWIGPINE_PINATA_JWT` | `""` (disabled) | Pinata bearer JWT enabling the warm tier | +| `TWIGPINE_PINATA_UPLOAD_URL` | `https://uploads.pinata.cloud/v3/files` | Pinata v3 upload endpoint | +| `TWIGPINE_MAX_CONCURRENT_PIN_TASKS` | `8` | Cap on concurrent post-push pin loops across all repos | ## How pinning runs @@ -91,7 +91,7 @@ objects whose successful pin is already recorded for that sink. The isolation is one-directional: a hot-only pin does not suppress the warm tier (`pinata_cid` stays null), and a warm-tier pin does not suppress the hot tier either: a row with only `pinata_cid` set has `local_ipfs_provenance = FALSE`, so an object -warm-pinned while `GITLAWB_IPFS_API` was unset can still enter the hot upload +warm-pinned while `TWIGPINE_IPFS_API` was unset can still enter the hot upload path once Kubo is configured, provided a later push selects it (the hot walk covers objects new to that push) or the enabled reconciliation sweep picks it up among eligible public objects, subject to visibility checks, budgets, and diff --git a/install.ps1 b/install.ps1 index dd66d92b..4a9decf4 100644 --- a/install.ps1 +++ b/install.ps1 @@ -22,11 +22,27 @@ $ErrorActionPreference = "Stop" # Windows PowerShell 5.1 may default to TLS 1.0; GitHub requires TLS 1.2+. [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 -$Repo = if ($env:GITLAWB_RELEASE_REPO) { $env:GITLAWB_RELEASE_REPO } else { "Twigpine/node" } -$DownloadBase = if ($env:GITLAWB_DOWNLOAD_BASE) { $env:GITLAWB_DOWNLOAD_BASE.TrimEnd("/") } else { "https://github.com/$Repo/releases/download" } -$ChecksumsUrl = if ($env:GITLAWB_CHECKSUMS_URL) { $env:GITLAWB_CHECKSUMS_URL } else { "https://twigpine.com/install-checksums.txt" } -$InstallDir = if ($env:GITLAWB_INSTALL_DIR) { $env:GITLAWB_INSTALL_DIR } else { "$env:LOCALAPPDATA\Programs\gitlawb" } -$Headers = @{ "User-Agent" = "gitlawb-installer" } +# Settings are TWIGPINE_*; the GITLAWB_* names from before the rename still work. +function Get-Setting([string]$Name, [string]$Default) { + foreach ($prefix in @("TWIGPINE_", "GITLAWB_")) { + $value = [Environment]::GetEnvironmentVariable("$prefix$Name") + if ($value) { return $value } + } + return $Default +} + +$Repo = Get-Setting "RELEASE_REPO" "Twigpine/node" +$DownloadBase = (Get-Setting "DOWNLOAD_BASE" "https://github.com/$Repo/releases/download").TrimEnd("/") +$ChecksumsUrl = Get-Setting "CHECKSUMS_URL" "https://twigpine.com/install-checksums.txt" +# The default folder was Programs\gitlawb before the rename. An install that is +# already there is upgraded in place, so the PATH entry it added stays valid. +$DefaultDir = "$env:LOCALAPPDATA\Programs\twigpine" +$OldDefaultDir = "$env:LOCALAPPDATA\Programs\gitlawb" +if (-not (Test-Path -LiteralPath $DefaultDir) -and (Test-Path -LiteralPath $OldDefaultDir -PathType Container)) { + $DefaultDir = $OldDefaultDir +} +$InstallDir = Get-Setting "INSTALL_DIR" $DefaultDir +$Headers = @{ "User-Agent" = "twigpine-installer" } $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 @@ -38,7 +54,7 @@ if ($arch -ne "AMD64") { } $target = "x86_64-pc-windows-msvc" -$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("gitlawb-" + [System.Guid]::NewGuid().ToString("N")) +$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("twigpine-" + [System.Guid]::NewGuid().ToString("N")) New-Item -ItemType Directory -Path $tmp | Out-Null try { # The checksum list comes first: it names the latest version and is the only @@ -143,7 +159,7 @@ try { foreach ($item in $plan) { $dst = Join-Path $InstallDir $item.Name if (Test-Path -LiteralPath $dst -PathType Container) { - throw "$dst is a directory, and the installer needs that name for a program. Move it away or set GITLAWB_INSTALL_DIR. Nothing was installed." + throw "$dst is a directory, and the installer needs that name for a program. Move it away or set TWIGPINE_INSTALL_DIR. Nothing was installed." } } diff --git a/install.sh b/install.sh index e8122791..8e784ee8 100644 --- a/install.sh +++ b/install.sh @@ -15,10 +15,11 @@ # Plain POSIX sh on purpose: `curl ... | sh` runs dash on Debian and Ubuntu. set -eu -REPO="${GITLAWB_RELEASE_REPO:-Twigpine/node}" -DOWNLOAD_BASE="${GITLAWB_DOWNLOAD_BASE:-https://github.com/${REPO}/releases/download}" -CHECKSUMS_URL="${GITLAWB_CHECKSUMS_URL:-https://twigpine.com/install-checksums.txt}" -INSTALL_DIR="${GITLAWB_INSTALL_DIR:-$HOME/.local/bin}" +# Settings are TWIGPINE_*; the GITLAWB_* names from before the rename still work. +REPO="${TWIGPINE_RELEASE_REPO:-${GITLAWB_RELEASE_REPO:-Twigpine/node}}" +DOWNLOAD_BASE="${TWIGPINE_DOWNLOAD_BASE:-${GITLAWB_DOWNLOAD_BASE:-https://github.com/${REPO}/releases/download}}" +CHECKSUMS_URL="${TWIGPINE_CHECKSUMS_URL:-${GITLAWB_CHECKSUMS_URL:-https://twigpine.com/install-checksums.txt}}" +INSTALL_DIR="${TWIGPINE_INSTALL_DIR:-${GITLAWB_INSTALL_DIR:-$HOME/.local/bin}}" VERSION_ARG="latest" usage() { @@ -30,11 +31,11 @@ Options: -h, --help Show this help. Environment: - GITLAWB_INSTALL_DIR Install directory (default: $HOME/.local/bin) - GITLAWB_RELEASE_REPO GitHub repo to download from (default: Twigpine/node) - GITLAWB_DOWNLOAD_BASE Release download base URL, for mirrors + TWIGPINE_INSTALL_DIR Install directory (default: $HOME/.local/bin) + TWIGPINE_RELEASE_REPO GitHub repo to download from (default: Twigpine/node) + TWIGPINE_DOWNLOAD_BASE Release download base URL, for mirrors (default: https://github.com//releases/download) - GITLAWB_CHECKSUMS_URL Checksum list every download must match + TWIGPINE_CHECKSUMS_URL Checksum list every download must match (default: https://twigpine.com/install-checksums.txt) EOF } @@ -238,7 +239,7 @@ for NAME in twigpine twig gl git-remote-twigpine git-remote-gitlawb twigpine-nod twigpine.new gl.new git-remote-twigpine.new git-remote-gitlawb.new twigpine-node.new gitlawb-node.new; do if [ -d "$INSTALL_DIR/$NAME" ] && [ ! -L "$INSTALL_DIR/$NAME" ]; then echo "error: ${INSTALL_DIR}/${NAME} is a directory, and the installer needs that name for a program." >&2 - echo " Move it away or set GITLAWB_INSTALL_DIR. Nothing was installed." >&2 + echo " Move it away or set TWIGPINE_INSTALL_DIR. Nothing was installed." >&2 exit 1 fi done diff --git a/npm/packages/gl/install.js b/npm/packages/gl/install.js index 631b4571..2a2c3d57 100644 --- a/npm/packages/gl/install.js +++ b/npm/packages/gl/install.js @@ -78,6 +78,12 @@ function install() { chmodSync(dest, 0o755); } + // `twigpine` and `twig` run their own copy, so the CLI can tell it was not + // started as `gl` (it prints a note about the new name when it was). + const renamed = join(binDir, "twigpine"); + copyFileSync(join(binDir, "gl"), renamed); + chmodSync(renamed, 0o755); + console.log(`@gitlawb/gl: Installed Twigpine CLI for ${platformKey}`); } diff --git a/npm/packages/gl/package.json b/npm/packages/gl/package.json index c7acbfd3..d6a160a9 100644 --- a/npm/packages/gl/package.json +++ b/npm/packages/gl/package.json @@ -4,8 +4,8 @@ "description": "Twigpine CLI — decentralized git for AI agents and developers", "license": "MIT", "bin": { - "twigpine": "bin/gl", - "twig": "bin/gl", + "twigpine": "bin/twigpine", + "twig": "bin/twigpine", "gl": "bin/gl", "git-remote-gitlawb": "bin/git-remote-gitlawb" }, diff --git a/scripts/test-install.sh b/scripts/test-install.sh index 82afe121..ae5c3020 100755 --- a/scripts/test-install.sh +++ b/scripts/test-install.sh @@ -134,9 +134,9 @@ run_installer() { shift if [ "${KEEP_HOME:-}" != yes ]; then rm -rf "${W:?}/home" && mkdir -p "$W/home"; fi HOME="${W:?}/home" \ - GITLAWB_INSTALL_DIR="$W/home/bin" \ - GITLAWB_DOWNLOAD_BASE="$BASE/gh" \ - GITLAWB_CHECKSUMS_URL="${LIST_URL:-$BASE/web/install-checksums.txt}" \ + TWIGPINE_INSTALL_DIR="$W/home/bin" \ + TWIGPINE_DOWNLOAD_BASE="$BASE/gh" \ + TWIGPINE_CHECKSUMS_URL="${LIST_URL:-$BASE/web/install-checksums.txt}" \ PATH="${RUN_PATH:-$PATH}" \ "$shell" "$INSTALLER" "$@" > "$W/out" 2>&1 } @@ -175,6 +175,20 @@ suite() { ok "installs the latest listed version" else bad "installs the latest listed version"; fi + # The settings' names from before the rename still work. + reset_server + rm -rf "${W:?}/home" && mkdir -p "$W/home" + # In a subshell with the new names unset, so a developer shell that exports + # them cannot be what makes this pass. + if ( + unset TWIGPINE_INSTALL_DIR TWIGPINE_DOWNLOAD_BASE TWIGPINE_CHECKSUMS_URL TWIGPINE_RELEASE_REPO + HOME="$W/home" GITLAWB_INSTALL_DIR="$W/home/bin" GITLAWB_DOWNLOAD_BASE="$BASE/gh" \ + GITLAWB_CHECKSUMS_URL="$BASE/web/install-checksums.txt" \ + "$shell" "$INSTALLER" > "$W/out" 2>&1 + ) && installed 9.9.0; then + ok "honours the settings under their old GITLAWB_ names" + else bad "honours the settings under their old GITLAWB_ names"; fi + reset_server if run_installer "$shell" --version v9.8.0 && installed 9.8.0; then ok "installs a pinned listed version" @@ -332,9 +346,9 @@ done run_ps1() { if [ "${KEEP_HOME:-}" != yes ]; then rm -rf "${W:?}/home" && mkdir -p "$W/home"; fi PROCESSOR_ARCHITECTURE=AMD64 \ - GITLAWB_INSTALL_DIR="$W/home/bin" \ - GITLAWB_DOWNLOAD_BASE="$BASE/gh" \ - GITLAWB_CHECKSUMS_URL="${LIST_URL:-$BASE/web/install-checksums.txt}" \ + TWIGPINE_INSTALL_DIR="$W/home/bin" \ + TWIGPINE_DOWNLOAD_BASE="$BASE/gh" \ + TWIGPINE_CHECKSUMS_URL="${LIST_URL:-$BASE/web/install-checksums.txt}" \ pwsh -NoProfile -NonInteractive -File "$ROOT/install.ps1" "$@" > "$W/out" 2>&1 } # has : the installed .exe is the build that says . @@ -380,6 +394,18 @@ if [ "$PS1_OK" = yes ] && command -v pwsh >/dev/null 2>&1; then else bad "upgrades an install from before the rename"; fi KEEP_HOME="" + # The settings' names from before the rename still work. + reset_server + rm -rf "${W:?}/home" && mkdir -p "$W/home" + if ( + unset TWIGPINE_INSTALL_DIR TWIGPINE_DOWNLOAD_BASE TWIGPINE_CHECKSUMS_URL TWIGPINE_RELEASE_REPO + PROCESSOR_ARCHITECTURE=AMD64 GITLAWB_INSTALL_DIR="$W/home/bin" GITLAWB_DOWNLOAD_BASE="$BASE/gh" \ + GITLAWB_CHECKSUMS_URL="$BASE/web/install-checksums.txt" \ + pwsh -NoProfile -NonInteractive -File "$ROOT/install.ps1" > "$W/out" 2>&1 + ) && ps1_installed 9.9.0; then + ok "honours the settings under their old GITLAWB_ names" + else bad "honours the settings under their old GITLAWB_ names"; fi + # A directory sitting on a name the installer writes: refuse, copy nothing. for blocked in twigpine.exe twig.exe git-remote-gitlawb.exe; do reset_server