include/punk/punk_reqid.h

filter: Statementstmt 100% 77 / 77 Branchbran 72.5% 67 / 102 (15 uncoverable) Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 84.3% 144 / 179 (15 uncoverable) CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« include/punk/punk_future.h ↑ Summary include/punk/punk_url.h »
1 #ifndef PUNK_REQID_H
2 #define PUNK_REQID_H
3  
4 /* Punk::Plugin::RequestId - an id for every request, in C.
5 *
6 * Backs the plugin `Punk.pm`'s SYNOPSIS has always opened with. The whole
7 * path is here because an id is minted on EVERY request, including the ones
8 * that 404, so it sits on the floor of the framework's cost.
9 *
10 * ---- why the shape is what it is (measured) ------------------------------
11 *
12 * A bare Punk request - one route, in-process dispatch, no socket - was
13 * 1058 ns when this was measured (Punk 0.3x; bench/apps/punk-conditional-get
14 * records 1434 ns on a later build, and 0.59 after the state struct is about
15 * 1.9 us on bench/dispatch.pl, which includes building the env). The ratios
16 * are what matter. Against that:
17 *
18 * getentropy(16) per id ............. 693 ns 65.5% of a request
19 * entropy sliced 16 ids per call ..... 42 ns 4.0%
20 * clock_gettime(CLOCK_REALTIME) ...... 12 ns
21 * getpid() ........................... 1.5 ns
22 * this generator, complete ........... 64 ns 6.0%
23 *
24 * `getentropy` costs per CALL, not per byte: a flat ~640-730 ns whether it is
25 * asked for 16 bytes or 256. So it is asked for 256 - its documented maximum -
26 * and sixteen ids are handed out of the result. That one constant is worth
27 * 17x, and it is why pk_random_bytes (which draws per call, correctly, for a
28 * per-session CSRF token) is not used here.
29 *
30 * A LARGER buffer buys nothing: CAP bytes still needs CAP/256 calls, so ids
31 * per syscall is pinned at 16 however much is held. 256 B measured the same
32 * as 256 KB, so 256 B it is - least memory, least unused entropy resident.
33 */
34  
35 #define PR_ID_HEX 32 /* 16 bytes as hex */
36  
37 /* The entropy comes from punk_entropy.h, which is shared with the CSP nonce:
38 * one 256-byte pid-guarded buffer for the dist rather than one per feature.
39 * The reasoning for both the slicing and the pid guard lives there. */
40  
41 static const char PR_HEX[] = "0123456789abcdef";
42  
43 /* A UUIDv7 (RFC 9562) as 32 lowercase hex characters: 48 bits of millisecond
44 * timestamp, then randomness.
45 *
46 * The timestamp is what a plain random id does not have, and it costs one
47 * vDSO clock read - 12 ns, about 1% of a bare request. It buys ids that sort
48 * chronologically across every worker and every log file, which is the thing
49 * people actually do with them.
50 *
51 * A per-worker counter would be 2.7 ns, and was rejected on disclosure rather
52 * than cost: the id goes back to the client in a response header, so a caller
53 * making two requests would learn how many requests that worker served in
54 * between, and every other id would be guessable.
55 */
56 52148 static SV *pr_mint(pTHX) {
57 unsigned char raw[16];
58 char hex[PR_ID_HEX];
59 int i;
60 UV ms;
61  
62 52148 pk_ent_take(aTHX_ raw, 16);
63  
64 { /* milliseconds since the epoch */
65 struct timeval tv;
66 52148 gettimeofday(&tv, NULL);
67 52148 ms = (UV)tv.tv_sec * 1000 + (UV)(tv.tv_usec / 1000);
68 }
69 52148 raw[0] = (unsigned char)((ms >> 40) & 0xff);
70 52148 raw[1] = (unsigned char)((ms >> 32) & 0xff);
71 52148 raw[2] = (unsigned char)((ms >> 24) & 0xff);
72 52148 raw[3] = (unsigned char)((ms >> 16) & 0xff);
73 52148 raw[4] = (unsigned char)((ms >> 8) & 0xff);
74 52148 raw[5] = (unsigned char)( ms & 0xff);
75 52148 raw[6] = (unsigned char)(0x70 | (raw[6] & 0x0f)); /* version 7 */
76 52148 raw[8] = (unsigned char)(0x80 | (raw[8] & 0x3f)); /* variant */
77  
78 886516 ▶ for (i = 0; i < 16; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 16; i++) { 834368 52148 886516
79 834368 hex[i * 2] = PR_HEX[raw[i] >> 4];
80 834368 hex[i * 2 + 1] = PR_HEX[raw[i] & 0x0f];
81 }
82 52148 return newSVpvn(hex, PR_ID_HEX);
83 }
84  
85 /* ---- adopting an id handed in by a proxy --------------------------------- */
86  
87 /* An inbound id is REQUEST BYTES, which is the bug class this workspace has
88 * been bitten by three times (CVE-2026-75628, the markdown 301, the
89 * Reverse::Proxy smuggling fix). It reaches two dangerous places: a log line
90 * and a response header. A CR in the first forges a log entry; a CR in the
91 * second splits the response.
92 *
93 * So the charset is deliberately narrower than HTTP allows: printable ASCII
94 * with no space and no DEL, which is 0x21 to 0x7e. That covers every real id
95 * format - a UUID, hex, base64, base64url, a W3C traceparent - and excludes
96 * CR, LF, NUL, tab, every other control byte and everything above ASCII.
97 *
98 * 128 bytes because the longest thing anyone legitimately sends is a
99 * traceparent at 55. An id is not a place to put a kilobyte, and a log file
100 * is not a place to let somebody else decide how many bytes to write.
101 */
102 #define PR_MAX_INBOUND 128
103  
104 static UV pr_n_adopted = 0;
105 static UV pr_n_rejected = 0;
106 static UV pr_n_minted = 0;
107  
108 33 static int pr_id_ok(const char *p, STRLEN len) {
109 STRLEN i;
110 33 ▶ if (len == 0 || len > PR_MAX_INBOUND) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (len == 0 || len > PR_MAX_INBOUND) return 0; 31 2 33
if (len == 0 || len > PR_MAX_INBOUND) return 0; 4 27 31
111 391 ▶ for (i = 0; i < len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < len; i++) { 382 9 391
112 382 unsigned char ch = (unsigned char)p[i];
113 382 ▶ if (ch < 0x21 || ch > 0x7e) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (ch < 0x21 || ch > 0x7e) return 0; 368 14 382
if (ch < 0x21 || ch > 0x7e) return 0; 4 364 368
114 }
115 9 return 1;
116 }
117  
118 /* ---- the plugin's state -------------------------------------------------- */
119 /*
120 * The observers are process-global - they have to be, the same way Fetch's
121 * are - but the CONFIGURATION is per application, frozen on the app hash
122 * beside the `session` and `csrf` keywords' own.
123 *
124 * Holding the header name in a static instead was the first version, and it
125 * was wrong in a way only a second app reveals: two Punk apps under one
126 * Plack::Builder share the process, so whichever registered last named the
127 * header for BOTH. App A emitted `X-B-Id`. Per-app options that quietly stop
128 * being per-app are worse than options that were never offered.
129 */
130  
131 #define PR_APP_KEY "punk.request_id"
132  
133 static int pr_on = 0; /* observers registered in this process */
134  
135 /* This app's config: an AV of [ header-name-or-false, env-key-or-undef ].
136 *
137 * Two elements rather than two hash keys because it is read on every request
138 * and an AV fetch is cheaper than a second hv_fetch. Element 1 is present
139 * only when `trust_header` was asked for, so its mere existence is the
140 * trust decision - there is no separate flag to fall out of step with it.
141 */
142 256 static AV *pr_cfg(pTHX_ SV *c) {
143 SV *app, **e;
144 AV *av;
145 /*
146 # uncoverable branch true
147 # uncoverable condition left count:1 class:ignore_covered_err */
148 256 ▶ if (!SvROK(c)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(c)) return NULL; 0 256 256
149 256 av = pcx_av(aTHX_ c);
150 /*
151 # uncoverable branch true
152 # uncoverable condition left count:1 class:ignore_covered_err */
153 256 ▶ if (!av) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!av) return NULL; 0 256 256
154 256 app = pcx_get(aTHX_ av, PCX_APP);
155 /*
156 # uncoverable branch true
157 # uncoverable condition left count:1 class:ignore_covered_err
158 # uncoverable condition left count:2 class:ignore_covered_err
159 # uncoverable condition left count:3 class:ignore_covered_err */
160 256 ▶ if (!(app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)) return NULL;
Branch: 3 branches
BranchTrueFalseTotal
if (!(app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)) return NULL; 256 0 256
if (!(app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)) return NULL; 256 0 256
if (!(app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)) return NULL; 0 256 256
161 256 e = hv_fetchs((HV *)SvRV(app), PR_APP_KEY, 0);
162 /*
163 # uncoverable condition left count:2 class:ignore_covered_err
164 # uncoverable condition left count:3 class:ignore_covered_err
165 # uncoverable condition left count:4 class:ignore_covered_err */
166 256 ▶ if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVAV) return NULL;
Branch: 4 branches
BranchTrueFalseTotal
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVAV) return NULL; 244 12 256
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVAV) return NULL; 244 0 244
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVAV) return NULL; 244 0 244
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVAV) return NULL; 0 244 244
167 244 return (AV *)SvRV(*e);
168 }
169  
170 /* The header to send, or NULL for none - which is `header => 0`. */
171 128 static SV *pr_cfg_header(pTHX_ AV *cfg) {
172 128 ▶ SV **e = cfg ? av_fetch(cfg, 0, 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV **e = cfg ? av_fetch(cfg, 0, 0) : NULL; 122 6 128
173 /*
174 # uncoverable condition right count:2 class:ignore_covered_err
175 # uncoverable condition right count:3 class:ignore_covered_err */
176 128 ▶ return (e && *e && SvOK(*e) && SvTRUE(*e)) ? *e : NULL;
Branch: 4 branches
BranchTrueFalseTotal
return (e && *e && SvOK(*e) && SvTRUE(*e)) ? *e : NULL; 122 6 128
return (e && *e && SvOK(*e) && SvTRUE(*e)) ? *e : NULL; 122 0 122
return (e && *e && SvOK(*e) && SvTRUE(*e)) ? *e : NULL; 122 0 122
return (e && *e && SvOK(*e) && SvTRUE(*e)) ? *e : NULL; 117 5 122
177 }
178  
179 /* Put the id where $c->request_id and the response observer can both find it.
180 *
181 * A CONTEXT SLOT, not the stash. The stash was the first version and cost an
182 * HV allocation plus a hash store on every request, for one string - on a
183 * route that never touches the stash otherwise, that HV existed only to hold
184 * this. A slot on the context AV that is already allocated is one av_store.
185 *
186 * On the context at all, rather than a C static, and that is not a stylistic
187 * choice: Punk dispatches asynchronously through Punk::Future, so a worker
188 * can have several requests in flight at once. A "current request id" in a
189 * static would hand one request's id to another - invisibly, and only under
190 * load.
191 */
192 128 static void pr_obs_req(pTHX_ SV *c, void *ud) {
193 AV *av, *cfg;
194 128 SV **envp, *id = NULL;
195 PERL_UNUSED_ARG(ud);
196  
197 /*
198 # uncoverable branch true
199 # uncoverable condition left count:1 class:ignore_covered_err */
200 128 ▶ if (!SvROK(c)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(c)) return; 0 128 128
201 128 cfg = pr_cfg(aTHX_ c);
202 128 ▶ if (!cfg) return; /* another app in this process */
Branch: 1 branch
BranchTrueFalseTotal
if (!cfg) return; /* another app in this process */ 6 122 128
203 122 av = pcx_av(aTHX_ c);
204 /*
205 # uncoverable branch true
206 # uncoverable condition left count:1 class:ignore_covered_err */
207 122 ▶ if (!av) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!av) return; 0 122 122
208  
209 /* Adopt an inbound id only when this app asked to, and only when what
210 * arrived survives validation. A value that fails is REPLACED, never
211 * trimmed into shape: a mangled id correlates with nothing at either end,
212 * and silently editing what a client sent produces a third value that
213 * matches neither. */
214 122 envp = av_fetch(cfg, 1, 0);
215 /*
216 # uncoverable condition right count:1 class:ignore_covered_err
217 # uncoverable condition right count:2 class:ignore_covered_err */
218 122 ▶ if (envp && *envp && SvOK(*envp)) {
Branch: 3 branches
BranchTrueFalseTotal
if (envp && *envp && SvOK(*envp)) { 122 0 122
if (envp && *envp && SvOK(*envp)) { 122 0 122
if (envp && *envp && SvOK(*envp)) { 33 89 122
219 33 SV *envsv = pcx_get(aTHX_ av, PCX_ENV);
220 /*
221 # uncoverable branch false
222 # uncoverable condition right count:1 class:ignore_covered_err
223 # uncoverable condition right count:2 class:ignore_covered_err
224 # uncoverable condition right count:3 class:ignore_covered_err */
225 33 ▶ if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) {
Branch: 3 branches
BranchTrueFalseTotal
if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) { 33 0 33
if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) { 33 0 33
if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) { 33 0 33
226 STRLEN kl;
227 33 const char *k = SvPV_const(*envp, kl);
228 33 SV **hv = hv_fetch((HV *)SvRV(envsv), k, (I32)kl, 0);
229 /*
230 # uncoverable branch false
231 # uncoverable condition right count:1 class:ignore_covered_err
232 # uncoverable condition right count:2 class:ignore_covered_err
233 # uncoverable condition right count:3 class:ignore_covered_err */
234 33 ▶ if (hv && *hv && SvOK(*hv)) {
Branch: 3 branches
BranchTrueFalseTotal
if (hv && *hv && SvOK(*hv)) { 33 0 33
if (hv && *hv && SvOK(*hv)) { 33 0 33
if (hv && *hv && SvOK(*hv)) { 33 0 33
235 STRLEN vl;
236 33 const char *v = SvPV_const(*hv, vl);
237 33 ▶ if (pr_id_ok(v, vl)) { id = newSVpvn(v, vl); pr_n_adopted++; }
Branch: 1 branch
BranchTrueFalseTotal
if (pr_id_ok(v, vl)) { id = newSVpvn(v, vl); pr_n_adopted++; } 9 24 33
238 24 else { pr_n_rejected++; }
239 }
240 }
241 }
242  
243 122 ▶ if (!id) { id = pr_mint(aTHX); pr_n_minted++; }
Branch: 1 branch
BranchTrueFalseTotal
if (!id) { id = pr_mint(aTHX); pr_n_minted++; } 113 9 122
244 122 (void)av_store(av, PCX_REQID, id);
245  
246 /* And into the env under the PSGI extension key, which is how everything
247 * else in the stack finds it: Punk's own logger reads psgix.request_id,
248 * and so do other people's middlewares. Publishing it here rather than
249 * teaching the logger about a context slot means one convention instead
250 * of two, and anything mounted inside this app sees it as well. */
251 {
252 122 SV *envsv = pcx_get(aTHX_ av, PCX_ENV);
253 /*
254 # uncoverable branch false
255 # uncoverable condition right count:1 class:ignore_covered_err
256 # uncoverable condition right count:2 class:ignore_covered_err
257 # uncoverable condition right count:3 class:ignore_covered_err */
258 122 ▶ if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV)
Branch: 3 branches
BranchTrueFalseTotal
if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) 122 0 122
if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) 122 0 122
if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) 122 0 122
259 122 (void)hv_stores((HV *)SvRV(envsv), "psgix.request_id",
260 newSVsv(id));
261 }
262 }
263  
264 /* Echo it on the way out.
265 *
266 * This runs on the RESPONSE OBSERVER rather than an after_dispatch hook, and
267 * the difference is the whole point: the dispatcher has exits that never
268 * reach punk_finish_c - the house 404 and 405 among them - so an
269 * after_dispatch hook cannot see them. An id present on a 200 and missing on
270 * a 404 is missing exactly when somebody is trying to trace a 404.
271 */
272 128 static void pr_obs_res(pTHX_ SV *c, SV *response, void *ud) {
273 AV *ra, *hdrs, *cav;
274 SV **hp, *id, *name;
275 PERL_UNUSED_ARG(ud);
276  
277 128 name = pr_cfg_header(aTHX_ pr_cfg(aTHX_ c));
278 128 ▶ if (!name) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!name) return; 11 117 128
279 /*
280 # uncoverable branch true
281 # uncoverable condition left count:1 class:ignore_covered_err
282 # uncoverable condition left count:2 class:ignore_covered_err */
283 117 ▶ if (!SvROK(response) || SvTYPE(SvRV(response)) != SVt_PVAV) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(response) || SvTYPE(SvRV(response)) != SVt_PVAV) return; 117 0 117
if (!SvROK(response) || SvTYPE(SvRV(response)) != SVt_PVAV) return; 0 117 117
284 117 ra = (AV *)SvRV(response);
285 /*
286 # uncoverable branch true
287 # uncoverable condition left count:1 class:ignore_covered_err */
288 117 ▶ if (av_len(ra) < 1) return; /* not a triplet: leave it */
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(ra) < 1) return; /* not a triplet: leave it */ 0 117 117
289  
290 117 hp = av_fetch(ra, 1, 0);
291 /*
292 # uncoverable branch true
293 # uncoverable condition left count:1 class:ignore_covered_err
294 # uncoverable condition left count:2 class:ignore_covered_err
295 # uncoverable condition left count:3 class:ignore_covered_err
296 # uncoverable condition left count:4 class:ignore_covered_err */
297 117 ▶ if (!hp || !*hp || !SvROK(*hp) || SvTYPE(SvRV(*hp)) != SVt_PVAV) return;
Branch: 4 branches
BranchTrueFalseTotal
if (!hp || !*hp || !SvROK(*hp) || SvTYPE(SvRV(*hp)) != SVt_PVAV) return; 117 0 117
if (!hp || !*hp || !SvROK(*hp) || SvTYPE(SvRV(*hp)) != SVt_PVAV) return; 117 0 117
if (!hp || !*hp || !SvROK(*hp) || SvTYPE(SvRV(*hp)) != SVt_PVAV) return; 117 0 117
if (!hp || !*hp || !SvROK(*hp) || SvTYPE(SvRV(*hp)) != SVt_PVAV) return; 0 117 117
298 117 hdrs = (AV *)SvRV(*hp);
299  
300 117 cav = pcx_av(aTHX_ c);
301 /*
302 # uncoverable branch true
303 # uncoverable condition left count:1 class:ignore_covered_err */
304 117 ▶ if (!cav) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!cav) return; 0 117 117
305 117 id = pcx_get(aTHX_ cav, PCX_REQID);
306 /*
307 # uncoverable branch true
308 # uncoverable condition left count:1 class:ignore_covered_err
309 # uncoverable condition left count:2 class:ignore_covered_err */
310 117 ▶ if (!id || !SvOK(id)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!id || !SvOK(id)) return; 117 0 117
if (!id || !SvOK(id)) return; 0 117 117
311  
312 117 av_push(hdrs, newSVsv(name));
313 117 av_push(hdrs, newSVsv(id));
314 }
315  
316 /* Registered once per process, at plugin registration - which is boot, in the
317 * parent, before any fork. The observers are process-global by design (the
318 * same reason Fetch's are), so registering twice would echo the header twice. */
319 44 static int pr_enable(pTHX) {
320 44 ▶ if (pr_on) return 1; /* once per process, not per app */
Branch: 1 branch
BranchTrueFalseTotal
if (pr_on) return 1; /* once per process, not per app */ 34 10 44
321 /*
322 # uncoverable branch true
323 # uncoverable condition left count:1 class:ignore_covered_err */
324 10 ▶ if (!pk_obs_add_req(aTHX_ pr_obs_req, NULL)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!pk_obs_add_req(aTHX_ pr_obs_req, NULL)) return 0; 0 10 10
325 /*
326 # uncoverable branch true
327 # uncoverable condition left count:1 class:ignore_covered_err */
328 10 ▶ if (!pk_obs_add_res(aTHX_ pr_obs_res, NULL)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!pk_obs_add_res(aTHX_ pr_obs_res, NULL)) return 0; 0 10 10
329 10 pr_on = 1;
330 10 return 1;
331 }
332  
333 #endif /* PUNK_REQID_H */
« include/punk/punk_future.h ↑ Summary include/punk/punk_url.h »