include/punk/punk_reqid.h

filter: Statementstmt 100% 77 / 77 Branchbran 65.6% 67 / 102 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 80.4% 144 / 179 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« xs/views.xs ↑ Summary xs/config.xs »
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 10064 static SV *pr_mint(pTHX) {
57 unsigned char raw[16];
58 char hex[PR_ID_HEX];
59 int i;
60 UV ms;
61  
62 10064 pk_ent_take(aTHX_ raw, 16);
63  
64 { /* milliseconds since the epoch */
65 struct timeval tv;
66 10064 gettimeofday(&tv, NULL);
67 10064 ms = (UV)tv.tv_sec * 1000 + (UV)(tv.tv_usec / 1000);
68 }
69 10064 raw[0] = (unsigned char)((ms >> 40) & 0xff);
70 10064 raw[1] = (unsigned char)((ms >> 32) & 0xff);
71 10064 raw[2] = (unsigned char)((ms >> 24) & 0xff);
72 10064 raw[3] = (unsigned char)((ms >> 16) & 0xff);
73 10064 raw[4] = (unsigned char)((ms >> 8) & 0xff);
74 10064 raw[5] = (unsigned char)( ms & 0xff);
75 10064 raw[6] = (unsigned char)(0x70 | (raw[6] & 0x0f)); /* version 7 */
76 10064 raw[8] = (unsigned char)(0x80 | (raw[8] & 0x3f)); /* variant */
77  
78 171088 ▶ for (i = 0; i < 16; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 16; i++) { 161024 10064 171088
79 161024 hex[i * 2] = PR_HEX[raw[i] >> 4];
80 161024 hex[i * 2 + 1] = PR_HEX[raw[i] & 0x0f];
81 }
82 10064 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 136 static AV *pr_cfg(pTHX_ SV *c) {
143 SV *app, **e;
144 AV *av;
145 136 ▶ if (!SvROK(c)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(c)) return NULL; 0 136 136
146 136 av = pcx_av(aTHX_ c);
147 136 ▶ if (!av) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!av) return NULL; 0 136 136
148 136 app = pcx_get(aTHX_ av, PCX_APP);
149 136 ▶ 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; 136 0 136
if (!(app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)) return NULL; 136 0 136
if (!(app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)) return NULL; 0 136 136
150 136 e = hv_fetchs((HV *)SvRV(app), PR_APP_KEY, 0);
151 136 ▶ 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; 132 4 136
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVAV) return NULL; 132 0 132
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVAV) return NULL; 132 0 132
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVAV) return NULL; 0 132 132
152 132 return (AV *)SvRV(*e);
153 }
154  
155 /* The header to send, or NULL for none - which is `header => 0`. */
156 68 static SV *pr_cfg_header(pTHX_ AV *cfg) {
157 68 ▶ SV **e = cfg ? av_fetch(cfg, 0, 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV **e = cfg ? av_fetch(cfg, 0, 0) : NULL; 66 2 68
158 68 ▶ return (e && *e && SvOK(*e) && SvTRUE(*e)) ? *e : NULL;
Branch: 4 branches
BranchTrueFalseTotal
return (e && *e && SvOK(*e) && SvTRUE(*e)) ? *e : NULL; 66 2 68
return (e && *e && SvOK(*e) && SvTRUE(*e)) ? *e : NULL; 66 0 66
return (e && *e && SvOK(*e) && SvTRUE(*e)) ? *e : NULL; 66 0 66
return (e && *e && SvOK(*e) && SvTRUE(*e)) ? *e : NULL; 65 1 66
159 }
160  
161 /* Put the id where $c->request_id and the response observer can both find it.
162 *
163 * A CONTEXT SLOT, not the stash. The stash was the first version and cost an
164 * HV allocation plus a hash store on every request, for one string - on a
165 * route that never touches the stash otherwise, that HV existed only to hold
166 * this. A slot on the context AV that is already allocated is one av_store.
167 *
168 * On the context at all, rather than a C static, and that is not a stylistic
169 * choice: Punk dispatches asynchronously through Punk::Future, so a worker
170 * can have several requests in flight at once. A "current request id" in a
171 * static would hand one request's id to another - invisibly, and only under
172 * load.
173 */
174 68 static void pr_obs_req(pTHX_ SV *c, void *ud) {
175 AV *av, *cfg;
176 68 SV **envp, *id = NULL;
177 PERL_UNUSED_ARG(ud);
178  
179 68 ▶ if (!SvROK(c)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(c)) return; 0 68 68
180 68 cfg = pr_cfg(aTHX_ c);
181 68 ▶ if (!cfg) return; /* another app in this process */
Branch: 1 branch
BranchTrueFalseTotal
if (!cfg) return; /* another app in this process */ 2 66 68
182 66 av = pcx_av(aTHX_ c);
183 66 ▶ if (!av) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!av) return; 0 66 66
184  
185 /* Adopt an inbound id only when this app asked to, and only when what
186 * arrived survives validation. A value that fails is REPLACED, never
187 * trimmed into shape: a mangled id correlates with nothing at either end,
188 * and silently editing what a client sent produces a third value that
189 * matches neither. */
190 66 envp = av_fetch(cfg, 1, 0);
191 66 ▶ if (envp && *envp && SvOK(*envp)) {
Branch: 3 branches
BranchTrueFalseTotal
if (envp && *envp && SvOK(*envp)) { 66 0 66
if (envp && *envp && SvOK(*envp)) { 66 0 66
if (envp && *envp && SvOK(*envp)) { 33 33 66
192 33 SV *envsv = pcx_get(aTHX_ av, PCX_ENV);
193 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
194 STRLEN kl;
195 33 const char *k = SvPV_const(*envp, kl);
196 33 SV **hv = hv_fetch((HV *)SvRV(envsv), k, (I32)kl, 0);
197 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
198 STRLEN vl;
199 33 const char *v = SvPV_const(*hv, vl);
200 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
201 24 else { pr_n_rejected++; }
202 }
203 }
204 }
205  
206 66 ▶ if (!id) { id = pr_mint(aTHX); pr_n_minted++; }
Branch: 1 branch
BranchTrueFalseTotal
if (!id) { id = pr_mint(aTHX); pr_n_minted++; } 57 9 66
207 66 (void)av_store(av, PCX_REQID, id);
208  
209 /* And into the env under the PSGI extension key, which is how everything
210 * else in the stack finds it: Punk's own logger reads psgix.request_id,
211 * and so do other people's middlewares. Publishing it here rather than
212 * teaching the logger about a context slot means one convention instead
213 * of two, and anything mounted inside this app sees it as well. */
214 {
215 66 SV *envsv = pcx_get(aTHX_ av, PCX_ENV);
216 66 ▶ if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV)
Branch: 3 branches
BranchTrueFalseTotal
if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) 66 0 66
if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) 66 0 66
if (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) 66 0 66
217 66 (void)hv_stores((HV *)SvRV(envsv), "psgix.request_id",
218 newSVsv(id));
219 }
220 }
221  
222 /* Echo it on the way out.
223 *
224 * This runs on the RESPONSE OBSERVER rather than an after_dispatch hook, and
225 * the difference is the whole point: the dispatcher has exits that never
226 * reach punk_finish_c - the house 404 and 405 among them - so an
227 * after_dispatch hook cannot see them. An id present on a 200 and missing on
228 * a 404 is missing exactly when somebody is trying to trace a 404.
229 */
230 68 static void pr_obs_res(pTHX_ SV *c, SV *response, void *ud) {
231 AV *ra, *hdrs, *cav;
232 SV **hp, *id, *name;
233 PERL_UNUSED_ARG(ud);
234  
235 68 name = pr_cfg_header(aTHX_ pr_cfg(aTHX_ c));
236 68 ▶ if (!name) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!name) return; 3 65 68
237 65 ▶ if (!SvROK(response) || SvTYPE(SvRV(response)) != SVt_PVAV) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(response) || SvTYPE(SvRV(response)) != SVt_PVAV) return; 65 0 65
if (!SvROK(response) || SvTYPE(SvRV(response)) != SVt_PVAV) return; 0 65 65
238 65 ra = (AV *)SvRV(response);
239 65 ▶ 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 65 65
240  
241 65 hp = av_fetch(ra, 1, 0);
242 65 ▶ 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; 65 0 65
if (!hp || !*hp || !SvROK(*hp) || SvTYPE(SvRV(*hp)) != SVt_PVAV) return; 65 0 65
if (!hp || !*hp || !SvROK(*hp) || SvTYPE(SvRV(*hp)) != SVt_PVAV) return; 65 0 65
if (!hp || !*hp || !SvROK(*hp) || SvTYPE(SvRV(*hp)) != SVt_PVAV) return; 0 65 65
243 65 hdrs = (AV *)SvRV(*hp);
244  
245 65 cav = pcx_av(aTHX_ c);
246 65 ▶ if (!cav) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!cav) return; 0 65 65
247 65 id = pcx_get(aTHX_ cav, PCX_REQID);
248 65 ▶ if (!id || !SvOK(id)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!id || !SvOK(id)) return; 65 0 65
if (!id || !SvOK(id)) return; 0 65 65
249  
250 65 av_push(hdrs, newSVsv(name));
251 65 av_push(hdrs, newSVsv(id));
252 }
253  
254 /* Registered once per process, at plugin registration - which is boot, in the
255 * parent, before any fork. The observers are process-global by design (the
256 * same reason Fetch's are), so registering twice would echo the header twice. */
257 15 static int pr_enable(pTHX) {
258 15 ▶ 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 */ 10 5 15
259 5 ▶ 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 5 5
260 5 ▶ 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 5 5
261 5 pr_on = 1;
262 5 return 1;
263 }
264  
265 #endif /* PUNK_REQID_H */
« xs/views.xs ↑ Summary xs/config.xs »