include/oa_plack.h

filter: Statementstmt 88.8% 788 / 887 Branchbran 59.3% 650 / 1096 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 72.5% 1438 / 1983 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« API.xs ↑ Summary include/oa_tools.h »
1 #ifndef OA_PLACK_H
2 #define OA_PLACK_H
3  
4 /* The PSGI adapter, all in C: $api->to_app(handlers => {...}) returns a PSGI
5 * coderef (a magic CV carrying its captures) whose request path is
6 * route -> validate -> dispatch -> respond. A handler may return a PSGI
7 * triplet, plain data (JSON-encoded as a 200), or - on a non-blocking server
8 * (psgi.nonblocking, e.g. Hyperman) - a Future-like object resolving to one
9 * of those, which is passed straight through for the server to await. On
10 * blocking servers a returned Future is ->get awaited inline. */
11  
12 /* ---- closures: a CV carrying captured SVs (the rp_closure pattern) -------- */
13  
14 typedef struct oa_clos { AV *cap; } oa_clos;
15  
16 579 static int oa_clos_free(pTHX_ SV *sv, MAGIC *mg) {
17 579 oa_clos *c = (oa_clos *)mg->mg_ptr;
18 PERL_UNUSED_ARG(sv);
19 579 ▶ if (c) { if (c->cap) SvREFCNT_dec((SV *)c->cap); Safefree(c); }
Branch: 2 branches
BranchTrueFalseTotal
if (c) { if (c->cap) SvREFCNT_dec((SV *)c->cap); Safefree(c); } 579 0 579
if (c) { if (c->cap) SvREFCNT_dec((SV *)c->cap); Safefree(c); } 579 0 579
20 579 return 0;
21 }
22 static MGVTBL oa_clos_vtbl = { NULL, NULL, NULL, NULL, oa_clos_free,
23 NULL, NULL, NULL };
24  
25 580 static SV *oa_closure(pTHX_ XSUBADDR_t body, AV *cap) {
26 580 CV *cv = (CV *)newXS(NULL, body, __FILE__);
27 oa_clos *c;
28 580 Newxz(c, 1, oa_clos);
29 580 c->cap = cap; /* takes ownership */
30 580 sv_magicext((SV *)cv, NULL, PERL_MAGIC_ext, &oa_clos_vtbl, (char *)c, 0);
31 580 return newRV_noinc((SV *)cv);
32 }
33 631 static AV *oa_clos_cap(pTHX_ CV *cv) {
34 631 MAGIC *mg = mg_findext((SV *)cv, PERL_MAGIC_ext, &oa_clos_vtbl);
35 631 ▶ return mg ? ((oa_clos *)mg->mg_ptr)->cap : NULL;
Branch: 1 branch
BranchTrueFalseTotal
return mg ? ((oa_clos *)mg->mg_ptr)->cap : NULL; 631 0 631
36 }
37  
38 /* ---- JSON responses -------------------------------------------------------- */
39  
40 /* Encode a Perl value through the frj ABI. The ABI croaks on an unencodable
41 * shape, so the encode runs inside the private _frj_encode trampoline (a
42 * direct ABI call), invoked on its cached CV with G_EVAL - a bad handler
43 * return degrades instead of escaping the request. Mortal SV on success,
44 * NULL on failure. OA_ENC_CV is resolved in BOOT (API.xs). */
45 578 static SV *oa_json_encode(pTHX_ SV *val) {
46 578 dSP; int count; SV *ret = NULL;
47 578 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 578 578
48 578 ▶ XPUSHs(val); PUTBACK;
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(val); PUTBACK; 0 578 578
49 578 count = call_sv(OA_ENC_CV, G_SCALAR | G_EVAL);
50 578 SPAGAIN;
51 578 ▶ if (!SvTRUE(ERRSV) && count > 0) { SV *r = POPs; if (SvOK(r)) ret = newSVsv(r); }
Branch: 4 branches
BranchTrueFalseTotal
if (!SvTRUE(ERRSV) && count > 0) { SV *r = POPs; if (SvOK(r)) ret = newSVsv(r); } 578 0 578
if (!SvTRUE(ERRSV) && count > 0) { SV *r = POPs; if (SvOK(r)) ret = newSVsv(r); } 578 0 578
if (!SvTRUE(ERRSV) && count > 0) { SV *r = POPs; if (SvOK(r)) ret = newSVsv(r); } 578 0 578
if (!SvTRUE(ERRSV) && count > 0) { SV *r = POPs; if (SvOK(r)) ret = newSVsv(r); } 578 0 578
52 0 ▶ else if (count > 0) (void)POPs;
Branch: 1 branch
BranchTrueFalseTotal
else if (count > 0) (void)POPs; 0 0 0
53 578 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 578 0 578
54 578 ▶ return ret ? sv_2mortal(ret) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
return ret ? sv_2mortal(ret) : NULL; 578 0 578
55 }
56  
57 /* [ $status, ['Content-Type','application/json'], [$json] ] (+1) */
58 571 static SV *oa_json_response(pTHX_ int status, SV *val) {
59 571 AV *h = newAV(), *b = newAV(), *r = newAV();
60 571 SV *json = oa_json_encode(aTHX_ val);
61 571 av_push(h, newSVpvs("Content-Type"));
62 571 av_push(h, newSVpvs("application/json"));
63 571 ▶ av_push(b, json ? newSVsv(json) : newSVpvs("null"));
Branch: 1 branch
BranchTrueFalseTotal
av_push(b, json ? newSVsv(json) : newSVpvs("null")); 571 0 571
64 571 av_push(r, newSViv(status));
65 571 av_push(r, newRV_noinc((SV *)h));
66 571 av_push(r, newRV_noinc((SV *)b));
67 571 return newRV_noinc((SV *)r);
68 }
69  
70 /* { errors => \@errs } as a JSON response (+1). errs borrowed. */
71 49 static SV *oa_error_response(pTHX_ int status, AV *errs) {
72 49 HV *wrap = newHV();
73 SV *rv, *w;
74 49 (void)hv_stores(wrap, "errors", newRV_inc((SV *)errs));
75 49 w = sv_2mortal(newRV_noinc((SV *)wrap));
76 49 rv = oa_json_response(aTHX_ status, w);
77 49 return rv;
78 }
79  
80 /* one-message error response (+1) */
81 36 static SV *oa_error_msg(pTHX_ int status, const char *msg) {
82 36 AV *errs = (AV *)sv_2mortal((SV *)newAV());
83 36 HV *e = newHV();
84 36 (void)hv_stores(e, "message", newSVpv(msg, 0));
85 36 av_push(errs, newRV_noinc((SV *)e));
86 36 return oa_error_response(aTHX_ status, errs);
87 }
88  
89 /* ---- env access -------------------------------------------------------------- */
90  
91 4299 static SV *oa_env_get(pTHX_ HV *env, const char *k) {
92 4299 SV **e = hv_fetch(env, k, (I32)strlen(k), 0);
93 4299 ▶ return (e && *e && SvOK(*e)) ? *e : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (e && *e && SvOK(*e)) ? *e : NULL; 2013 2286 4299
return (e && *e && SvOK(*e)) ? *e : NULL; 2013 0 2013
return (e && *e && SvOK(*e)) ? *e : NULL; 2013 0 2013
94 }
95  
96 /* read CONTENT_LENGTH bytes from psgi.input (the rp_read_body pattern) */
97 15 static SV *oa_read_body_env(pTHX_ HV *env) {
98 15 SV *cl = oa_env_get(aTHX_ env, "CONTENT_LENGTH");
99 15 SV *in = oa_env_get(aTHX_ env, "psgi.input");
100 15 IV len, off = 0;
101 SV *body;
102 15 ▶ if (!cl || !in) return NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (!cl || !in) return NULL; 15 0 15
if (!cl || !in) return NULL; 0 15 15
103 15 len = SvIV(cl);
104 15 ▶ if (len <= 0) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (len <= 0) return NULL; 0 15 15
105 /* psgi.input is usually a plain filehandle, and read() on one is a method
106 * call. Perl only auto-loads IO::Handle to resolve filehandle methods from
107 * 5.14 on; before that the call simply fails, and under the G_EVAL below
108 * that failure is silent - the body read back empty and a perfectly good
109 * POST was rejected as "missing required request body". Load it once. */
110 {
111 static int oa_io_handle_loaded = 0;
112 15 ▶ if (!oa_io_handle_loaded) {
Branch: 1 branch
BranchTrueFalseTotal
if (!oa_io_handle_loaded) { 3 12 15
113 3 oa_io_handle_loaded = 1;
114 3 eval_pv("require IO::Handle;", FALSE);
115 }
116 }
117 15 body = sv_2mortal(newSVpvs(""));
118 30 ▶ while (off < len) {
Branch: 1 branch
BranchTrueFalseTotal
while (off < len) { 15 15 30
119 15 dSP; int n; IV got;
120 15 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 15 15
121 15 ▶ EXTEND(SP, 4);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 4); 0 15 15
122 15 PUSHs(in);
123 15 PUSHs(body);
124 15 PUSHs(sv_2mortal(newSViv(len - off)));
125 15 PUSHs(sv_2mortal(newSViv(off)));
126 15 PUTBACK;
127 15 n = call_method("read", G_SCALAR | G_EVAL);
128 15 SPAGAIN;
129 15 ▶ got = (!SvTRUE(ERRSV) && n > 0) ? POPi : 0;
Branch: 3 branches
BranchTrueFalseTotal
got = (!SvTRUE(ERRSV) && n > 0) ? POPi : 0; 15 0 15
got = (!SvTRUE(ERRSV) && n > 0) ? POPi : 0; 15 0 15
got = (!SvTRUE(ERRSV) && n > 0) ? POPi : 0; 15 0 15
130 15 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 15 0 15
131 15 ▶ if (got <= 0) break;
Branch: 1 branch
BranchTrueFalseTotal
if (got <= 0) break; 0 15 15
132 15 off += got;
133 }
134 15 return body;
135 }
136  
137 /* Build the minimal lowercased header HV oa_validate_op needs for this op:
138 * content-type, cookie, and each declared header parameter (fresh HV). */
139 600 static HV *oa_headers_for(pTHX_ oa_op *o, HV *env) {
140 600 HV *out = newHV();
141 SV *v;
142 int i;
143 600 ▶ if ((v = oa_env_get(aTHX_ env, "CONTENT_TYPE")))
Branch: 1 branch
BranchTrueFalseTotal
if ((v = oa_env_get(aTHX_ env, "CONTENT_TYPE"))) 35 565 600
144 35 (void)hv_stores(out, "content-type", newSVsv(v));
145 600 ▶ if ((v = oa_env_get(aTHX_ env, "HTTP_COOKIE")))
Branch: 1 branch
BranchTrueFalseTotal
if ((v = oa_env_get(aTHX_ env, "HTTP_COOKIE"))) 11 589 600
146 11 (void)hv_stores(out, "cookie", newSVsv(v));
147 1132 ▶ for (i = 0; i < o->nparams[OA_IN_HEADER]; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < o->nparams[OA_IN_HEADER]; i++) { 532 600 1132
148 532 STRLEN nl; const char *np = SvPV_const(o->params[OA_IN_HEADER][i].name, nl);
149 char key[160], lc[128];
150 STRLEN k;
151 SV **e;
152 532 ▶ if (nl + 5 >= sizeof key || nl >= sizeof lc) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (nl + 5 >= sizeof key || nl >= sizeof lc) continue; 532 0 532
if (nl + 5 >= sizeof key || nl >= sizeof lc) continue; 0 532 532
153 532 memcpy(key, "HTTP_", 5);
154 6916 ▶ for (k = 0; k < nl; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < nl; k++) { 6384 532 6916
155 6384 char c = np[k];
156 6384 ▶ key[5 + k] = (c == '-') ? '_' : (char)toUPPER((U8)c);
Branch: 2 branches
BranchTrueFalseTotal
key[5 + k] = (c == '-') ? '_' : (char)toUPPER((U8)c); 5320 1064 6384
key[5 + k] = (c == '-') ? '_' : (char)toUPPER((U8)c); 3724 1596 5320
157 6384 ▶ lc[k] = (char)toLOWER((U8)c);
Branch: 1 branch
BranchTrueFalseTotal
lc[k] = (char)toLOWER((U8)c); 1596 4788 6384
158 }
159 532 key[5 + nl] = '\0';
160 532 e = hv_fetch(env, key, (I32)(5 + nl), 0);
161 532 ▶ if (e && *e && SvOK(*e))
Branch: 3 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e)) 0 532 532
if (e && *e && SvOK(*e)) 0 0 0
if (e && *e && SvOK(*e)) 0 0 0
162 0 (void)hv_store(out, lc, (I32)nl, newSVsv(*e), 0);
163 }
164 600 return out;
165 }
166  
167 /* ---- handler result mapping ---------------------------------------------------- */
168  
169 /* a PSGI triplet: [ status, \@headers, ... ] */
170 4206 static int oa_is_triplet(pTHX_ SV *sv) {
171 AV *av;
172 SV **s, **h;
173 4206 ▶ if (!sv || !SvROK(sv) || SvTYPE(SvRV(sv)) != SVt_PVAV) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (!sv || !SvROK(sv) || SvTYPE(SvRV(sv)) != SVt_PVAV) return 0; 4206 0 4206
if (!sv || !SvROK(sv) || SvTYPE(SvRV(sv)) != SVt_PVAV) return 0; 4199 7 4206
if (!sv || !SvROK(sv) || SvTYPE(SvRV(sv)) != SVt_PVAV) return 0; 509 3690 4199
174 3690 av = (AV *)SvRV(sv);
175 3690 ▶ if (av_len(av) + 1 != 3) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(av) + 1 != 3) return 0; 13 3677 3690
176 3677 s = av_fetch(av, 0, 0);
177 3677 h = av_fetch(av, 1, 0);
178 3677 ▶ if (!s || !*s || !SvOK(*s) || SvROK(*s)) return 0;
Branch: 4 branches
BranchTrueFalseTotal
if (!s || !*s || !SvOK(*s) || SvROK(*s)) return 0; 3677 0 3677
if (!s || !*s || !SvOK(*s) || SvROK(*s)) return 0; 3677 0 3677
if (!s || !*s || !SvOK(*s) || SvROK(*s)) return 0; 3677 0 3677
if (!s || !*s || !SvOK(*s) || SvROK(*s)) return 0; 0 3677 3677
179 3677 ▶ if (!looks_like_number(*s)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!looks_like_number(*s)) return 0; 0 3677 3677
180 3677 ▶ if (!h || !*h || !SvROK(*h) || SvTYPE(SvRV(*h)) != SVt_PVAV) return 0;
Branch: 4 branches
BranchTrueFalseTotal
if (!h || !*h || !SvROK(*h) || SvTYPE(SvRV(*h)) != SVt_PVAV) return 0; 3677 0 3677
if (!h || !*h || !SvROK(*h) || SvTYPE(SvRV(*h)) != SVt_PVAV) return 0; 3677 0 3677
if (!h || !*h || !SvROK(*h) || SvTYPE(SvRV(*h)) != SVt_PVAV) return 0; 3677 0 3677
if (!h || !*h || !SvROK(*h) || SvTYPE(SvRV(*h)) != SVt_PVAV) return 0; 0 3677 3677
181 3677 return 1;
182 }
183  
184 /* an object with on_ready (a Future the server can await) */
185 586 static int oa_is_future(pTHX_ SV *sv) {
186 586 ▶ return sv && SvROK(sv) && SvOBJECT(SvRV(sv))
Branch: 2 branches
BranchTrueFalseTotal
return sv && SvROK(sv) && SvOBJECT(SvRV(sv)) 586 0 586
return sv && SvROK(sv) && SvOBJECT(SvRV(sv)) 2 584 586
187 1172 ▶ && gv_fetchmethod_autoload(SvSTASH(SvRV(sv)), "on_ready", 0) != NULL;
Branch: 2 branches
BranchTrueFalseTotal
&& gv_fetchmethod_autoload(SvSTASH(SvRV(sv)), "on_ready", 0) != NULL; 586 0 586
&& gv_fetchmethod_autoload(SvSTASH(SvRV(sv)), "on_ready", 0) != NULL; 2 0 2
188 }
189  
190 /* triplet passes through; anything else JSON-encodes as a 200 (+1) */
191 587 static SV *oa_map_result(pTHX_ SV *res) {
192 587 ▶ if (oa_is_triplet(aTHX_ res)) return newSVsv(res);
Branch: 1 branch
BranchTrueFalseTotal
if (oa_is_triplet(aTHX_ res)) return newSVsv(res); 65 522 587
193 522 return oa_json_response(aTHX_ 200, res);
194 }
195  
196 /* ---- response validation ------------------------------------------------------- *
197 *
198 * Two modes over one code path:
199 *
200 * OA_RV_REPLACE (validate_responses => 1) - the dev tool. A mismatch
201 * *replaces* the response with a 500 describing it. Unchanged from
202 * 0.06, defaults included: somebody's dev server depends on it.
203 * OA_RV_REPORT (validate_responses => 'report') - the product. The
204 * errors go to a coderef and NULL comes back, so the triplet the
205 * client receives is the one the handler built, byte for byte.
206 *
207 * Before any of that, a sampling gate: a per-operation counter, so an
208 * unsampled response costs one increment and one comparison and never
209 * touches the body. Then the skip rules, in order, each with its own
210 * counter - coverage is a reported number, not a silent gap. */
211  
212 #define OA_RV_OFF 0
213 #define OA_RV_REPLACE 1
214 #define OA_RV_REPORT 2
215  
216 /* defined below, with the rest of the response-finalization helpers */
217 static AV *oa_resp_headers(pTHX_ SV *resp);
218  
219 typedef struct oa_rvcfg {
220 int mode; /* OA_RV_* */
221 SV *report; /* coderef for report mode (borrowed), or NULL */
222 IV sample; /* validate 1 response in N; 0/1 = all of them */
223 IV max_body; /* skip bodies over this many bytes; 0 = no cap */
224 } oa_rvcfg;
225  
226 /* the value of a response header, or NULL (borrowed) */
227 1190 static SV *oa_hdr_get(pTHX_ AV *ha, const char *name, STRLEN nl) {
228 1190 ▶ SSize_t i, n = ha ? av_len(ha) + 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
SSize_t i, n = ha ? av_len(ha) + 1 : 0; 1190 0 1190
229 1224 ▶ for (i = 0; i + 1 < n; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < n; i += 2) { 1193 31 1224
230 1193 SV **k = av_fetch(ha, i, 0);
231 1193 ▶ if (k && *k) {
Branch: 2 branches
BranchTrueFalseTotal
if (k && *k) { 1193 0 1193
if (k && *k) { 1193 0 1193
232 1193 STRLEN kl; const char *kp = SvPV_const(*k, kl);
233 1193 ▶ if (oa_ci_eq(kp, kl, name, nl)) {
Branch: 1 branch
BranchTrueFalseTotal
if (oa_ci_eq(kp, kl, name, nl)) { 1159 34 1193
234 1159 SV **v = av_fetch(ha, i + 1, 0);
235 1159 ▶ return (v && *v && SvOK(*v)) ? *v : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (v && *v && SvOK(*v)) ? *v : NULL; 1159 0 1159
return (v && *v && SvOK(*v)) ? *v : NULL; 1159 0 1159
return (v && *v && SvOK(*v)) ? *v : NULL; 1159 0 1159
236 }
237 }
238 }
239 31 return NULL;
240 }
241  
242 /* the declared schema for this status (exact, then `default`), or NULL.
243 * `ctype_ok` reports whether the operation declares a JSON body for it,
244 * which is a different question from whether one was compiled. */
245 1140 static SV *oa_resp_handle(pTHX_ oa_op *o, int status) {
246 char sbuf[8];
247 STRLEN sl;
248 int i;
249 1140 sl = (STRLEN)my_snprintf(sbuf, sizeof sbuf, "%d", status);
250 1438 ▶ for (i = 0; i < o->nresps; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < o->nresps; i++) { 1425 13 1438
251 1425 STRLEN rl; const char *rp = SvPV_const(o->resps[i].status, rl);
252 1425 ▶ if (rl == sl && memEQ(rp, sbuf, sl)) return o->resps[i].handle;
Branch: 2 branches
BranchTrueFalseTotal
if (rl == sl && memEQ(rp, sbuf, sl)) return o->resps[i].handle; 1136 289 1425
if (rl == sl && memEQ(rp, sbuf, sl)) return o->resps[i].handle; 1127 9 1136
253 }
254 19 ▶ for (i = 0; i < o->nresps; i++) { /* a range key: 2XX, 4XX, ... */
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < o->nresps; i++) { /* a range key: 2XX, 4XX, ... */ 12 7 19
255 12 STRLEN rl; const char *rp = SvPV_const(o->resps[i].status, rl);
256 12 ▶ if (oa_status_covers(rp, rl, sbuf, sl)) return o->resps[i].handle;
Branch: 1 branch
BranchTrueFalseTotal
if (oa_status_covers(rp, rl, sbuf, sl)) return o->resps[i].handle; 6 6 12
257 }
258 7 ▶ for (i = 0; i < o->nresps; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < o->nresps; i++) { 4 3 7
259 4 STRLEN rl; const char *rp = SvPV_const(o->resps[i].status, rl);
260 4 ▶ if (rl == 7 && memEQ(rp, "default", 7)) return o->resps[i].handle;
Branch: 2 branches
BranchTrueFalseTotal
if (rl == 7 && memEQ(rp, "default", 7)) return o->resps[i].handle; 4 0 4
if (rl == 7 && memEQ(rp, "default", 7)) return o->resps[i].handle; 4 0 4
261 }
262 3 return NULL;
263 }
264  
265 /* $report->($op_id, $status, \@errors, $env) - never allowed to break the
266 * response, so it runs under G_EVAL and a die is swallowed after a warn. */
267 52 static void oa_rv_report(pTHX_ SV *cb, SV *op_id, int status, AV *errs, SV *env_rv) {
268 52 dSP;
269 52 ▶ if (!cb || !SvOK(cb)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!cb || !SvOK(cb)) return; 15 37 52
if (!cb || !SvOK(cb)) return; 0 15 15
270 15 ENTER; SAVETMPS;
271 15 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 15 15
272 15 ▶ EXTEND(SP, 4);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 4); 0 15 15
273 15 ▶ PUSHs(op_id ? op_id : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(op_id ? op_id : &PL_sv_undef); 15 0 15
274 15 PUSHs(sv_2mortal(newSViv(status)));
275 15 PUSHs(sv_2mortal(newRV_inc((SV *)errs)));
276 15 ▶ PUSHs(env_rv ? env_rv : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(env_rv ? env_rv : &PL_sv_undef); 15 0 15
277 15 PUTBACK;
278 15 (void)call_sv(cb, G_VOID | G_DISCARD | G_EVAL);
279 15 ▶ if (SvTRUE(ERRSV))
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) 15 0 15
if (SvTRUE(ERRSV)) 1 14 15
280 1 ▶ warn("Open::API: response report callback died: %" SVf, SVfARG(ERRSV));
Branch: 1 branch
BranchTrueFalseTotal
warn("Open::API: response report callback died: %" SVf, SVfARG(ERRSV)); 1 0 1
281 15 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 15 0 15
282 }
283  
284 /* The check itself. Returns NULL when there is nothing to answer with -
285 * which is every case in report mode, and the conforming case in replace
286 * mode - or a 500 triplet (+1) for a replace-mode mismatch.
287 *
288 * `out_errs`, when given, receives the error AV (borrowed, mortal) so a
289 * direct caller can have the findings without a callback. */
290 1175 static SV *oa_check_response_cfg(pTHX_ oa_op *o, SV *trip, const oa_rvcfg *rv,
291 SV *env_rv, AV **out_errs) {
292 AV *tv, *ba, *errs, *ha;
293 SV **st, **bd, **b0;
294 SV *handle, *data, *cl;
295 int status;
296 SSize_t j;
297 1175 ▶ if (out_errs) *out_errs = NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (out_errs) *out_errs = NULL; 1135 40 1175
298 1175 ▶ if (!o || rv->mode == OA_RV_OFF || !oa_is_triplet(aTHX_ trip)) return NULL;
Branch: 3 branches
BranchTrueFalseTotal
if (!o || rv->mode == OA_RV_OFF || !oa_is_triplet(aTHX_ trip)) return NULL; 1175 0 1175
if (!o || rv->mode == OA_RV_OFF || !oa_is_triplet(aTHX_ trip)) return NULL; 1175 0 1175
if (!o || rv->mode == OA_RV_OFF || !oa_is_triplet(aTHX_ trip)) return NULL; 0 1175 1175
299  
300 1175 o->rv.total++;
301  
302 /* the sampling gate, before anything touches the body */
303 1175 o->rv.seen++;
304 1175 ▶ if (rv->sample > 1 && (o->rv.seen % (unsigned long)rv->sample) != 0)
Branch: 2 branches
BranchTrueFalseTotal
if (rv->sample > 1 && (o->rv.seen % (unsigned long)rv->sample) != 0) 12 1163 1175
if (rv->sample > 1 && (o->rv.seen % (unsigned long)rv->sample) != 0) 9 3 12
305 9 return NULL;
306 1166 o->rv.sampled++;
307  
308 1166 tv = (AV *)SvRV(trip);
309 1166 st = av_fetch(tv, 0, 0);
310 1166 status = (int)SvIV(*st);
311 1166 ha = oa_resp_headers(aTHX_ trip);
312  
313 /* `errs` is created up front, and every skip below jumps to `verdict`
314 * rather than returning. The declared HEADERS are checked FIRST, above
315 * the body skip rules, because those rules return early for a non-JSON,
316 * oversized or streaming body - which is exactly when a Location or an
317 * X-Rate-Limit header still has to be right. Returning from a skip would
318 * throw away findings already made. */
319 1166 errs = (AV *)sv_2mortal((SV *)newAV());
320  
321 /* 0. declared response headers, by status (exact, range, then default) */
322 1166 ▶ if (o->nrhdrs) {
Branch: 1 branch
BranchTrueFalseTotal
if (o->nrhdrs) { 20 1146 1166
323 char sbuf[8];
324 20 STRLEN sl = (STRLEN)my_snprintf(sbuf, sizeof sbuf, "%d", status);
325 20 int hi, seen_any = 0;
326 42 ▶ for (hi = 0; hi < o->nrhdrs; hi++) {
Branch: 1 branch
BranchTrueFalseTotal
for (hi = 0; hi < o->nrhdrs; hi++) { 22 20 42
327 22 STRLEN rl; const char *rp = SvPV_const(o->rhdrs[hi].status, rl);
328 oa_param *pp;
329 SV *hv_;
330 STRLEN nl; const char *np;
331 22 ▶ if (!(rl == sl && memEQ(rp, sbuf, sl))
Branch: 2 branches
BranchTrueFalseTotal
if (!(rl == sl && memEQ(rp, sbuf, sl)) 22 0 22
if (!(rl == sl && memEQ(rp, sbuf, sl)) 1 21 22
332 1 ▶ && !oa_status_covers(rp, rl, sbuf, sl)
Branch: 1 branch
BranchTrueFalseTotal
&& !oa_status_covers(rp, rl, sbuf, sl) 0 1 1
333 0 ▶ && !(rl == 7 && memEQ(rp, "default", 7)))
Branch: 2 branches
BranchTrueFalseTotal
&& !(rl == 7 && memEQ(rp, "default", 7))) 0 0 0
&& !(rl == 7 && memEQ(rp, "default", 7))) 0 0 0
334 8 continue;
335 22 seen_any = 1;
336 22 pp = &o->rhdrs[hi].p;
337 22 np = SvPV_const(pp->name, nl);
338 22 hv_ = oa_hdr_get(aTHX_ ha, np, nl);
339 22 ▶ if (!hv_ || !SvOK(hv_)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!hv_ || !SvOK(hv_)) { 14 8 22
if (!hv_ || !SvOK(hv_)) { 0 14 14
340 8 ▶ if (pp->required) {
Branch: 1 branch
BranchTrueFalseTotal
if (pp->required) { 5 3 8
341 5 o->rv.hdr_missing++;
342 5 oa_err_push(aTHX_ errs, "response", pp->name, "required",
343 "missing required response header");
344 }
345 8 continue;
346 }
347 /* an array header is split before the check, as a request header
348 * is - comma unless the row carries another delimiter */
349 14 ▶ if (pp->is_array && !SvROK(hv_)) {
Branch: 2 branches
BranchTrueFalseTotal
if (pp->is_array && !SvROK(hv_)) { 9 5 14
if (pp->is_array && !SvROK(hv_)) { 9 0 9
350 9 STRLEN hl; const char *hp = SvPV_const(hv_, hl);
351 9 ▶ hv_ = sv_2mortal(oa_split(aTHX_ hp, hl, pp->delim ? pp->delim : ',', 0, 0));
Branch: 1 branch
BranchTrueFalseTotal
hv_ = sv_2mortal(oa_split(aTHX_ hp, hl, pp->delim ? pp->delim : ',', 0, 0)); 5 4 9
352 9 oa_split_nested(aTHX_ pp, hv_, 0);
353 }
354 14 ▶ if (!oa_check_param(aTHX_ pp, hv_, errs, "response"))
Branch: 1 branch
BranchTrueFalseTotal
if (!oa_check_param(aTHX_ pp, hv_, errs, "response")) 6 8 14
355 6 o->rv.hdr_invalid++;
356 }
357 20 ▶ if (seen_any) o->rv.hdr_checked++;
Branch: 1 branch
BranchTrueFalseTotal
if (seen_any) o->rv.hdr_checked++; 20 0 20
358 }
359  
360 /* 1. not a declared JSON content type */
361 {
362 1166 SV *ct = oa_hdr_get(aTHX_ ha, "content-type", 12);
363 STRLEN ctl; const char *ctp;
364 1167 ▶ if (!ct) { o->rv.skip_ctype++; goto verdict; }
Branch: 1 branch
BranchTrueFalseTotal
if (!ct) { o->rv.skip_ctype++; goto verdict; } 22 1144 1166
365 1144 ctp = SvPV_const(ct, ctl);
366 1144 ▶ if (!oa_ctype_is_json(ctp, ctl)) { o->rv.skip_ctype++; goto verdict; }
Branch: 1 branch
BranchTrueFalseTotal
if (!oa_ctype_is_json(ctp, ctl)) { o->rv.skip_ctype++; goto verdict; } 1 1143 1144
367 }
368  
369 /* 2. Content-Length absent or over the cap. Only with a cap set: without
370 * one there is nothing to be over, and demanding the header would stop
371 * validating the handlers that never set it. */
372 1143 ▶ if (rv->max_body > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (rv->max_body > 0) { 2 1141 1143
373 2 cl = oa_hdr_get(aTHX_ ha, "content-length", 14);
374 2 ▶ if (!cl || !looks_like_number(cl) || SvIV(cl) > rv->max_body) {
Branch: 3 branches
BranchTrueFalseTotal
if (!cl || !looks_like_number(cl) || SvIV(cl) > rv->max_body) { 1 1 2
if (!cl || !looks_like_number(cl) || SvIV(cl) > rv->max_body) { 1 0 1
if (!cl || !looks_like_number(cl) || SvIV(cl) > rv->max_body) { 1 0 1
375 2 o->rv.skip_size++;
376 2 goto verdict;
377 }
378 }
379  
380 /* 3. the body is not a plain scalar: a filehandle, a streaming coderef,
381 * an SSE writer. Never buffered, never measured, forwarded as it is. */
382 1141 bd = av_fetch(tv, 2, 0);
383 1141 ▶ if (!bd || !*bd || !SvROK(*bd) || SvTYPE(SvRV(*bd)) != SVt_PVAV) {
Branch: 4 branches
BranchTrueFalseTotal
if (!bd || !*bd || !SvROK(*bd) || SvTYPE(SvRV(*bd)) != SVt_PVAV) { 1141 0 1141
if (!bd || !*bd || !SvROK(*bd) || SvTYPE(SvRV(*bd)) != SVt_PVAV) { 1141 0 1141
if (!bd || !*bd || !SvROK(*bd) || SvTYPE(SvRV(*bd)) != SVt_PVAV) { 1141 0 1141
if (!bd || !*bd || !SvROK(*bd) || SvTYPE(SvRV(*bd)) != SVt_PVAV) { 1 1140 1141
384 1 o->rv.skip_body++;
385 1 goto verdict;
386 }
387 1140 ba = (AV *)SvRV(*bd);
388 1140 b0 = av_fetch(ba, 0, 0);
389 1140 ▶ if (!b0 || !*b0 || !SvOK(*b0) || SvROK(*b0)) {
Branch: 4 branches
BranchTrueFalseTotal
if (!b0 || !*b0 || !SvOK(*b0) || SvROK(*b0)) { 1140 0 1140
if (!b0 || !*b0 || !SvOK(*b0) || SvROK(*b0)) { 1140 0 1140
if (!b0 || !*b0 || !SvOK(*b0) || SvROK(*b0)) { 1140 0 1140
if (!b0 || !*b0 || !SvOK(*b0) || SvROK(*b0)) { 0 1140 1140
390 0 o->rv.skip_body++;
391 0 goto verdict;
392 }
393  
394 /* 4. the status declares no schema */
395 1140 handle = oa_resp_handle(aTHX_ o, status);
396 1140 ▶ if (!handle) { o->rv.skip_schema++; goto verdict; }
Branch: 1 branch
BranchTrueFalseTotal
if (!handle) { o->rv.skip_schema++; goto verdict; } 3 1137 1140
397  
398 1137 data = oa_body_decode(aTHX_ *b0);
399 1137 ▶ if (!data) { o->rv.skip_decode++; goto verdict; }
Branch: 1 branch
BranchTrueFalseTotal
if (!data) { o->rv.skip_decode++; goto verdict; } 0 1137 1137
400  
401 1137 o->rv.checked++;
402 1137 (void)JSF->validate(aTHX_ handle, data, errs);
403  
404 1166 verdict:
405 1166 ▶ if (av_len(errs) < 0) return NULL; /* nothing found, body or header */
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(errs) < 0) return NULL; /* nothing found, body or header */ 1111 55 1166
406  
407 55 o->rv.violations++;
408 124 ▶ for (j = 0; j <= av_len(errs); j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j <= av_len(errs); j++) { 69 55 124
409 69 SV **e = av_fetch(errs, j, 0);
410 69 ▶ HV *h = (e && *e && SvROK(*e)) ? (HV *)SvRV(*e) : NULL;
Branch: 3 branches
BranchTrueFalseTotal
HV *h = (e && *e && SvROK(*e)) ? (HV *)SvRV(*e) : NULL; 69 0 69
HV *h = (e && *e && SvROK(*e)) ? (HV *)SvRV(*e) : NULL; 69 0 69
HV *h = (e && *e && SvROK(*e)) ? (HV *)SvRV(*e) : NULL; 69 0 69
411 69 ▶ if (h) (void)hv_stores(h, "in", newSVpvs("response"));
Branch: 1 branch
BranchTrueFalseTotal
if (h) (void)hv_stores(h, "in", newSVpvs("response")); 69 0 69
412 }
413 55 ▶ if (out_errs) *out_errs = errs;
Branch: 1 branch
BranchTrueFalseTotal
if (out_errs) *out_errs = errs; 37 18 55
414  
415 55 ▶ if (rv->mode == OA_RV_REPORT) {
Branch: 1 branch
BranchTrueFalseTotal
if (rv->mode == OA_RV_REPORT) { 52 3 55
416 52 oa_rv_report(aTHX_ rv->report, o->op_id, status, errs, env_rv);
417 52 return NULL; /* the client's bytes are not ours to edit */
418 }
419 3 return oa_error_response(aTHX_ 500, errs);
420 }
421  
422 /* The coverage counters as a hash (+1 owned by the caller). */
423 51 static HV *oa_rv_hv(pTHX_ const oa_rvstat *s) {
424 51 HV *h = newHV();
425 51 (void)hv_stores(h, "total", newSVuv(s->total));
426 51 (void)hv_stores(h, "sampled", newSVuv(s->sampled));
427 51 (void)hv_stores(h, "checked", newSVuv(s->checked));
428 51 (void)hv_stores(h, "violations", newSVuv(s->violations));
429 51 (void)hv_stores(h, "skip_ctype", newSVuv(s->skip_ctype));
430 51 (void)hv_stores(h, "skip_size", newSVuv(s->skip_size));
431 51 (void)hv_stores(h, "skip_body", newSVuv(s->skip_body));
432 51 (void)hv_stores(h, "skip_schema", newSVuv(s->skip_schema));
433 51 (void)hv_stores(h, "skip_decode", newSVuv(s->skip_decode));
434 51 (void)hv_stores(h, "unsampled", newSVuv(s->total - s->sampled));
435 51 return h;
436 }
437  
438 /* The request path's version: the mode comes from its own capture slot, the
439 * report callback and the sampling settings from the options HV. */
440 40 static void oa_rvcfg_from(pTHX_ int vresp, HV *opts, oa_rvcfg *rv) {
441 SV **v;
442 40 rv->mode = vresp; rv->report = NULL; rv->sample = 1; rv->max_body = 0;
443 40 ▶ if (!opts) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!opts) return; 0 40 40
444 40 ▶ if ((v = hv_fetchs(opts, "response_report", 0)) && *v && SvOK(*v))
Branch: 3 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "response_report", 0)) && *v && SvOK(*v)) 37 3 40
if ((v = hv_fetchs(opts, "response_report", 0)) && *v && SvOK(*v)) 37 0 37
if ((v = hv_fetchs(opts, "response_report", 0)) && *v && SvOK(*v)) 37 0 37
445 37 rv->report = *v;
446 40 ▶ if ((v = hv_fetchs(opts, "response_sample", 0)) && *v && SvOK(*v))
Branch: 3 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "response_sample", 0)) && *v && SvOK(*v)) 12 28 40
if ((v = hv_fetchs(opts, "response_sample", 0)) && *v && SvOK(*v)) 12 0 12
if ((v = hv_fetchs(opts, "response_sample", 0)) && *v && SvOK(*v)) 12 0 12
447 12 rv->sample = SvIV(*v);
448 40 ▶ if ((v = hv_fetchs(opts, "response_max_body", 0)) && *v && SvOK(*v))
Branch: 3 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "response_max_body", 0)) && *v && SvOK(*v)) 2 38 40
if ((v = hv_fetchs(opts, "response_max_body", 0)) && *v && SvOK(*v)) 2 0 2
if ((v = hv_fetchs(opts, "response_max_body", 0)) && *v && SvOK(*v)) 2 0 2
449 2 rv->max_body = SvIV(*v);
450 }
451  
452 /* Check with the configured mode. NULL unless replace mode found a
453 * mismatch, in which case the 500 that replaces the response (+1). */
454 40 static SV *oa_check_response_opts(pTHX_ oa_op *o, SV *trip, int vresp,
455 HV *opts, SV *env_rv) {
456 oa_rvcfg rv;
457 /* deliberately no `!o->nresps` shortcut: an operation whose declared
458 * statuses carry no schema still counts its responses and attributes
459 * them to skip_schema. Silence there would read as coverage. */
460 40 ▶ if (!o || !vresp) return NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (!o || !vresp) return NULL; 40 0 40
if (!o || !vresp) return NULL; 0 40 40
461 40 oa_rvcfg_from(aTHX_ vresp, opts, &rv);
462 40 return oa_check_response_cfg(aTHX_ o, trip, &rv, env_rv, NULL);
463 }
464  
465 /* ---- response finalization (security headers, CORS, problem+json) ----------------- */
466  
467 /* case-insensitive: does the header AV already carry `name`? */
468 2524 static int oa_hdr_has(pTHX_ AV *ha, const char *name, STRLEN nl) {
469 2524 SSize_t i, n = av_len(ha) + 1;
470 9037 ▶ for (i = 0; i + 1 < n; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < n; i += 2) { 6514 2523 9037
471 6514 SV **k = av_fetch(ha, i, 0);
472 6514 ▶ if (k && *k) {
Branch: 2 branches
BranchTrueFalseTotal
if (k && *k) { 6514 0 6514
if (k && *k) { 6514 0 6514
473 6514 STRLEN kl; const char *kp = SvPV_const(*k, kl);
474 6514 STRLEN j; int eq = (kl == nl);
475 7157 ▶ for (j = 0; eq && j < kl; j++)
Branch: 2 branches
BranchTrueFalseTotal
for (j = 0; eq && j < kl; j++) 644 6513 7157
for (j = 0; eq && j < kl; j++) 643 1 644
476 643 ▶ if (toLOWER((U8)kp[j]) != toLOWER((U8)name[j])) eq = 0;
Branch: 3 branches
BranchTrueFalseTotal
if (toLOWER((U8)kp[j]) != toLOWER((U8)name[j])) eq = 0; 631 12 643
if (toLOWER((U8)kp[j]) != toLOWER((U8)name[j])) eq = 0; 631 12 643
if (toLOWER((U8)kp[j]) != toLOWER((U8)name[j])) eq = 0; 628 15 643
477 6514 ▶ if (eq) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (eq) return 1; 1 6513 6514
478 }
479 }
480 2523 return 0;
481 }
482  
483 /* the triplet's header AV, or NULL */
484 1807 static AV *oa_resp_headers(pTHX_ SV *resp) {
485 AV *tv; SV **hh;
486 1807 ▶ if (!oa_is_triplet(aTHX_ resp)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!oa_is_triplet(aTHX_ resp)) return NULL; 0 1807 1807
487 1807 tv = (AV *)SvRV(resp);
488 1807 hh = av_fetch(tv, 1, 0);
489 1807 ▶ return (hh && *hh && SvROK(*hh)) ? (AV *)SvRV(*hh) : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (hh && *hh && SvROK(*hh)) ? (AV *)SvRV(*hh) : NULL; 1807 0 1807
return (hh && *hh && SvROK(*hh)) ? (AV *)SvRV(*hh) : NULL; 1807 0 1807
return (hh && *hh && SvROK(*hh)) ? (AV *)SvRV(*hh) : NULL; 1807 0 1807
490 }
491  
492 /* push name => value (borrowed name, value copied) */
493 2529 static void oa_hdr_push(pTHX_ AV *ha, const char *name, SV *val) {
494 2529 av_push(ha, newSVpv(name, 0));
495 2529 av_push(ha, newSVsv(val));
496 2529 }
497  
498 /* join an AV of strings with ", " (mortal SV), NULL when empty */
499 1 static SV *oa_join_csv(pTHX_ AV *av) {
500 1 ▶ SSize_t i, n = av ? av_len(av) + 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
SSize_t i, n = av ? av_len(av) + 1 : 0; 1 0 1
501 SV *out;
502 1 ▶ if (n <= 0) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return NULL; 0 1 1
503 1 out = sv_2mortal(newSVpvs(""));
504 3 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 2 1 3
505 2 SV **e = av_fetch(av, i, 0);
506 2 ▶ if (!e || !*e) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!e || !*e) continue; 2 0 2
if (!e || !*e) continue; 0 2 2
507 2 ▶ if (SvCUR(out)) sv_catpvs(out, ", ");
Branch: 1 branch
BranchTrueFalseTotal
if (SvCUR(out)) sv_catpvs(out, ", "); 1 1 2
508 2 sv_catsv(out, *e);
509 }
510 1 return out;
511 }
512  
513 #define OA_HAS(ha, lit) oa_hdr_has(aTHX_ (ha), "" lit, sizeof(lit) - 1)
514  
515 /* apply the configured header set (set-if-absent, so a handler or the after
516 * hook keeps the last word) to a triplet response */
517 629 static void oa_apply_headers(pTHX_ SV *resp, HV *hdrs) {
518 629 AV *ha = oa_resp_headers(aTHX_ resp);
519 HE *he;
520 629 ▶ if (!ha || !hdrs) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!ha || !hdrs) return; 629 0 629
if (!ha || !hdrs) return; 0 629 629
521 629 hv_iterinit(hdrs);
522 3145 ▶ while ((he = hv_iternext(hdrs))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(hdrs))) { 2516 629 3145
523 2516 I32 kl; const char *k = hv_iterkey(he, &kl);
524 2516 ▶ if (!oa_hdr_has(aTHX_ ha, k, (STRLEN)kl))
Branch: 1 branch
BranchTrueFalseTotal
if (!oa_hdr_has(aTHX_ ha, k, (STRLEN)kl)) 2515 1 2516
525 2515 oa_hdr_push(aTHX_ ha, k, hv_iterval(hdrs, he));
526 }
527 }
528  
529 /* Finalize every outgoing triplet: convert error envelopes to problem+json
530 * (opt-in), add CORS response headers for an allowed cross-origin request,
531 * then stamp the security header set. Called at each exit and, for async
532 * handlers, when the future resolves. opts may be NULL. */
533 static void oa_cors_actual(pTHX_ SV *resp, SV *env_rv, HV *cors); /* below */
534 static void oa_to_problem(pTHX_ SV *resp); /* below */
535  
536 629 static void oa_finalize(pTHX_ SV *resp, SV *env_rv, HV *opts) {
537 SV **v;
538 SV *setcookie;
539 629 ▶ if (!oa_is_triplet(aTHX_ resp)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!oa_is_triplet(aTHX_ resp)) return; 0 629 629
540 /* CSRF cookie rotation from a check callback (independent of opts, so it
541 * applies on the async path and even when no other option is set) */
542 629 ▶ if ((setcookie = oa_env_get(aTHX_ (HV *)SvRV(env_rv), "openapi.csrf.setcookie"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((setcookie = oa_env_get(aTHX_ (HV *)SvRV(env_rv), "openapi.csrf.setcookie"))) { 4 625 629
543 4 AV *ha = oa_resp_headers(aTHX_ resp);
544 4 ▶ if (ha) oa_hdr_push(aTHX_ ha, "Set-Cookie", setcookie);
Branch: 1 branch
BranchTrueFalseTotal
if (ha) oa_hdr_push(aTHX_ ha, "Set-Cookie", setcookie); 4 0 4
545 }
546 629 ▶ if (!opts) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!opts) return; 0 629 629
547 629 ▶ if ((v = hv_fetchs(opts, "error_format", 0)) && *v && SvOK(*v)) {
Branch: 3 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "error_format", 0)) && *v && SvOK(*v)) { 3 626 629
if ((v = hv_fetchs(opts, "error_format", 0)) && *v && SvOK(*v)) { 3 0 3
if ((v = hv_fetchs(opts, "error_format", 0)) && *v && SvOK(*v)) { 3 0 3
548 3 STRLEN l; const char *p = SvPV_const(*v, l);
549 3 ▶ if (l == 7 && memEQ(p, "problem", 7)) oa_to_problem(aTHX_ resp);
Branch: 2 branches
BranchTrueFalseTotal
if (l == 7 && memEQ(p, "problem", 7)) oa_to_problem(aTHX_ resp); 3 0 3
if (l == 7 && memEQ(p, "problem", 7)) oa_to_problem(aTHX_ resp); 3 0 3
550 }
551 629 ▶ if ((v = hv_fetchs(opts, "cors", 0)) && *v && SvROK(*v))
Branch: 3 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "cors", 0)) && *v && SvROK(*v)) 5 624 629
if ((v = hv_fetchs(opts, "cors", 0)) && *v && SvROK(*v)) 5 0 5
if ((v = hv_fetchs(opts, "cors", 0)) && *v && SvROK(*v)) 5 0 5
552 5 oa_cors_actual(aTHX_ resp, env_rv, (HV *)SvRV(*v));
553 629 ▶ if ((v = hv_fetchs(opts, "headers", 0)) && *v && SvROK(*v))
Branch: 3 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "headers", 0)) && *v && SvROK(*v)) 629 0 629
if ((v = hv_fetchs(opts, "headers", 0)) && *v && SvROK(*v)) 629 0 629
if ((v = hv_fetchs(opts, "headers", 0)) && *v && SvROK(*v)) 629 0 629
554 629 oa_apply_headers(aTHX_ resp, (HV *)SvRV(*v));
555 }
556  
557 /* finalize and return - a function (not a macro) so the response expression
558 * is evaluated exactly once at each exit */
559 627 static SV *oa_fin(pTHX_ SV *resp, SV *env_rv, HV *opts) {
560 627 oa_finalize(aTHX_ resp, env_rv, opts);
561 627 return resp;
562 }
563  
564 /* reason phrase for the statuses this layer emits */
565 2 static const char *oa_reason(int s) {
566 2 switch (s) {
567 1 case 400: return "Bad Request";
568 0 case 401: return "Unauthorized";
569 0 case 403: return "Forbidden";
570 1 case 404: return "Not Found";
571 0 case 405: return "Method Not Allowed";
572 0 case 406: return "Not Acceptable";
573 0 case 413: return "Payload Too Large";
574 0 case 415: return "Unsupported Media Type";
575 0 case 500: return "Internal Server Error";
576 0 case 501: return "Not Implemented";
577 0 default: return "Error";
578 }
579 }
580  
581 /* Rewrite our JSON error envelope { errors => [...] } into an RFC 7807
582 * application/problem+json body. Only touches a >=400 triplet whose body is
583 * our application/json envelope; a handler's own error body is left alone. */
584 3 static void oa_to_problem(pTHX_ SV *resp) {
585 3 AV *tv = (AV *)SvRV(resp);
586 3 SV **st = av_fetch(tv, 0, 0);
587 3 AV *ha = oa_resp_headers(aTHX_ resp);
588 SV **bd, **b0, **errs;
589 AV *ba;
590 SV *data, *enc;
591 HV *src, *prob;
592 3 int status, is_json = 0;
593 SSize_t i, n;
594  
595 3 ▶ if (!st || !*st || !ha) return;
Branch: 3 branches
BranchTrueFalseTotal
if (!st || !*st || !ha) return; 3 0 3
if (!st || !*st || !ha) return; 3 0 3
if (!st || !*st || !ha) return; 0 3 3
596 3 status = (int)SvIV(*st);
597 3 ▶ if (status < 400) return;
Branch: 1 branch
BranchTrueFalseTotal
if (status < 400) return; 1 2 3
598  
599 2 n = av_len(ha) + 1;
600 2 ▶ for (i = 0; i + 1 < n; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < n; i += 2) { 2 0 2
601 2 SV **k = av_fetch(ha, i, 0), **v = av_fetch(ha, i + 1, 0);
602 2 ▶ if (k && *k && v && *v) {
Branch: 4 branches
BranchTrueFalseTotal
if (k && *k && v && *v) { 2 0 2
if (k && *k && v && *v) { 2 0 2
if (k && *k && v && *v) { 2 0 2
if (k && *k && v && *v) { 2 0 2
603 2 STRLEN kl; const char *kp = SvPV_const(*k, kl);
604 2 ▶ if (oa_ci_eq(kp, kl, "content-type", 12)) {
Branch: 1 branch
BranchTrueFalseTotal
if (oa_ci_eq(kp, kl, "content-type", 12)) { 2 0 2
605 2 STRLEN vl; const char *vp = SvPV_const(*v, vl);
606 2 ▶ is_json = (vl >= 16 && memEQ(vp, "application/json", 16)
Branch: 1 branch
BranchTrueFalseTotal
is_json = (vl >= 16 && memEQ(vp, "application/json", 16) 2 0 2
607 4 ▶ && (vl == 16 || vp[16] == ';'));
Branch: 3 branches
BranchTrueFalseTotal
&& (vl == 16 || vp[16] == ';')); 2 0 2
&& (vl == 16 || vp[16] == ';')); 0 2 2
&& (vl == 16 || vp[16] == ';')); 0 0 0
608 2 break;
609 }
610 }
611 }
612 2 ▶ if (!is_json) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!is_json) return; 0 2 2
613  
614 2 bd = av_fetch(tv, 2, 0);
615 2 ▶ if (!bd || !*bd || !SvROK(*bd) || SvTYPE(SvRV(*bd)) != SVt_PVAV) return;
Branch: 4 branches
BranchTrueFalseTotal
if (!bd || !*bd || !SvROK(*bd) || SvTYPE(SvRV(*bd)) != SVt_PVAV) return; 2 0 2
if (!bd || !*bd || !SvROK(*bd) || SvTYPE(SvRV(*bd)) != SVt_PVAV) return; 2 0 2
if (!bd || !*bd || !SvROK(*bd) || SvTYPE(SvRV(*bd)) != SVt_PVAV) return; 2 0 2
if (!bd || !*bd || !SvROK(*bd) || SvTYPE(SvRV(*bd)) != SVt_PVAV) return; 0 2 2
616 2 ba = (AV *)SvRV(*bd);
617 2 b0 = av_fetch(ba, 0, 0);
618 2 ▶ if (!b0 || !*b0 || !SvOK(*b0)) return;
Branch: 3 branches
BranchTrueFalseTotal
if (!b0 || !*b0 || !SvOK(*b0)) return; 2 0 2
if (!b0 || !*b0 || !SvOK(*b0)) return; 2 0 2
if (!b0 || !*b0 || !SvOK(*b0)) return; 0 2 2
619 2 data = oa_body_decode(aTHX_ *b0); /* mortal, or NULL */
620 2 ▶ if (!data || !SvROK(data) || SvTYPE(SvRV(data)) != SVt_PVHV) return;
Branch: 3 branches
BranchTrueFalseTotal
if (!data || !SvROK(data) || SvTYPE(SvRV(data)) != SVt_PVHV) return; 2 0 2
if (!data || !SvROK(data) || SvTYPE(SvRV(data)) != SVt_PVHV) return; 2 0 2
if (!data || !SvROK(data) || SvTYPE(SvRV(data)) != SVt_PVHV) return; 0 2 2
621 2 src = (HV *)SvRV(data);
622 2 errs = hv_fetchs(src, "errors", 0);
623 /* the errors AV marks OUR envelope; a handler's own JSON error body
624 * (no errors key) is left alone, as promised above */
625 2 ▶ if (!(errs && *errs && SvROK(*errs) && SvTYPE(SvRV(*errs)) == SVt_PVAV))
Branch: 4 branches
BranchTrueFalseTotal
if (!(errs && *errs && SvROK(*errs) && SvTYPE(SvRV(*errs)) == SVt_PVAV)) 2 0 2
if (!(errs && *errs && SvROK(*errs) && SvTYPE(SvRV(*errs)) == SVt_PVAV)) 2 0 2
if (!(errs && *errs && SvROK(*errs) && SvTYPE(SvRV(*errs)) == SVt_PVAV)) 2 0 2
if (!(errs && *errs && SvROK(*errs) && SvTYPE(SvRV(*errs)) == SVt_PVAV)) 0 2 2
626 0 return;
627 2 prob = newHV();
628 2 (void)hv_stores(prob, "type", newSVpvs("about:blank"));
629 2 (void)hv_stores(prob, "title", newSVpv(oa_reason(status), 0));
630 2 (void)hv_stores(prob, "status", newSViv(status));
631 2 (void)hv_stores(prob, "errors", newSVsv(*errs));
632 {
633 2 AV *ea = (AV *)SvRV(*errs);
634 2 SV **e0 = av_fetch(ea, 0, 0);
635 2 ▶ if (e0 && *e0 && SvROK(*e0) && SvTYPE(SvRV(*e0)) == SVt_PVHV) {
Branch: 4 branches
BranchTrueFalseTotal
if (e0 && *e0 && SvROK(*e0) && SvTYPE(SvRV(*e0)) == SVt_PVHV) { 2 0 2
if (e0 && *e0 && SvROK(*e0) && SvTYPE(SvRV(*e0)) == SVt_PVHV) { 2 0 2
if (e0 && *e0 && SvROK(*e0) && SvTYPE(SvRV(*e0)) == SVt_PVHV) { 2 0 2
if (e0 && *e0 && SvROK(*e0) && SvTYPE(SvRV(*e0)) == SVt_PVHV) { 2 0 2
636 2 SV **m = hv_fetchs((HV *)SvRV(*e0), "message", 0);
637 2 ▶ if (m && *m && SvOK(*m)) (void)hv_stores(prob, "detail", newSVsv(*m));
Branch: 3 branches
BranchTrueFalseTotal
if (m && *m && SvOK(*m)) (void)hv_stores(prob, "detail", newSVsv(*m)); 2 0 2
if (m && *m && SvOK(*m)) (void)hv_stores(prob, "detail", newSVsv(*m)); 2 0 2
if (m && *m && SvOK(*m)) (void)hv_stores(prob, "detail", newSVsv(*m)); 2 0 2
638 }
639 }
640 2 enc = oa_json_encode(aTHX_ sv_2mortal(newRV_noinc((SV *)prob)));
641 2 ▶ if (!enc) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!enc) return; 0 2 2
642 2 (void)av_store(ba, 0, newSVsv(enc));
643 2 ▶ if (av_len(ba) > 0) av_fill(ba, 0); /* one chunk now */
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(ba) > 0) av_fill(ba, 0); /* one chunk now */ 0 2 2
644 2 ▶ for (i = 0; i + 1 < n; i += 2) { /* switch the content-type */
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < n; i += 2) { /* switch the content-type */ 2 0 2
645 2 SV **k = av_fetch(ha, i, 0);
646 2 ▶ if (k && *k) {
Branch: 2 branches
BranchTrueFalseTotal
if (k && *k) { 2 0 2
if (k && *k) { 2 0 2
647 2 STRLEN kl; const char *kp = SvPV_const(*k, kl);
648 2 ▶ if (oa_ci_eq(kp, kl, "content-type", 12)) {
Branch: 1 branch
BranchTrueFalseTotal
if (oa_ci_eq(kp, kl, "content-type", 12)) { 2 0 2
649 2 (void)av_store(ha, i + 1,
650 newSVpvs("application/problem+json"));
651 2 break;
652 }
653 }
654 }
655 }
656  
657 /* Add CORS headers to a non-preflight response when the request carries an
658 * allowed Origin. cors config: origins ('*' or an AV of exact origins),
659 * credentials (bool), expose (AV of header names). */
660 5 static void oa_cors_actual(pTHX_ SV *resp, SV *env_rv, HV *cors) {
661 5 HV *env = (HV *)SvRV(env_rv);
662 5 SV *origin = oa_env_get(aTHX_ env, "HTTP_ORIGIN");
663 5 AV *ha = oa_resp_headers(aTHX_ resp);
664 SV **v, *allow_val;
665 5 int allow = 0, wildcard = 0, creds;
666  
667 5 ▶ if (!origin || !ha) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!origin || !ha) return; 5 0 5
if (!origin || !ha) return; 0 5 5
668 5 v = hv_fetchs(cors, "credentials", 0);
669 5 ▶ creds = (v && *v && SvTRUE(*v));
Branch: 3 branches
BranchTrueFalseTotal
creds = (v && *v && SvTRUE(*v)); 5 0 5
creds = (v && *v && SvTRUE(*v)); 5 0 5
creds = (v && *v && SvTRUE(*v)); 1 4 5
670  
671 5 v = hv_fetchs(cors, "origins", 0);
672 5 ▶ if (v && *v) {
Branch: 2 branches
BranchTrueFalseTotal
if (v && *v) { 5 0 5
if (v && *v) { 5 0 5
673 5 ▶ if (!SvROK(*v)) { /* '*', or one exact origin */
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(*v)) { /* '*', or one exact origin */ 1 4 5
674 2 ▶ STRLEN l; const char *p = SvPV_const(*v, l);
Branch: 1 branch
BranchTrueFalseTotal
STRLEN l; const char *p = SvPV_const(*v, l); 1 0 1
675 1 STRLEN ol; const char *op = SvPV_const(origin, ol);
676 1 ▶ if (l == 1 && *p == '*') { allow = 1; wildcard = 1; }
Branch: 2 branches
BranchTrueFalseTotal
if (l == 1 && *p == '*') { allow = 1; wildcard = 1; } 1 0 1
if (l == 1 && *p == '*') { allow = 1; wildcard = 1; } 1 0 1
677 0 ▶ else if (l == ol && memEQ(p, op, ol)) allow = 1;
Branch: 2 branches
BranchTrueFalseTotal
else if (l == ol && memEQ(p, op, ol)) allow = 1; 0 0 0
else if (l == ol && memEQ(p, op, ol)) allow = 1; 0 0 0
678 4 ▶ } else if (SvTYPE(SvRV(*v)) == SVt_PVAV) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (SvTYPE(SvRV(*v)) == SVt_PVAV) { 4 0 4
679 4 AV *list = (AV *)SvRV(*v);
680 4 STRLEN ol; const char *op = SvPV_const(origin, ol);
681 4 SSize_t i, n = av_len(list) + 1;
682 5 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 4 1 5
683 4 SV **e = av_fetch(list, i, 0);
684 STRLEN el; const char *ep;
685 4 ▶ if (!e || !*e) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!e || !*e) continue; 4 0 4
if (!e || !*e) continue; 0 4 4
686 4 ep = SvPV_const(*e, el);
687 7 ▶ if (el == 1 && *ep == '*') { allow = 1; wildcard = 1; break; }
Branch: 2 branches
BranchTrueFalseTotal
if (el == 1 && *ep == '*') { allow = 1; wildcard = 1; break; } 0 4 4
if (el == 1 && *ep == '*') { allow = 1; wildcard = 1; break; } 0 0 0
688 4 ▶ if (el == ol && memEQ(ep, op, ol)) { allow = 1; break; }
Branch: 2 branches
BranchTrueFalseTotal
if (el == ol && memEQ(ep, op, ol)) { allow = 1; break; } 3 1 4
if (el == ol && memEQ(ep, op, ol)) { allow = 1; break; } 3 0 3
689 }
690 }
691 }
692 5 ▶ if (!allow) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!allow) return; 1 4 5
693  
694 /* credentials forbid a wildcard ACAO: echo the concrete origin */
695 4 ▶ allow_val = (wildcard && !creds) ? sv_2mortal(newSVpvs("*")) : origin;
Branch: 2 branches
BranchTrueFalseTotal
allow_val = (wildcard && !creds) ? sv_2mortal(newSVpvs("*")) : origin; 1 3 4
allow_val = (wildcard && !creds) ? sv_2mortal(newSVpvs("*")) : origin; 1 0 1
696 4 ▶ if (!OA_HAS(ha, "Access-Control-Allow-Origin"))
Branch: 1 branch
BranchTrueFalseTotal
if (!OA_HAS(ha, "Access-Control-Allow-Origin")) 4 0 4
697 4 oa_hdr_push(aTHX_ ha, "Access-Control-Allow-Origin", allow_val);
698 4 ▶ if (!wildcard && !OA_HAS(ha, "Vary"))
Branch: 2 branches
BranchTrueFalseTotal
if (!wildcard && !OA_HAS(ha, "Vary")) 3 1 4
if (!wildcard && !OA_HAS(ha, "Vary")) 3 0 3
699 3 oa_hdr_push(aTHX_ ha, "Vary", sv_2mortal(newSVpvs("Origin")));
700 4 ▶ if (creds && !OA_HAS(ha, "Access-Control-Allow-Credentials"))
Branch: 2 branches
BranchTrueFalseTotal
if (creds && !OA_HAS(ha, "Access-Control-Allow-Credentials")) 1 3 4
if (creds && !OA_HAS(ha, "Access-Control-Allow-Credentials")) 1 0 1
701 1 oa_hdr_push(aTHX_ ha, "Access-Control-Allow-Credentials",
702 sv_2mortal(newSVpvs("true")));
703 4 v = hv_fetchs(cors, "expose", 0);
704 4 ▶ if (v && *v && SvROK(*v) && SvTYPE(SvRV(*v)) == SVt_PVAV) {
Branch: 4 branches
BranchTrueFalseTotal
if (v && *v && SvROK(*v) && SvTYPE(SvRV(*v)) == SVt_PVAV) { 0 4 4
if (v && *v && SvROK(*v) && SvTYPE(SvRV(*v)) == SVt_PVAV) { 0 0 0
if (v && *v && SvROK(*v) && SvTYPE(SvRV(*v)) == SVt_PVAV) { 0 0 0
if (v && *v && SvROK(*v) && SvTYPE(SvRV(*v)) == SVt_PVAV) { 0 0 0
705 0 SV *joined = oa_join_csv(aTHX_ (AV *)SvRV(*v));
706 0 ▶ if (joined && !OA_HAS(ha, "Access-Control-Expose-Headers"))
Branch: 2 branches
BranchTrueFalseTotal
if (joined && !OA_HAS(ha, "Access-Control-Expose-Headers")) 0 0 0
if (joined && !OA_HAS(ha, "Access-Control-Expose-Headers")) 0 0 0
707 0 oa_hdr_push(aTHX_ ha, "Access-Control-Expose-Headers", joined);
708 }
709 }
710  
711 /* Build a CORS preflight (204) response for an OPTIONS request against a known
712 * path: Allow-Methods from the router's Allow list (the declared methods),
713 * Allow-Headers echoed from the request or configured, and Max-Age. The
714 * Allow-Origin / credentials headers are added by oa_cors_actual in finalize.
715 * (+1) */
716 1 static SV *oa_cors_preflight(pTHX_ SV *env_rv, HV *cors, AV *allow) {
717 1 HV *env = (HV *)SvRV(env_rv);
718 1 AV *h = newAV(), *b = newAV(), *r = newAV();
719 1 SV **v, *methods, *val = NULL;
720  
721 1 av_push(r, newSViv(204));
722 1 av_push(r, newRV_noinc((SV *)h));
723 1 av_push(b, newSVpvs(""));
724 1 av_push(r, newRV_noinc((SV *)b));
725  
726 /* Allow-Methods: the declared methods (the router uppercases them),
727 * else echo the requested one */
728 1 methods = oa_join_csv(aTHX_ allow);
729 1 ▶ if (!methods)
Branch: 1 branch
BranchTrueFalseTotal
if (!methods) 0 1 1
730 0 methods = oa_env_get(aTHX_ env, "HTTP_ACCESS_CONTROL_REQUEST_METHOD");
731 1 ▶ if (methods) oa_hdr_push(aTHX_ h, "Access-Control-Allow-Methods", methods);
Branch: 1 branch
BranchTrueFalseTotal
if (methods) oa_hdr_push(aTHX_ h, "Access-Control-Allow-Methods", methods); 1 0 1
732  
733 /* Allow-Headers: configured list, else echo the requested set */
734 1 v = hv_fetchs(cors, "headers", 0);
735 1 ▶ if (v && *v && SvROK(*v) && SvTYPE(SvRV(*v)) == SVt_PVAV)
Branch: 4 branches
BranchTrueFalseTotal
if (v && *v && SvROK(*v) && SvTYPE(SvRV(*v)) == SVt_PVAV) 0 1 1
if (v && *v && SvROK(*v) && SvTYPE(SvRV(*v)) == SVt_PVAV) 0 0 0
if (v && *v && SvROK(*v) && SvTYPE(SvRV(*v)) == SVt_PVAV) 0 0 0
if (v && *v && SvROK(*v) && SvTYPE(SvRV(*v)) == SVt_PVAV) 0 0 0
736 0 val = oa_join_csv(aTHX_ (AV *)SvRV(*v));
737 1 ▶ else if (v && *v && SvOK(*v) && !SvROK(*v))
Branch: 4 branches
BranchTrueFalseTotal
else if (v && *v && SvOK(*v) && !SvROK(*v)) 0 1 1
else if (v && *v && SvOK(*v) && !SvROK(*v)) 0 0 0
else if (v && *v && SvOK(*v) && !SvROK(*v)) 0 0 0
else if (v && *v && SvOK(*v) && !SvROK(*v)) 0 0 0
738 0 val = *v;
739 1 ▶ if (!val)
Branch: 1 branch
BranchTrueFalseTotal
if (!val) 1 0 1
740 1 val = oa_env_get(aTHX_ env, "HTTP_ACCESS_CONTROL_REQUEST_HEADERS");
741 1 ▶ if (val) oa_hdr_push(aTHX_ h, "Access-Control-Allow-Headers", val);
Branch: 1 branch
BranchTrueFalseTotal
if (val) oa_hdr_push(aTHX_ h, "Access-Control-Allow-Headers", val); 0 1 1
742  
743 1 ▶ if ((v = hv_fetchs(cors, "max_age", 0)) && *v && SvOK(*v))
Branch: 3 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(cors, "max_age", 0)) && *v && SvOK(*v)) 1 0 1
if ((v = hv_fetchs(cors, "max_age", 0)) && *v && SvOK(*v)) 1 0 1
if ((v = hv_fetchs(cors, "max_age", 0)) && *v && SvOK(*v)) 1 0 1
744 1 oa_hdr_push(aTHX_ h, "Access-Control-Max-Age", *v);
745  
746 1 return newRV_noinc((SV *)r);
747 }
748  
749 /* ---- content negotiation (opt-in: 415 request type, 406 Accept) ------------------- */
750  
751 /* compare two media types ignoring parameters, list separators and space */
752 1 static int oa_media_eq(const char *a, STRLEN al, const char *b, STRLEN bl) {
753 1 STRLEN i = 0, j = 0, ie, je;
754 1 ▶ while (i < al && (a[i] == ' ' || a[i] == '\t')) i++;
Branch: 3 branches
BranchTrueFalseTotal
while (i < al && (a[i] == ' ' || a[i] == '\t')) i++; 1 0 1
while (i < al && (a[i] == ' ' || a[i] == '\t')) i++; 0 1 1
while (i < al && (a[i] == ' ' || a[i] == '\t')) i++; 0 1 1
755 1 ▶ while (j < bl && (b[j] == ' ' || b[j] == '\t')) j++;
Branch: 3 branches
BranchTrueFalseTotal
while (j < bl && (b[j] == ' ' || b[j] == '\t')) j++; 1 0 1
while (j < bl && (b[j] == ' ' || b[j] == '\t')) j++; 0 1 1
while (j < bl && (b[j] == ' ' || b[j] == '\t')) j++; 0 1 1
756 1 ie = i;
757 1 je = j;
758 17 ▶ while (ie < al && a[ie] != ';' && a[ie] != ',' && a[ie] != ' ') ie++;
Branch: 4 branches
BranchTrueFalseTotal
while (ie < al && a[ie] != ';' && a[ie] != ',' && a[ie] != ' ') ie++; 16 1 17
while (ie < al && a[ie] != ';' && a[ie] != ',' && a[ie] != ' ') ie++; 16 0 16
while (ie < al && a[ie] != ';' && a[ie] != ',' && a[ie] != ' ') ie++; 16 0 16
while (ie < al && a[ie] != ';' && a[ie] != ',' && a[ie] != ' ') ie++; 16 0 16
759 17 ▶ while (je < bl && b[je] != ';' && b[je] != ',' && b[je] != ' ') je++;
Branch: 4 branches
BranchTrueFalseTotal
while (je < bl && b[je] != ';' && b[je] != ',' && b[je] != ' ') je++; 16 1 17
while (je < bl && b[je] != ';' && b[je] != ',' && b[je] != ' ') je++; 16 0 16
while (je < bl && b[je] != ';' && b[je] != ',' && b[je] != ' ') je++; 16 0 16
while (je < bl && b[je] != ';' && b[je] != ',' && b[je] != ' ') je++; 16 0 16
760 1 return oa_ci_eq(a + i, ie - i, b + j, je - j);
761 }
762  
763 /* 415 when a request body is present but its Content-Type matches none of the
764 * operation's declared body media types. NULL to proceed, else a +1 response. */
765 5 static SV *oa_check_request_ctype(pTHX_ oa_op *o, HV *env) {
766 5 SV *cl = oa_env_get(aTHX_ env, "CONTENT_LENGTH");
767 SV *ct;
768 STRLEN rl; const char *rp;
769 5 int i, match = 0;
770 5 ▶ if (!o->nbodies) return NULL; /* no declared body: pass */
Branch: 1 branch
BranchTrueFalseTotal
if (!o->nbodies) return NULL; /* no declared body: pass */ 3 2 5
771 2 ▶ if (!cl || SvIV(cl) <= 0) return NULL; /* no body sent: pass */
Branch: 2 branches
BranchTrueFalseTotal
if (!cl || SvIV(cl) <= 0) return NULL; /* no body sent: pass */ 2 0 2
if (!cl || SvIV(cl) <= 0) return NULL; /* no body sent: pass */ 0 2 2
772 2 ct = oa_env_get(aTHX_ env, "CONTENT_TYPE");
773 2 ▶ if (!ct) return oa_error_msg(aTHX_ 415, "missing Content-Type");
Branch: 1 branch
BranchTrueFalseTotal
if (!ct) return oa_error_msg(aTHX_ 415, "missing Content-Type"); 0 2 2
774 2 rp = SvPV_const(ct, rl);
775 5 ▶ for (i = 0; i < o->nbodies; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < o->nbodies; i++) { 4 1 5
776 4 STRLEN dl; const char *dp = SvPV_const(o->bodies[i].ctype, dl);
777 /* oa_ctype_matches, not oa_media_eq: a declared range has to admit the
778 * types it covers here too, or the 415 gate refuses a body that
779 * oa_body_for would have accepted. */
780 4 ▶ if (oa_ctype_matches(dp, dl, rp, rl)) { match = 1; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (oa_ctype_matches(dp, dl, rp, rl)) { match = 1; break; } 1 3 4
781 }
782 2 ▶ return match ? NULL : oa_error_msg(aTHX_ 415, "unsupported media type");
Branch: 1 branch
BranchTrueFalseTotal
return match ? NULL : oa_error_msg(aTHX_ 415, "unsupported media type"); 1 1 2
783 }
784  
785 /* 406 when the request has an Accept that admits none of the operation's
786 * declared response media types. Lenient: unknown (no declared types, no
787 * Accept, or Accept carries a wildcard) always passes. */
788 4 static SV *oa_check_accept(pTHX_ oa_op *o, HV *env) {
789 4 SV *acc = oa_env_get(aTHX_ env, "HTTP_ACCEPT");
790 STRLEN al, k; const char *ap;
791 4 int i, any = 0, ok = 0;
792 4 ▶ if (!acc || !o->nresps) return NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (!acc || !o->nresps) return NULL; 3 1 4
if (!acc || !o->nresps) return NULL; 0 3 3
793 3 ap = SvPV_const(acc, al);
794 3 ▶ if (al == 0) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (al == 0) return NULL; 0 3 3
795 30 ▶ for (k = 0; k + 2 < al; k++) /* star-slash-star: accept all */
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k + 2 < al; k++) /* star-slash-star: accept all */ 28 2 30
796 28 ▶ if (ap[k] == '*' && ap[k+1] == '/' && ap[k+2] == '*') return NULL;
Branch: 3 branches
BranchTrueFalseTotal
if (ap[k] == '*' && ap[k+1] == '/' && ap[k+2] == '*') return NULL; 1 27 28
if (ap[k] == '*' && ap[k+1] == '/' && ap[k+2] == '*') return NULL; 1 0 1
if (ap[k] == '*' && ap[k+1] == '/' && ap[k+2] == '*') return NULL; 1 0 1
797 4 ▶ for (i = 0; i < o->nresps && !ok; i++) {
Branch: 2 branches
BranchTrueFalseTotal
for (i = 0; i < o->nresps && !ok; i++) { 2 2 4
for (i = 0; i < o->nresps && !ok; i++) { 2 0 2
798 STRLEN dl; const char *dp;
799 STRLEN s;
800 2 ▶ if (!o->resps[i].ctype) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!o->resps[i].ctype) continue; 0 2 2
801 2 any = 1;
802 2 dp = SvPV_const(o->resps[i].ctype, dl);
803 /* acceptable if the declared type (up to ';') appears in Accept */
804 2 ▶ for (s = 0; s + dl <= al; s++)
Branch: 1 branch
BranchTrueFalseTotal
for (s = 0; s + dl <= al; s++) 1 1 2
805 1 ▶ if (oa_media_eq(ap + s, al - s, dp, dl)) { ok = 1; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (oa_media_eq(ap + s, al - s, dp, dl)) { ok = 1; break; } 1 0 1
806 }
807 2 ▶ if (!any) return NULL; /* nothing declared: pass */
Branch: 1 branch
BranchTrueFalseTotal
if (!any) return NULL; /* nothing declared: pass */ 0 2 2
808 2 ▶ return ok ? NULL : oa_error_msg(aTHX_ 406, "not acceptable");
Branch: 1 branch
BranchTrueFalseTotal
return ok ? NULL : oa_error_msg(aTHX_ 406, "not acceptable"); 1 1 2
809 }
810  
811 /* ---- hooks ------------------------------------------------------------------------ */
812  
813 /* Resolve a hook/handler spec - a coderef, or a fully qualified sub name -
814 * to an RV-to-CV (+1). Croaks (with `what` for context) on anything else. */
815 47 static SV *oa_cv_or_name(pTHX_ SV *v, const char *what) {
816 47 ▶ if (v && SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVCV)
Branch: 3 branches
BranchTrueFalseTotal
if (v && SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVCV) 47 0 47
if (v && SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVCV) 44 3 47
if (v && SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVCV) 44 0 44
817 44 return newSVsv(v);
818 3 ▶ if (v && SvOK(v) && !SvROK(v)) {
Branch: 3 branches
BranchTrueFalseTotal
if (v && SvOK(v) && !SvROK(v)) { 3 0 3
if (v && SvOK(v) && !SvROK(v)) { 3 0 3
if (v && SvOK(v) && !SvROK(v)) { 3 0 3
819 3 STRLEN nl; const char *np = SvPV_const(v, nl);
820 3 CV *cv = get_cv(np, 0);
821 3 ▶ if (!cv)
Branch: 1 branch
BranchTrueFalseTotal
if (!cv) 1 2 3
822 1 croak("Open::API->to_app: %s names no such sub '%.*s'",
823 what, (int)nl, np);
824 2 return newRV_inc((SV *)cv);
825 }
826 0 croak("Open::API->to_app: %s must be a coderef or a fully qualified "
827 "sub name", what);
828 return NULL; /* not reached */
829 }
830  
831 /* Run the after hook on a finished response: $after->($resp, $env, $opId).
832 * The hook may mutate the triplet in place; returning a PSGI triplet
833 * replaces the response (other return values are ignored). A die becomes a
834 * 500. Replaces *resp in place, consuming the old one. */
835 616 static void oa_run_after(pTHX_ SV **resp, SV *after, SV *env_rv, SV *opid) {
836 616 dSP; int n; SV *r = NULL;
837 616 ▶ if (!after || !SvOK(after)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!after || !SvOK(after)) return; 616 0 616
if (!after || !SvOK(after)) return; 608 8 616
838 8 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 8 8
839 8 ▶ EXTEND(SP, 3);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 3); 0 8 8
840 8 PUSHs(*resp);
841 8 PUSHs(env_rv);
842 8 PUSHs(opid);
843 8 PUTBACK;
844 8 n = call_sv(after, G_SCALAR | G_EVAL);
845 8 SPAGAIN;
846 8 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 8 0 8
if (SvTRUE(ERRSV)) { 0 8 8
847 0 ▶ SV *e = newSVsv(ERRSV);
Branch: 1 branch
BranchTrueFalseTotal
SV *e = newSVsv(ERRSV); 0 0 0
848 0 ▶ if (n > 0) (void)POPs;
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) (void)POPs; 0 0 0
849 0 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 0 0 0
850 0 SvREFCNT_dec(*resp);
851 0 *resp = oa_error_msg(aTHX_ 500, SvPV_nolen(e));
852 0 SvREFCNT_dec(e);
853 0 return;
854 }
855 8 ▶ if (n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { 8 0 8
856 8 SV *t = POPs;
857 8 ▶ if (oa_is_triplet(aTHX_ t) && t != *resp) r = newSVsv(t);
Branch: 2 branches
BranchTrueFalseTotal
if (oa_is_triplet(aTHX_ t) && t != *resp) r = newSVsv(t); 1 7 8
if (oa_is_triplet(aTHX_ t) && t != *resp) r = newSVsv(t); 1 0 1
858 }
859 8 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 8 0 8
860 8 ▶ if (r) { SvREFCNT_dec(*resp); *resp = r; }
Branch: 1 branch
BranchTrueFalseTotal
if (r) { SvREFCNT_dec(*resp); *resp = r; } 1 7 8
861 }
862  
863 /* Run the before hook after routing, before validation:
864 * $before->($env, $opId). A REFERENCE return short-circuits the request and
865 * becomes the response (a PSGI triplet as-is, other data JSON-encoded);
866 * non-reference returns continue. A die becomes a 500. Returns the
867 * short-circuit response (+1) or NULL to continue. */
868 6 static SV *oa_run_before(pTHX_ SV *before, SV *env_rv, SV *opid) {
869 6 dSP; int n; SV *out = NULL;
870 6 ▶ if (!before || !SvOK(before)) return NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (!before || !SvOK(before)) return NULL; 6 0 6
if (!before || !SvOK(before)) return NULL; 0 6 6
871 6 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 6 6
872 6 ▶ EXTEND(SP, 2);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 2); 0 6 6
873 6 PUSHs(env_rv);
874 6 PUSHs(opid);
875 6 PUTBACK;
876 6 n = call_sv(before, G_SCALAR | G_EVAL);
877 6 SPAGAIN;
878 6 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 6 0 6
if (SvTRUE(ERRSV)) { 1 5 6
879 1 ▶ SV *e = newSVsv(ERRSV);
Branch: 1 branch
BranchTrueFalseTotal
SV *e = newSVsv(ERRSV); 1 0 1
880 1 ▶ if (n > 0) (void)POPs;
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) (void)POPs; 1 0 1
881 1 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 1 0 1
882 1 out = oa_error_msg(aTHX_ 500, SvPV_nolen(e));
883 1 SvREFCNT_dec(e);
884 1 return out;
885 }
886 5 ▶ if (n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { 5 0 5
887 5 SV *t = POPs;
888 5 ▶ if (SvROK(t)) out = oa_map_result(aTHX_ t);
Branch: 1 branch
BranchTrueFalseTotal
if (SvROK(t)) out = oa_map_result(aTHX_ t); 1 4 5
889 }
890 5 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 5 0 5
891 5 return out;
892 }
893  
894 /* ---- security enforcement ---------------------------------------------------------- */
895  
896 /* Extract the credential a scheme describes from the request. Mortal SV, or
897 * NULL when absent/malformed. Basic credentials are base64-decoded so the
898 * checker sees "user:pass". */
899 24 static SV *oa_sec_extract(pTHX_ oa_scheme *s, HV *env) {
900 24 switch (s->type) {
901 17 case OA_SEC_APIKEY: {
902 17 STRLEN nl; const char *np = SvPV_const(s->pname, nl);
903 17 ▶ if (s->loc == OA_IN_HEADER) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->loc == OA_IN_HEADER) { 17 0 17
904 char key[160];
905 STRLEN k;
906 SV **e;
907 17 ▶ if (nl + 5 >= sizeof key) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (nl + 5 >= sizeof key) return NULL; 0 17 17
908 17 memcpy(key, "HTTP_", 5);
909 80 ▶ for (k = 0; k < nl; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < nl; k++) { 63 17 80
910 63 char c = np[k];
911 63 ▶ key[5 + k] = (c == '-') ? '_' : (char)toUPPER((U8)c);
Branch: 2 branches
BranchTrueFalseTotal
key[5 + k] = (c == '-') ? '_' : (char)toUPPER((U8)c); 44 19 63
key[5 + k] = (c == '-') ? '_' : (char)toUPPER((U8)c); 4 40 44
912 }
913 17 e = hv_fetch(env, key, (I32)(5 + nl), 0);
914 17 ▶ return (e && *e && SvOK(*e)) ? sv_mortalcopy(*e) : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (e && *e && SvOK(*e)) ? sv_mortalcopy(*e) : NULL; 16 1 17
return (e && *e && SvOK(*e)) ? sv_mortalcopy(*e) : NULL; 16 0 16
return (e && *e && SvOK(*e)) ? sv_mortalcopy(*e) : NULL; 16 0 16
915 }
916 0 ▶ if (s->loc == OA_IN_QUERY) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->loc == OA_IN_QUERY) { 0 0 0
917 0 SV *qs = oa_env_get(aTHX_ env, "QUERY_STRING");
918 STRLEN ql; const char *qp;
919 0 STRLEN i = 0;
920 0 ▶ if (!qs) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!qs) return NULL; 0 0 0
921 0 qp = SvPV_const(qs, ql);
922 0 ▶ while (i < ql) {
Branch: 1 branch
BranchTrueFalseTotal
while (i < ql) { 0 0 0
923 0 STRLEN e = i, eq;
924 0 ▶ while (e < ql && qp[e] != '&') e++;
Branch: 2 branches
BranchTrueFalseTotal
while (e < ql && qp[e] != '&') e++; 0 0 0
while (e < ql && qp[e] != '&') e++; 0 0 0
925 0 eq = i;
926 0 ▶ while (eq < e && qp[eq] != '=') eq++;
Branch: 2 branches
BranchTrueFalseTotal
while (eq < e && qp[eq] != '=') eq++; 0 0 0
while (eq < e && qp[eq] != '=') eq++; 0 0 0
927 0 ▶ if (eq - i == nl && memEQ(qp + i, np, nl) && eq < e)
Branch: 3 branches
BranchTrueFalseTotal
if (eq - i == nl && memEQ(qp + i, np, nl) && eq < e) 0 0 0
if (eq - i == nl && memEQ(qp + i, np, nl) && eq < e) 0 0 0
if (eq - i == nl && memEQ(qp + i, np, nl) && eq < e) 0 0 0
928 0 return sv_2mortal(oa_pct_decode(aTHX_ qp + eq + 1,
929 e - eq - 1, 1));
930 0 i = e + 1;
931 }
932 0 return NULL;
933 }
934 0 ▶ if (s->loc == OA_IN_COOKIE) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->loc == OA_IN_COOKIE) { 0 0 0
935 0 SV *ch = oa_env_get(aTHX_ env, "HTTP_COOKIE");
936 HV *jar;
937 SV **v;
938 0 SV *out = NULL;
939 STRLEN cl; const char *cp;
940 0 ▶ if (!ch) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ch) return NULL; 0 0 0
941 0 cp = SvPV_const(ch, cl);
942 0 jar = oa_parse_cookies(aTHX_ cp, cl);
943 0 v = hv_fetch(jar, np, (I32)nl, 0);
944 0 ▶ if (v && *v && SvOK(*v)) out = sv_mortalcopy(*v);
Branch: 3 branches
BranchTrueFalseTotal
if (v && *v && SvOK(*v)) out = sv_mortalcopy(*v); 0 0 0
if (v && *v && SvOK(*v)) out = sv_mortalcopy(*v); 0 0 0
if (v && *v && SvOK(*v)) out = sv_mortalcopy(*v); 0 0 0
945 0 SvREFCNT_dec((SV *)jar);
946 0 return out;
947 }
948 0 return NULL;
949 }
950 7 case OA_SEC_BEARER:
951 case OA_SEC_BASIC: {
952 7 SV *az = oa_env_get(aTHX_ env, "HTTP_AUTHORIZATION");
953 SV *dec;
954 STRLEN al; const char *ap;
955 7 ▶ const char *want = (s->type == OA_SEC_BEARER) ? "Bearer " : "Basic ";
Branch: 1 branch
BranchTrueFalseTotal
const char *want = (s->type == OA_SEC_BEARER) ? "Bearer " : "Basic "; 2 5 7
956 7 ▶ STRLEN wl = (s->type == OA_SEC_BEARER) ? 7 : 6;
Branch: 1 branch
BranchTrueFalseTotal
STRLEN wl = (s->type == OA_SEC_BEARER) ? 7 : 6; 2 5 7
957 STRLEN k;
958 7 ▶ if (!az) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!az) return NULL; 2 5 7
959 5 ap = SvPV_const(az, al);
960 5 ▶ if (al <= wl) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (al <= wl) return NULL; 0 5 5
961 37 ▶ for (k = 0; k < wl; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < wl; k++) 32 5 37
962 32 ▶ if (toLOWER((U8)ap[k]) != toLOWER((U8)want[k])) return NULL;
Branch: 3 branches
BranchTrueFalseTotal
if (toLOWER((U8)ap[k]) != toLOWER((U8)want[k])) return NULL; 5 27 32
if (toLOWER((U8)ap[k]) != toLOWER((U8)want[k])) return NULL; 5 27 32
if (toLOWER((U8)ap[k]) != toLOWER((U8)want[k])) return NULL; 0 32 32
963 5 ▶ while (wl < al && ap[wl] == ' ') wl++;
Branch: 2 branches
BranchTrueFalseTotal
while (wl < al && ap[wl] == ' ') wl++; 5 0 5
while (wl < al && ap[wl] == ' ') wl++; 0 5 5
964 5 ▶ if (s->type == OA_SEC_BEARER)
Branch: 1 branch
BranchTrueFalseTotal
if (s->type == OA_SEC_BEARER) 2 3 5
965 2 return sv_2mortal(newSVpvn(ap + wl, al - wl));
966 3 dec = oa_b64_decode(aTHX_ ap + wl, al - wl);
967 3 ▶ return dec ? sv_2mortal(dec) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
return dec ? sv_2mortal(dec) : NULL; 3 0 3
968 }
969 0 case OA_SEC_OTHER: {
970 /* A scheme this library cannot settle: hand the checker whatever the
971 * request carried and let it decide. Something truthy has to come
972 * back even when there is no header, or the alternative could never
973 * be satisfied - mutualTLS carries no credential in the request, it
974 * is settled by the transport. */
975 0 SV *az = oa_env_get(aTHX_ env, "HTTP_AUTHORIZATION");
976 0 ▶ return (az && SvOK(az)) ? sv_mortalcopy(az) : sv_2mortal(newSViv(1));
Branch: 2 branches
BranchTrueFalseTotal
return (az && SvOK(az)) ? sv_mortalcopy(az) : sv_2mortal(newSViv(1)); 0 0 0
return (az && SvOK(az)) ? sv_mortalcopy(az) : sv_2mortal(newSViv(1)); 0 0 0
977 }
978 }
979 0 return NULL;
980 }
981  
982 /* Enforce the operation's security requirements: try each alternative in
983 * order (schemes within one are ANDed); the first fully satisfied one wins
984 * and its checker results land in $env->{'openapi.auth'} = { name => ... }.
985 * Returns NULL on success, else a +1 response (401, or 500 for a checker
986 * die). Coverage of `checkers` was validated at to_app time. */
987 17 static SV *oa_security_check(pTHX_ oa_api *a, oa_op *o, SV *env_rv,
988 HV *checkers) {
989 17 oa_ops *t = (oa_ops *)a->ops;
990 17 HV *env = (HV *)SvRV(env_rv);
991 int i;
992 29 ▶ for (i = 0; i < o->nsec; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < o->nsec; i++) { 21 8 29
993 21 oa_secalt *alt = &o->sec[i];
994 21 HV *auth = (HV *)sv_2mortal((SV *)newHV());
995 21 int j, ok = 1;
996 33 ▶ for (j = 0; j < alt->n && ok; j++) {
Branch: 2 branches
BranchTrueFalseTotal
for (j = 0; j < alt->n && ok; j++) { 24 9 33
for (j = 0; j < alt->n && ok; j++) { 24 0 24
997 24 oa_scheme *s = &t->schemes[alt->items[j].scheme];
998 24 SV *cred = oa_sec_extract(aTHX_ s, env);
999 SV **cbp;
1000 STRLEN nl; const char *np;
1001 33 ▶ if (!cred) { ok = 0; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (!cred) { ok = 0; break; } 3 21 24
1002 21 np = SvPV_const(s->name, nl);
1003 21 cbp = hv_fetch(checkers, np, (I32)nl, 0);
1004 /* No checker for a scheme this alternative names: the
1005 * alternative cannot be satisfied. The Plack path validates
1006 * coverage at to_app time so this never fires there; it keeps
1007 * a caller that supplies an incomplete map (check_op_security)
1008 * from dereferencing NULL. */
1009 21 ▶ if (!cbp || !*cbp) { ok = 0; break; }
Branch: 2 branches
BranchTrueFalseTotal
if (!cbp || !*cbp) { ok = 0; break; } 21 0 21
if (!cbp || !*cbp) { ok = 0; break; } 0 21 21
1010 {
1011 21 dSP; int n; SV *ret = NULL;
1012 21 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 21 21
1013 21 ▶ EXTEND(SP, 4);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 4); 0 21 21
1014 21 PUSHs(cred);
1015 21 PUSHs(env_rv);
1016 21 PUSHs(o->op_id);
1017 21 ▶ PUSHs(alt->items[j].scopes ? alt->items[j].scopes
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(alt->items[j].scopes ? alt->items[j].scopes 21 0 21
1018 : &PL_sv_undef);
1019 21 PUTBACK;
1020 21 n = call_sv(*cbp, G_SCALAR | G_EVAL);
1021 21 SPAGAIN;
1022 21 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 21 0 21
if (SvTRUE(ERRSV)) { 0 21 21
1023 0 ▶ SV *e = newSVsv(ERRSV);
Branch: 1 branch
BranchTrueFalseTotal
SV *e = newSVsv(ERRSV); 0 0 0
1024 SV *resp;
1025 0 ▶ if (n > 0) (void)POPs;
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) (void)POPs; 0 0 0
1026 0 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 0 0 0
1027 0 resp = oa_error_msg(aTHX_ 500, SvPV_nolen(e));
1028 0 SvREFCNT_dec(e);
1029 0 return resp;
1030 }
1031 21 ▶ if (n > 0) { SV *r = POPs; if (SvTRUE(r)) ret = newSVsv(r); }
Branch: 2 branches
BranchTrueFalseTotal
if (n > 0) { SV *r = POPs; if (SvTRUE(r)) ret = newSVsv(r); } 21 0 21
if (n > 0) { SV *r = POPs; if (SvTRUE(r)) ret = newSVsv(r); } 12 9 21
1032 21 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 21 0 21
1033 21 ▶ if (!ret) { ok = 0; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (!ret) { ok = 0; break; } 9 12 21
1034 12 (void)hv_store(auth, np, (I32)nl, ret, 0);
1035 }
1036 }
1037 21 ▶ if (ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (ok) { 9 12 21
1038 9 (void)hv_stores(env, "openapi.auth",
1039 newRV_inc((SV *)auth));
1040 9 return NULL;
1041 }
1042 }
1043 8 return oa_error_msg(aTHX_ 401, "unauthorized");
1044 }
1045  
1046 /* ---- CSRF -------------------------------------------------------------------------- */
1047  
1048 /* "scheme://host:port/..." or a bare "host:port" -> the host:port slice */
1049 28 static void oa_origin_host(const char *p, STRLEN l, const char **hp, STRLEN *hl) {
1050 28 STRLEN i = 0, s;
1051 28 const char *sep = "://";
1052 168 ▶ for (i = 0; i + 2 < l; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 2 < l; i++) 168 0 168
1053 168 ▶ if (p[i] == ':' && p[i+1] == '/' && p[i+2] == '/') { i += 3; break; }
Branch: 3 branches
BranchTrueFalseTotal
if (p[i] == ':' && p[i+1] == '/' && p[i+2] == '/') { i += 3; break; } 28 140 168
if (p[i] == ':' && p[i+1] == '/' && p[i+2] == '/') { i += 3; break; } 28 0 28
if (p[i] == ':' && p[i+1] == '/' && p[i+2] == '/') { i += 3; break; } 28 0 28
1054 28 ▶ if (i + 2 >= l) i = 0; /* no scheme: treat the whole thing as authority */
Branch: 1 branch
BranchTrueFalseTotal
if (i + 2 >= l) i = 0; /* no scheme: treat the whole thing as authority */ 0 28 28
1055 28 s = i;
1056 450 ▶ while (i < l && p[i] != '/' && p[i] != '?' && p[i] != '#') i++;
Branch: 4 branches
BranchTrueFalseTotal
while (i < l && p[i] != '/' && p[i] != '?' && p[i] != '#') i++; 424 26 450
while (i < l && p[i] != '/' && p[i] != '?' && p[i] != '#') i++; 422 2 424
while (i < l && p[i] != '/' && p[i] != '?' && p[i] != '#') i++; 422 0 422
while (i < l && p[i] != '/' && p[i] != '?' && p[i] != '#') i++; 422 0 422
1057 28 *hp = p + s;
1058 28 *hl = i - s;
1059 (void)sep;
1060 28 }
1061  
1062 /* Enforce CSRF protection for state-changing methods. cfg keys (normalised at
1063 * to_app time): origins (AV of allowed origins, may be empty for same-origin),
1064 * secret (SV, present => double-submit), cookie (SV name), header (SV name).
1065 * Returns NULL when the request may proceed, else a +1 403 response. Safe
1066 * methods (GET/HEAD/OPTIONS/TRACE) always pass. */
1067 19 static SV *oa_csrf_check(pTHX_ oa_op *o, SV *env_rv, HV *cfg) {
1068 19 HV *env = (HV *)SvRV(env_rv);
1069 19 STRLEN ml; const char *mp = SvPV_const(o->method, ml); /* lowercase */
1070 SV *origin, *host, **sv, **chk;
1071 AV *origins;
1072 19 const char *oh = NULL;
1073 19 STRLEN ohl = 0;
1074 19 int matched = 0;
1075  
1076 19 ▶ if ((ml == 3 && memEQ(mp, "get", 3)) || (ml == 4 && memEQ(mp, "head", 4))
Branch: 4 branches
BranchTrueFalseTotal
if ((ml == 3 && memEQ(mp, "get", 3)) || (ml == 4 && memEQ(mp, "head", 4)) 2 17 19
if ((ml == 3 && memEQ(mp, "get", 3)) || (ml == 4 && memEQ(mp, "head", 4)) 0 2 2
if ((ml == 3 && memEQ(mp, "get", 3)) || (ml == 4 && memEQ(mp, "head", 4)) 0 17 17
if ((ml == 3 && memEQ(mp, "get", 3)) || (ml == 4 && memEQ(mp, "head", 4)) 0 0 0
1077 17 ▶ || (ml == 7 && memEQ(mp, "options", 7))
Branch: 2 branches
BranchTrueFalseTotal
|| (ml == 7 && memEQ(mp, "options", 7)) 0 17 17
|| (ml == 7 && memEQ(mp, "options", 7)) 0 0 0
1078 17 ▶ || (ml == 5 && memEQ(mp, "trace", 5)))
Branch: 2 branches
BranchTrueFalseTotal
|| (ml == 5 && memEQ(mp, "trace", 5))) 0 17 17
|| (ml == 5 && memEQ(mp, "trace", 5))) 0 0 0
1079 2 return NULL;
1080  
1081 /* ---- Origin / Referer check ---- */
1082 17 origin = oa_env_get(aTHX_ env, "HTTP_ORIGIN");
1083 17 ▶ if (!origin) origin = oa_env_get(aTHX_ env, "HTTP_REFERER");
Branch: 1 branch
BranchTrueFalseTotal
if (!origin) origin = oa_env_get(aTHX_ env, "HTTP_REFERER"); 2 15 17
1084 17 sv = hv_fetchs(cfg, "origins", 0);
1085 17 ▶ origins = (sv && *sv && SvROK(*sv)) ? (AV *)SvRV(*sv) : NULL;
Branch: 3 branches
BranchTrueFalseTotal
origins = (sv && *sv && SvROK(*sv)) ? (AV *)SvRV(*sv) : NULL; 12 5 17
origins = (sv && *sv && SvROK(*sv)) ? (AV *)SvRV(*sv) : NULL; 12 0 12
origins = (sv && *sv && SvROK(*sv)) ? (AV *)SvRV(*sv) : NULL; 12 0 12
1086 17 ▶ if (origin) {
Branch: 1 branch
BranchTrueFalseTotal
if (origin) { 16 1 17
1087 16 STRLEN ol; const char *op = SvPV_const(origin, ol);
1088 16 oa_origin_host(op, ol, &oh, &ohl);
1089 }
1090 29 ▶ if (origins && av_len(origins) >= 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (origins && av_len(origins) >= 0) { 12 5 17
if (origins && av_len(origins) >= 0) { 12 0 12
1091 SSize_t i;
1092 13 ▶ if (oh) for (i = 0; i <= av_len(origins); i++) {
Branch: 2 branches
BranchTrueFalseTotal
if (oh) for (i = 0; i <= av_len(origins); i++) { 12 0 12
if (oh) for (i = 0; i <= av_len(origins); i++) { 12 1 13
1093 12 SV **a = av_fetch(origins, i, 0);
1094 const char *ah, *ap; STRLEN al, al2;
1095 12 ▶ if (!a || !*a) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!a || !*a) continue; 12 0 12
if (!a || !*a) continue; 0 12 12
1096 12 ap = SvPV_const(*a, al);
1097 12 oa_origin_host(ap, al, &ah, &al2);
1098 12 ▶ if (al2 == ohl && memEQ(ah, oh, ohl)) { matched = 1; break; }
Branch: 2 branches
BranchTrueFalseTotal
if (al2 == ohl && memEQ(ah, oh, ohl)) { matched = 1; break; } 12 0 12
if (al2 == ohl && memEQ(ah, oh, ohl)) { matched = 1; break; } 11 1 12
1099 }
1100 } else {
1101 /* same-origin default: Origin authority must equal Host */
1102 5 host = oa_env_get(aTHX_ env, "HTTP_HOST");
1103 5 ▶ if (oh && host) {
Branch: 2 branches
BranchTrueFalseTotal
if (oh && host) { 4 1 5
if (oh && host) { 4 0 4
1104 4 STRLEN hl; const char *hpp = SvPV_const(host, hl);
1105 4 ▶ if (hl == ohl && memEQ(hpp, oh, ohl)) matched = 1;
Branch: 2 branches
BranchTrueFalseTotal
if (hl == ohl && memEQ(hpp, oh, ohl)) matched = 1; 2 2 4
if (hl == ohl && memEQ(hpp, oh, ohl)) matched = 1; 2 0 2
1106 }
1107 }
1108 17 ▶ if (!matched)
Branch: 1 branch
BranchTrueFalseTotal
if (!matched) 4 13 17
1109 4 ▶ return oa_error_msg(aTHX_ 403,
Branch: 1 branch
BranchTrueFalseTotal
return oa_error_msg(aTHX_ 403, 3 1 4
1110 origin ? "CSRF check failed: origin not allowed"
1111 : "CSRF check failed: missing Origin/Referer");
1112  
1113 /* ---- token: an app-owned store, via the check callback. The submitted
1114 * token comes from the configured header (a cross-site page cannot set a
1115 * custom header, so this half is what actually stops the forgery). */
1116 13 chk = hv_fetchs(cfg, "check", 0);
1117 13 ▶ if (chk && *chk && SvROK(*chk)) {
Branch: 3 branches
BranchTrueFalseTotal
if (chk && *chk && SvROK(*chk)) { 9 4 13
if (chk && *chk && SvROK(*chk)) { 9 0 9
if (chk && *chk && SvROK(*chk)) { 9 0 9
1118 9 SV **hn = hv_fetchs(cfg, "header", 0);
1119 STRLEN hnl, k;
1120 9 const char *hnp = SvPV_const(*hn, hnl);
1121 char key[160];
1122 9 SV *hd = NULL;
1123 9 dSP; int n; SV *err = NULL; SV *resp, *keep = NULL;
1124  
1125 9 ▶ if (hnl + 5 < sizeof key) { /* the submitted token header */
Branch: 1 branch
BranchTrueFalseTotal
if (hnl + 5 < sizeof key) { /* the submitted token header */ 9 0 9
1126 SV **v;
1127 9 memcpy(key, "HTTP_", 5);
1128 111 ▶ for (k = 0; k < hnl; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < hnl; k++) { 102 9 111
1129 102 char c = hnp[k];
1130 102 ▶ key[5 + k] = (c == '-') ? '_' : (char)toUPPER((U8)c);
Branch: 2 branches
BranchTrueFalseTotal
key[5 + k] = (c == '-') ? '_' : (char)toUPPER((U8)c); 85 17 102
key[5 + k] = (c == '-') ? '_' : (char)toUPPER((U8)c); 32 53 85
1131 }
1132 9 v = hv_fetch(env, key, (I32)(5 + hnl), 0);
1133 9 ▶ if (v && *v && SvOK(*v)) hd = *v;
Branch: 3 branches
BranchTrueFalseTotal
if (v && *v && SvOK(*v)) hd = *v; 7 2 9
if (v && *v && SvOK(*v)) hd = *v; 7 0 7
if (v && *v && SvOK(*v)) hd = *v; 7 0 7
1134 }
1135  
1136 /* check($submitted_token, $env, $operationId) - a truthy return
1137 * passes AND is stashed as $env->{'openapi.csrf'} (mirroring the
1138 * security checkers' 'openapi.auth'), so the handler / after hook can
1139 * consume or rotate the token without re-loading the store. A die
1140 * becomes a 500. */
1141 9 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 9 9
1142 9 ▶ EXTEND(SP, 3);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 3); 0 9 9
1143 9 ▶ PUSHs(hd ? hd : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(hd ? hd : &PL_sv_undef); 7 2 9
1144 9 PUSHs(env_rv);
1145 9 PUSHs(o->op_id);
1146 9 PUTBACK;
1147 9 n = call_sv(*chk, G_SCALAR | G_EVAL);
1148 9 SPAGAIN;
1149 9 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 9 0 9
if (SvTRUE(ERRSV)) { 1 8 9
1150 1 ▶ err = newSVsv(ERRSV);
Branch: 1 branch
BranchTrueFalseTotal
err = newSVsv(ERRSV); 1 0 1
1151 1 ▶ if (n > 0) (void)POPs;
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) (void)POPs; 1 0 1
1152 1 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 1 0 1
1153 1 resp = oa_error_msg(aTHX_ 500, SvPV_nolen(err));
1154 1 SvREFCNT_dec(err);
1155 4 return resp;
1156 }
1157 8 ▶ if (n > 0) { SV *r = POPs; if (SvTRUE(r)) keep = newSVsv(r); }
Branch: 2 branches
BranchTrueFalseTotal
if (n > 0) { SV *r = POPs; if (SvTRUE(r)) keep = newSVsv(r); } 8 0 8
if (n > 0) { SV *r = POPs; if (SvTRUE(r)) keep = newSVsv(r); } 5 3 8
1158 8 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 8 0 8
1159 8 ▶ if (!keep)
Branch: 1 branch
BranchTrueFalseTotal
if (!keep) 3 5 8
1160 3 return oa_error_msg(aTHX_ 403,
1161 "CSRF check failed: invalid or missing token");
1162 5 (void)hv_stores(env, "openapi.csrf", keep); /* env owns it */
1163 /* a returned string token rotates the cookie: the framework sets it
1164 * on the response (any status), so the client always leaves holding a
1165 * fresh, unused token. A non-string truthy return (1, a ref) just
1166 * passes - set your own cookie in the after hook. */
1167 5 ▶ if (SvPOK(keep) && SvCUR(keep) > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvPOK(keep) && SvCUR(keep) > 0) { 4 1 5
if (SvPOK(keep) && SvCUR(keep) > 0) { 4 0 4
1168 4 SV **cn = hv_fetchs(cfg, "cookie", 0);
1169 4 STRLEN cnl; const char *cnp = SvPV_const(*cn, cnl);
1170 4 SV *sc = newSVpvn(cnp, cnl);
1171 4 sv_catpvs(sc, "=");
1172 4 sv_catsv(sc, keep);
1173 4 sv_catpvs(sc, "; Path=/; SameSite=Strict");
1174 4 (void)hv_stores(env, "openapi.csrf.setcookie", sc);
1175 }
1176 }
1177  
1178 9 return NULL;
1179 }
1180  
1181 /* ---- Future completion (nonblocking servers) --------------------------------------- *
1182 * When a handler returns a Future on a nonblocking server AND there is
1183 * post-processing to do (after hook or validate_responses), the future is
1184 * chained with ->then(done, fail): done maps the resolved value and applies
1185 * response validation + the after hook; fail turns a failed future into a
1186 * 500 (also passed to after). Captures: [0]=api self SV (keeps the op table
1187 * alive), [1]=env_rv, [2]=opId SV, [3]=after or undef, [4]=vresp IV,
1188 * [5]=op pointer IV, [6]=opts HV ref or undef. */
1189  
1190 XS_INTERNAL(oa_then_done_cb);
1191 2 XS_INTERNAL(oa_then_done_cb) {
1192 2 dXSARGS;
1193 2 AV *cap = oa_clos_cap(aTHX_ cv);
1194 SV *env_rv, *opid, *after, *resp, *optsv;
1195 oa_op *o;
1196 int vresp;
1197 2 ▶ if (!cap) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (!cap) XSRETURN_EMPTY; 0 2 2
1198 2 env_rv = *av_fetch(cap, 1, 0);
1199 2 opid = *av_fetch(cap, 2, 0);
1200 2 after = *av_fetch(cap, 3, 0);
1201 2 vresp = (int)SvIV(*av_fetch(cap, 4, 0));
1202 2 o = INT2PTR(oa_op *, SvIV(*av_fetch(cap, 5, 0)));
1203 2 optsv = *av_fetch(cap, 6, 0);
1204 2 ▶ resp = oa_map_result(aTHX_ items > 0 ? ST(0) : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
resp = oa_map_result(aTHX_ items > 0 ? ST(0) : &PL_sv_undef); 2 0 2
1205 2 ▶ if (vresp) {
Branch: 1 branch
BranchTrueFalseTotal
if (vresp) { 1 1 2
1206 1 SV *bad = oa_check_response_opts(aTHX_ o, resp, vresp,
1207 1 ▶ SvROK(optsv) ? (HV *)SvRV(optsv) : NULL, env_rv);
Branch: 1 branch
BranchTrueFalseTotal
SvROK(optsv) ? (HV *)SvRV(optsv) : NULL, env_rv); 1 0 1
1208 1 ▶ if (bad) { SvREFCNT_dec(resp); resp = bad; }
Branch: 1 branch
BranchTrueFalseTotal
if (bad) { SvREFCNT_dec(resp); resp = bad; } 1 0 1
1209 }
1210 2 oa_run_after(aTHX_ &resp, after, env_rv, opid);
1211 2 ▶ oa_finalize(aTHX_ resp, env_rv, SvROK(optsv) ? (HV *)SvRV(optsv) : NULL);
Branch: 1 branch
BranchTrueFalseTotal
oa_finalize(aTHX_ resp, env_rv, SvROK(optsv) ? (HV *)SvRV(optsv) : NULL); 2 0 2
1212 2 ST(0) = sv_2mortal(resp);
1213 2 XSRETURN(1);
1214 }
1215  
1216 XS_INTERNAL(oa_then_fail_cb);
1217 0 XS_INTERNAL(oa_then_fail_cb) {
1218 0 dXSARGS;
1219 0 AV *cap = oa_clos_cap(aTHX_ cv);
1220 SV *env_rv, *opid, *after, *resp, *optsv;
1221 0 ▶ if (!cap) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (!cap) XSRETURN_EMPTY; 0 0 0
1222 0 env_rv = *av_fetch(cap, 1, 0);
1223 0 opid = *av_fetch(cap, 2, 0);
1224 0 after = *av_fetch(cap, 3, 0);
1225 0 optsv = *av_fetch(cap, 6, 0);
1226 0 ▶ resp = oa_error_msg(aTHX_ 500,
Branch: 1 branch
BranchTrueFalseTotal
resp = oa_error_msg(aTHX_ 500, 0 0 0
1227 0 ▶ (items > 0 && SvOK(ST(0))) ? SvPV_nolen(ST(0)) : "handler future failed");
Branch: 1 branch
BranchTrueFalseTotal
(items > 0 && SvOK(ST(0))) ? SvPV_nolen(ST(0)) : "handler future failed"); 0 0 0
1228 0 oa_run_after(aTHX_ &resp, after, env_rv, opid);
1229 0 ▶ oa_finalize(aTHX_ resp, env_rv, SvROK(optsv) ? (HV *)SvRV(optsv) : NULL);
Branch: 1 branch
BranchTrueFalseTotal
oa_finalize(aTHX_ resp, env_rv, SvROK(optsv) ? (HV *)SvRV(optsv) : NULL); 0 0 0
1230 0 ST(0) = sv_2mortal(resp);
1231 0 XSRETURN(1);
1232 }
1233  
1234 /* one capture AV for the then callbacks (each closure needs its own) */
1235 4 static AV *oa_then_cap(pTHX_ SV *self_sv, SV *env_rv, oa_op *o, SV *after,
1236 int vresp, SV *optsv) {
1237 4 AV *cap = newAV();
1238 4 av_push(cap, SvREFCNT_inc(self_sv));
1239 4 av_push(cap, SvREFCNT_inc(env_rv));
1240 4 av_push(cap, newSVsv(o->op_id));
1241 4 ▶ av_push(cap, after && SvOK(after) ? SvREFCNT_inc(after) : newSV(0));
Branch: 2 branches
BranchTrueFalseTotal
av_push(cap, after && SvOK(after) ? SvREFCNT_inc(after) : newSV(0)); 4 0 4
av_push(cap, after && SvOK(after) ? SvREFCNT_inc(after) : newSV(0)); 2 2 4
1242 4 av_push(cap, newSViv(vresp));
1243 4 av_push(cap, newSViv(PTR2IV(o)));
1244 4 ▶ av_push(cap, optsv && SvROK(optsv) ? SvREFCNT_inc(optsv) : newSV(0));
Branch: 2 branches
BranchTrueFalseTotal
av_push(cap, optsv && SvROK(optsv) ? SvREFCNT_inc(optsv) : newSV(0)); 4 0 4
av_push(cap, optsv && SvROK(optsv) ? SvREFCNT_inc(optsv) : newSV(0)); 4 0 4
1245 4 return cap;
1246 }
1247  
1248 /* ---- the request path ------------------------------------------------------------ */
1249  
1250 /* Serve one PSGI request. Returns a PSGI triplet SV, or a Future SV on a
1251 * non-blocking server (chained with the post-processing when an after hook
1252 * or response validation is active). (+1 owned by caller) */
1253 629 static SV *oa_serve_psgi(pTHX_ SV *self_sv, HV *handlers, SV *env_rv,
1254 int vresp, SV *before, SV *after, HV *seccb,
1255 HV *csrf, HV *opts) {
1256 629 oa_api *a = (oa_api *)INT2PTR(void *, SvIV(SvRV(self_sv)));
1257 629 HV *env = (HV *)SvRV(env_rv);
1258 629 SV *msv = oa_env_get(aTHX_ env, "REQUEST_METHOD");
1259 629 SV *psv = oa_env_get(aTHX_ env, "PATH_INFO");
1260 629 SV *qsv = oa_env_get(aTHX_ env, "QUERY_STRING");
1261 629 HV *caps = (HV *)sv_2mortal((SV *)newHV());
1262 629 AV *allow = (AV *)sv_2mortal((SV *)newAV());
1263 oa_op *o;
1264 HV *headers;
1265 SV *body, *handler;
1266 629 HV *params = NULL;
1267 AV *errs;
1268 629 int is_options = 0;
1269 629 HV *cors = NULL;
1270 629 int negotiate = 0;
1271 629 IV max_body = 0;
1272 STRLEN ml, pl, il;
1273 const char *mp, *pp, *ip;
1274 SV **h;
1275  
1276 /* every triplet exit runs through finalize (problem+json, CORS, headers) */
1277 #define OA_FIN(r) oa_fin(aTHX_ (r), env_rv, opts)
1278  
1279 629 ▶ if (opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts) { 629 0 629
1280 SV **v;
1281 629 ▶ if ((v = hv_fetchs(opts, "cors", 0)) && *v && SvROK(*v))
Branch: 3 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "cors", 0)) && *v && SvROK(*v)) 5 624 629
if ((v = hv_fetchs(opts, "cors", 0)) && *v && SvROK(*v)) 5 0 5
if ((v = hv_fetchs(opts, "cors", 0)) && *v && SvROK(*v)) 5 0 5
1282 5 cors = (HV *)SvRV(*v);
1283 629 ▶ if ((v = hv_fetchs(opts, "negotiate", 0)) && *v) negotiate = SvTRUE(*v);
Branch: 2 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "negotiate", 0)) && *v) negotiate = SvTRUE(*v); 5 624 629
if ((v = hv_fetchs(opts, "negotiate", 0)) && *v) negotiate = SvTRUE(*v); 5 0 5
1284 629 ▶ if ((v = hv_fetchs(opts, "max_body_size", 0)) && *v) max_body = SvIV(*v);
Branch: 2 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "max_body_size", 0)) && *v) max_body = SvIV(*v); 502 127 629
if ((v = hv_fetchs(opts, "max_body_size", 0)) && *v) max_body = SvIV(*v); 502 0 502
1285 }
1286  
1287 1258 ▶ mp = msv ? SvPV_const(msv, ml) : (ml = 3, "GET");
Branch: 1 branch
BranchTrueFalseTotal
mp = msv ? SvPV_const(msv, ml) : (ml = 3, "GET"); 629 0 629
1288 1258 ▶ pp = psv ? SvPV_const(psv, pl) : (pl = 1, "/");
Branch: 1 branch
BranchTrueFalseTotal
pp = psv ? SvPV_const(psv, pl) : (pl = 1, "/"); 629 0 629
1289 629 ▶ is_options = (ml == 7 && (mp[0]=='O'||mp[0]=='o') && oa_ci_eq(mp, ml, "options", 7));
Branch: 4 branches
BranchTrueFalseTotal
is_options = (ml == 7 && (mp[0]=='O'||mp[0]=='o') && oa_ci_eq(mp, ml, "options", 7)); 1 628 629
is_options = (ml == 7 && (mp[0]=='O'||mp[0]=='o') && oa_ci_eq(mp, ml, "options", 7)); 0 1 1
is_options = (ml == 7 && (mp[0]=='O'||mp[0]=='o') && oa_ci_eq(mp, ml, "options", 7)); 0 0 0
is_options = (ml == 7 && (mp[0]=='O'||mp[0]=='o') && oa_ci_eq(mp, ml, "options", 7)); 1 0 1
1290 629 o = oa_route(aTHX_ a, mp, ml, pp, pl, caps, allow);
1291 629 ▶ if (!o) {
Branch: 1 branch
BranchTrueFalseTotal
if (!o) { 13 616 629
1292 13 ▶ if (av_len(allow) >= 0) { /* path exists, method does not */
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(allow) >= 0) { /* path exists, method does not */ 3 10 13
1293 SV *resp;
1294 AV *tv, *ha;
1295 SV **hh;
1296 SV *joined;
1297 SSize_t i;
1298 /* CORS preflight: an OPTIONS with Access-Control-Request-Method */
1299 3 ▶ if (cors && is_options
Branch: 2 branches
BranchTrueFalseTotal
if (cors && is_options 1 2 3
if (cors && is_options 1 0 1
1300 1 ▶ && oa_env_get(aTHX_ env, "HTTP_ACCESS_CONTROL_REQUEST_METHOD"))
Branch: 1 branch
BranchTrueFalseTotal
&& oa_env_get(aTHX_ env, "HTTP_ACCESS_CONTROL_REQUEST_METHOD")) 1 0 1
1301 1 return OA_FIN(oa_cors_preflight(aTHX_ env_rv, cors, allow));
1302 2 resp = oa_error_msg(aTHX_ 405, "method not allowed");
1303 2 tv = (AV *)SvRV(resp);
1304 2 hh = av_fetch(tv, 1, 0);
1305 2 ha = (AV *)SvRV(*hh);
1306 2 joined = newSVpvs("");
1307 6 ▶ for (i = 0; i <= av_len(allow); i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i <= av_len(allow); i++) { 4 2 6
1308 4 SV **m = av_fetch(allow, i, 0);
1309 4 ▶ if (i) sv_catpvs(joined, ", ");
Branch: 1 branch
BranchTrueFalseTotal
if (i) sv_catpvs(joined, ", "); 2 2 4
1310 4 sv_catsv(joined, *m);
1311 }
1312 2 av_push(ha, newSVpvs("Allow"));
1313 2 av_push(ha, joined);
1314 2 return OA_FIN(resp);
1315 }
1316 10 return OA_FIN(oa_error_msg(aTHX_ 404, "not found"));
1317 }
1318  
1319 /* body size limit: reject an over-large declared Content-Length before
1320 * doing any auth or reading the body */
1321 616 ▶ if (max_body > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (max_body > 0) { 502 114 616
1322 502 SV *cl = oa_env_get(aTHX_ env, "CONTENT_LENGTH");
1323 502 ▶ if (cl && SvIV(cl) > max_body) {
Branch: 2 branches
BranchTrueFalseTotal
if (cl && SvIV(cl) > max_body) { 2 500 502
if (cl && SvIV(cl) > max_body) { 1 1 2
1324 1 SV *resp = oa_error_msg(aTHX_ 413, "request body too large");
1325 1 oa_run_after(aTHX_ &resp, after, env_rv, o->op_id);
1326 1 return OA_FIN(resp);
1327 }
1328 }
1329  
1330 /* CSRF: guard state-changing methods before anything else touches the
1331 * request (independent of who is authenticated) */
1332 615 ▶ if (csrf) {
Branch: 1 branch
BranchTrueFalseTotal
if (csrf) { 19 596 615
1333 19 SV *denied = oa_csrf_check(aTHX_ o, env_rv, csrf);
1334 19 ▶ if (denied) {
Branch: 1 branch
BranchTrueFalseTotal
if (denied) { 8 11 19
1335 8 oa_run_after(aTHX_ &denied, after, env_rv, o->op_id);
1336 8 return OA_FIN(denied);
1337 }
1338 }
1339  
1340 /* spec-driven security first: extract credential, run the checker, 401
1341 * when no requirement alternative is satisfied */
1342 607 ▶ if (o->nsec && seccb) {
Branch: 2 branches
BranchTrueFalseTotal
if (o->nsec && seccb) { 5 602 607
if (o->nsec && seccb) { 5 0 5
1343 5 SV *denied = oa_security_check(aTHX_ a, o, env_rv, seccb);
1344 5 ▶ if (denied) {
Branch: 1 branch
BranchTrueFalseTotal
if (denied) { 3 2 5
1345 3 oa_run_after(aTHX_ &denied, after, env_rv, o->op_id);
1346 3 return OA_FIN(denied);
1347 }
1348 }
1349  
1350 /* content negotiation (opt-in): 415 on an unsupported request body type,
1351 * 406 when the client's Accept admits none of the declared responses */
1352 604 ▶ if (negotiate) {
Branch: 1 branch
BranchTrueFalseTotal
if (negotiate) { 5 599 604
1353 5 SV *bad = oa_check_request_ctype(aTHX_ o, env);
1354 5 ▶ if (!bad) bad = oa_check_accept(aTHX_ o, env);
Branch: 1 branch
BranchTrueFalseTotal
if (!bad) bad = oa_check_accept(aTHX_ o, env); 4 1 5
1355 5 ▶ if (bad) {
Branch: 1 branch
BranchTrueFalseTotal
if (bad) { 2 3 5
1356 2 oa_run_after(aTHX_ &bad, after, env_rv, o->op_id);
1357 2 return OA_FIN(bad);
1358 }
1359 }
1360  
1361 /* before hook: post-route, pre-validation - a reference return
1362 * short-circuits (the auth case: return [401, ...]) */
1363 602 ▶ if (before && SvOK(before)) {
Branch: 2 branches
BranchTrueFalseTotal
if (before && SvOK(before)) { 602 0 602
if (before && SvOK(before)) { 6 596 602
1364 6 SV *early = oa_run_before(aTHX_ before, env_rv, o->op_id);
1365 6 ▶ if (early) {
Branch: 1 branch
BranchTrueFalseTotal
if (early) { 2 4 6
1366 2 oa_run_after(aTHX_ &early, after, env_rv, o->op_id);
1367 2 return OA_FIN(early);
1368 }
1369 }
1370  
1371 600 headers = (HV *)sv_2mortal((SV *)oa_headers_for(aTHX_ o, env));
1372 600 ▶ body = o->nbodies ? oa_read_body_env(aTHX_ env) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
body = o->nbodies ? oa_read_body_env(aTHX_ env) : NULL; 15 585 600
1373 600 errs = (AV *)sv_2mortal((SV *)newAV());
1374  
1375 600 ▶ if (!oa_validate_op(aTHX_ a, o, caps,
Branch: 2 branches
BranchTrueFalseTotal
if (!oa_validate_op(aTHX_ a, o, caps, 600 0 600
if (!oa_validate_op(aTHX_ a, o, caps, 10 590 600
1376 qsv ? qsv : &PL_sv_no, headers, body,
1377 &params, errs)) {
1378 10 SV *resp = oa_error_response(aTHX_ 400, errs);
1379 10 oa_run_after(aTHX_ &resp, after, env_rv, o->op_id);
1380 10 return OA_FIN(resp);
1381 }
1382  
1383 590 ip = SvPV_const(o->op_id, il);
1384 590 h = hv_fetch(handlers, ip, (I32)il, 0);
1385 590 ▶ if (!h || !*h || !SvROK(*h) || SvTYPE(SvRV(*h)) != SVt_PVCV) {
Branch: 4 branches
BranchTrueFalseTotal
if (!h || !*h || !SvROK(*h) || SvTYPE(SvRV(*h)) != SVt_PVCV) { 588 2 590
if (!h || !*h || !SvROK(*h) || SvTYPE(SvRV(*h)) != SVt_PVCV) { 588 0 588
if (!h || !*h || !SvROK(*h) || SvTYPE(SvRV(*h)) != SVt_PVCV) { 588 0 588
if (!h || !*h || !SvROK(*h) || SvTYPE(SvRV(*h)) != SVt_PVCV) { 0 588 588
1386 SV *resp;
1387 2 SvREFCNT_dec((SV *)params);
1388 2 resp = oa_error_msg(aTHX_ 501, "no handler for this operation");
1389 2 oa_run_after(aTHX_ &resp, after, env_rv, o->op_id);
1390 2 return OA_FIN(resp);
1391 }
1392 588 handler = *h;
1393  
1394 { /* call the handler: ($params, $env) */
1395 588 dSP; int n; SV *res = NULL, *resp;
1396 588 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 588 588
1397 588 ▶ EXTEND(SP, 2);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 2); 0 588 588
1398 588 mPUSHs(newRV_noinc((SV *)params));
1399 588 PUSHs(env_rv);
1400 588 PUTBACK;
1401 588 n = call_sv(handler, G_SCALAR | G_EVAL);
1402 588 SPAGAIN;
1403 588 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 588 0 588
if (SvTRUE(ERRSV)) { 2 586 588
1404 2 ▶ SV *e = newSVsv(ERRSV); /* keep past FREETMPS */
Branch: 1 branch
BranchTrueFalseTotal
SV *e = newSVsv(ERRSV); /* keep past FREETMPS */ 2 0 2
1405 2 ▶ if (n > 0) (void)POPs;
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) (void)POPs; 2 0 2
1406 2 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 2 0 2
1407 2 resp = oa_error_msg(aTHX_ 500, SvPV_nolen(e));
1408 2 SvREFCNT_dec(e);
1409 2 oa_run_after(aTHX_ &resp, after, env_rv, o->op_id);
1410 2 return OA_FIN(resp);
1411 }
1412 586 ▶ res = n > 0 ? SvREFCNT_inc(POPs) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
res = n > 0 ? SvREFCNT_inc(POPs) : &PL_sv_undef; 586 0 586
1413 586 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 586 0 586
1414  
1415 586 ▶ if (oa_is_future(aTHX_ res)) {
Branch: 1 branch
BranchTrueFalseTotal
if (oa_is_future(aTHX_ res)) { 2 584 586
1416 2 SV *nb = oa_env_get(aTHX_ env, "psgi.nonblocking");
1417 2 ▶ if (nb && SvTRUE(nb)) {
Branch: 2 branches
BranchTrueFalseTotal
if (nb && SvTRUE(nb)) { 2 0 2
if (nb && SvTRUE(nb)) { 2 0 2
1418 2 ▶ int want_after = after && SvOK(after);
Branch: 2 branches
BranchTrueFalseTotal
int want_after = after && SvOK(after); 2 0 2
int want_after = after && SvOK(after); 1 1 2
1419 2 ▶ if (!want_after && !vresp && !opts)
Branch: 3 branches
BranchTrueFalseTotal
if (!want_after && !vresp && !opts) 1 1 2
if (!want_after && !vresp && !opts) 0 1 1
if (!want_after && !vresp && !opts) 0 0 0
1420 0 return res; /* nothing to add: hand it over */
1421 { /* chain ->then(done, fail) so mapping + response
1422 * validation + finalize + the after hook run on
1423 * resolution */
1424 2 dSP; int n2; SV *derived = NULL;
1425 2 SV *optsv = opts ? sv_2mortal(newRV_inc((SV *)opts))
1426 2 ▶ : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
: &PL_sv_undef; 2 0 2
1427 2 SV *done = oa_closure(aTHX_ oa_then_done_cb,
1428 oa_then_cap(aTHX_ self_sv, env_rv, o, after, vresp, optsv));
1429 2 SV *fail = oa_closure(aTHX_ oa_then_fail_cb,
1430 oa_then_cap(aTHX_ self_sv, env_rv, o, after, 0, optsv));
1431 2 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 2 2
1432 2 ▶ EXTEND(SP, 3);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 3); 0 2 2
1433 2 PUSHs(sv_2mortal(res));
1434 2 PUSHs(sv_2mortal(done));
1435 2 PUSHs(sv_2mortal(fail));
1436 2 PUTBACK;
1437 2 n2 = call_method("then", G_SCALAR | G_EVAL);
1438 2 SPAGAIN;
1439 2 ▶ if (!SvTRUE(ERRSV) && n2 > 0) derived = SvREFCNT_inc(POPs);
Branch: 3 branches
BranchTrueFalseTotal
if (!SvTRUE(ERRSV) && n2 > 0) derived = SvREFCNT_inc(POPs); 2 0 2
if (!SvTRUE(ERRSV) && n2 > 0) derived = SvREFCNT_inc(POPs); 2 0 2
if (!SvTRUE(ERRSV) && n2 > 0) derived = SvREFCNT_inc(POPs); 2 0 2
1440 0 ▶ else if (n2 > 0) (void)POPs;
Branch: 1 branch
BranchTrueFalseTotal
else if (n2 > 0) (void)POPs; 0 0 0
1441 2 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 2 0 2
1442 2 ▶ if (derived) return derived;
Branch: 1 branch
BranchTrueFalseTotal
if (derived) return derived; 2 0 2
1443 0 return OA_FIN(oa_error_msg(aTHX_ 500, "could not chain future"));
1444 }
1445 }
1446 { /* blocking: await inline */
1447 0 dSP; int n2; SV *val = NULL;
1448 0 ▶ ENTER; SAVETMPS; PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
ENTER; SAVETMPS; PUSHMARK(SP); 0 0 0
1449 0 ▶ EXTEND(SP, 1); PUSHs(sv_2mortal(res));
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 1); PUSHs(sv_2mortal(res)); 0 0 0
1450 0 PUTBACK;
1451 0 n2 = call_method("get", G_SCALAR | G_EVAL);
1452 0 SPAGAIN;
1453 0 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 0 0 0
if (SvTRUE(ERRSV)) { 0 0 0
1454 0 ▶ SV *e = newSVsv(ERRSV); /* keep past FREETMPS */
Branch: 1 branch
BranchTrueFalseTotal
SV *e = newSVsv(ERRSV); /* keep past FREETMPS */ 0 0 0
1455 0 ▶ if (n2 > 0) (void)POPs;
Branch: 1 branch
BranchTrueFalseTotal
if (n2 > 0) (void)POPs; 0 0 0
1456 0 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 0 0 0
1457 0 resp = oa_error_msg(aTHX_ 500, SvPV_nolen(e));
1458 0 SvREFCNT_dec(e);
1459 0 oa_run_after(aTHX_ &resp, after, env_rv, o->op_id);
1460 0 return OA_FIN(resp);
1461 }
1462 0 ▶ val = n2 > 0 ? SvREFCNT_inc(POPs) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
val = n2 > 0 ? SvREFCNT_inc(POPs) : &PL_sv_undef; 0 0 0
1463 0 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 0 0 0
1464 0 res = val;
1465 }
1466 }
1467 584 resp = oa_map_result(aTHX_ res);
1468 584 SvREFCNT_dec(res);
1469 584 ▶ if (vresp) {
Branch: 1 branch
BranchTrueFalseTotal
if (vresp) { 39 545 584
1470 39 SV *bad = oa_check_response_opts(aTHX_ o, resp, vresp, opts, env_rv);
1471 39 ▶ if (bad) { SvREFCNT_dec(resp); resp = bad; }
Branch: 1 branch
BranchTrueFalseTotal
if (bad) { SvREFCNT_dec(resp); resp = bad; } 2 37 39
1472 }
1473 584 oa_run_after(aTHX_ &resp, after, env_rv, o->op_id);
1474 584 return OA_FIN(resp);
1475 }
1476 #undef OA_FIN
1477 }
1478  
1479 #endif /* OA_PLACK_H */
« API.xs ↑ Summary include/oa_tools.h »