Última actualización: 2026-12-02

DAY 013 OF 1600 · 2026-09-28

Day 013 — The one axis that keeps the spread

A student's private learning log · one concept at a time. Date: 2026-09-28 · Day: 13 of 1600 Log: a student's private learning log · one concept at a time. ---

Concept #13 — PCA: instead of picking the best column, build a new axis where the data is widest

Twelve days of classifiers all did the same thing in the end: they drew a boundary in the space of the features I gave them . Today I stopped asking how to split the data and asked a question underneath that one — *are these even the right axes?* That is principal component analysis , and it exists because the columns we collect are almost never the directions in which the data actually varies most. The course slides (MA01, Week 4 — Dimensionality Reduction (PCA & LDA) ) put a trap on it in plain letters, and I have to be honest that I nearly fell into it. The lazy reading of "reduce the dimensions" is *keep the columns that look most useful and drop the rest* — that is feature selection . PCA is not that. PCA builds brand-new columns by mixing the old ones together, and it picks the mix that points along the direction where the cloud of points is stretched the widest . The first such direction is PC1 : the single axis that keeps the most spread (variance). The second, PC2 , is the widest direction perpendicular to PC1, and so on. Why the widest direction? Because variance is information. If two features move together — tall people also weigh more — then almost everything the two columns know is already captured by one combined axis running along their diagonal. Keeping that one axis loses very little; the second axis only carries the small leftover difference. And a new axis that is a mix can beat any single original column, because it is allowed to lean into the correlation the original columns share. What I tried today: I built PCA from scratch with nothing but the standard library. I generate two features that share a hidden driver (so they are correlated), standardise them so neither has a size advantage, build the covariance matrix , and find its top eigenvector — the PC1 direction — with power iteration (keep multiplying the matrix by a vector and re-normalising until it stops turning). Then I measure, honestly, two things: how much of the total variance PC1 keeps, and how much is kept by the lazy plan of just throwing one original column away. Both numbers use the same data. #!/usr/bin/env python3 # pca_stdlib.py - principal component analysis by hand, pure standard library. # MA01 (Machine Learning), Week 4 "Dimensionality Reduction (PCA & LDA)". # # The trap the course warns about: PCA is NOT "picking the best column". It # builds a NEW axis -- a combination of the old ones -- aimed at the direction # where the data is spread the widest. Here I compute that axis with power # iteration on the covariance matrix and compare it, honestly, against the # lazy alternative of simply dropping one original feature. import math, random def make_data(seed, n): rnd = random.Random(seed) rows = [] for _ in range(n): latent = rnd.gauss(0.0, 1.0) # the hidden thing driving both columns x1 = latent + rnd.gauss(0.0, 0.35) # column 1: latent + its own noise x2 = 0.85 * latent + rnd.gauss(0.0, 0.35) # column 2: same latent, weaker rows.append((x1, x2)) return rows def standardize(rows): n = len(rows) cols = list(zip(*rows)) means = [sum(c) / n for c in cols] stds = [math.sqrt(sum((v - m) ** 2 for v in c) / n) or 1.0 for c, m in zip(cols, means)] return [tuple((v - m) / s for v, m, s in zip(r, means, stds)) for r in rows] def covariance(rows): n = len(rows) p = len(rows[0]) cov = [[sum(r[i] * r[j] for r in rows) / n for j in range(p)] for i in range(p)] return cov def mat_vec(m, v): return [sum(m[i][j] * v[j] for j in range(len(v))) for i in range(len(m))] def power_iteration(cov, iters=200): p = len(cov) v = [1.0 / math.sqrt(p)] * p for _ in range(iters): w = mat_vec(cov, v) norm = math.sqrt(sum(x * x for x in w)) or 1.0 v = [x / norm for x in w] eigenvalue = sum(v[i] * mat_vec(cov, v)[i] for i in range(p)) return eigenvalue, v def trace(cov): return sum(cov[i][i] for i in range(len(cov))) def residual_variance(rows, axis): # project onto the axis, reconstruct, measure what is left over n = len(rows) left = 0.0 for r in rows: proj = sum(a * b for a, b in zip(axis, r)) recon = [proj * a for a in axis] left += sum((a - b) ** 2 for a, b in zip(r, recon)) return left / n rows = standardize(make_data(7, 4000)) cov = covariance(rows) total = trace(cov) ev, pc1 = power_iteration(cov) kept = ev / total # best single original feature = keep the column with the largest variance (all 1.0 here) best_col_var = max(cov[i][i] for i in range(len(cov))) drop_col_kept = best_col_var / total print("standardised data, 2 features, 4000 points (all feature variances = 1.000)") print(f"covariance off-diagonal : {cov[0][1]:.3f} (features move together)") print(f"PC1 direction (unit vector) : [{pc1[0]:.3f}, {pc1[1]:.3f}]") print(f"PC1 variance : {ev:.3f}") print(f"variance kept by PCA (1 axis): {kept*100:.1f}%") print(f"variance kept dropping a column: {drop_col_kept*100:.1f}%") print(f"residual (lost) variance PCA : {residual_variance(rows, pc1):.3f}") Real output ( python3 pca_stdlib.py , Python 3.11.15): standardised data, 2 features, 4000 points (all feature variances = 1.000) covariance off-diagonal : 0.874 (features move together) PC1 direction (unit vector) : [0.707, 0.707] PC1 variance : 1.874 variance kept by PCA (1 axis): 93.7% variance kept dropping a column: 50.0% residual (lost) variance PCA : 0.126 What I understood from it: the two features share a driver, so their covariance off the diagonal is 0.874 — almost the whole 1.0 of a standardised column. The power iteration settles on the direction [0.707, 0.707] — a perfect 45° mix, dead between the two columns, which is exactly where a correlated cloud is longest. One axis along that mix keeps 93.7% of everything. Now the honest comparison: both original columns have variance 1.000, so the best possible single column keeps 50.0% — half of the total is on the diagonal, and one column can only see its own half. So the number that matters is 93.7 against 50.0. The lazy plan loses 43.7 points of variance; PCA loses 6.3 . That gap is the whole idea: PC1 was allowed to lean into the correlation, so it captured both columns' shared motion at once, while any single column stays blind to the other. And the residual — 0.126 — is just the noise I planted (two 0.35-noise features), which no rotation can remove, because it is genuinely irreducible. That is what "dimensionality reduction" sells: not a smaller copy of the columns, but a smarter axis that spends its one dimension where the data actually has something to say. ---

Security #13 — Prototype pollution: a deep-merge that edits the objects you did not pass it (CWE-1321)

What I learned about this topic — contained, sandbox only, no live targets: The last injection days (SQL, commands, templates) all had the same shape: *my input was read as code by a parser*. Today's bug is stranger, and it is a hole I had not really understood. In JavaScript, prototype pollution (CWE-1321) . It is not about a query or a template. It is about the object model itself . Every plain object in JavaScript inherits from one shared ancestor, Object.prototype . If anything adds a property to that ancestor, **every object in the process suddenly has that property** — objects that already existed, objects the attacker never saw, objects not yet created. And the door is usually a "helpful" deep-merge / recursive-extend function : the kind of utility that walks a user-supplied JSON body and copies each key into a config or a record. If the body contains a __proto__ key — the magic key that means "reach up to the ancestor" — the merge follows it and plants a property where the whole app can see it. Why this is an auth bypass , not a curiosity: server-side authorization code is often written as a truthy check. if (user.isAdmin) { ... } . The check assumes isAdmin is absent unless that user has it. But after pollution, isAdmin is inherited by every object, so the check passes for users who never had the flag, sometimes for anyone. One crafted {"__proto__":{...}} in a request body can flip a global switch for the rest of the process's life — and because nothing wrote to a user record, it is easy to miss in a diff. I reproduced it in my sandbox (/tmp): a naive recursive merge, a mock attacker-controlled JSON body, and a plain "session user" check. Everything is fake and local; no network, no target. Then I wrote the fix and re-ran. The pattern I studied: // A "helpful" config merge utility. Walks the source, copies every key. function deepMerge(target, source) { for (const key in source) { if (typeof source[key] === 'object' && source[key] !== null) { if (!target[key]) target[key] = {}; deepMerge(target[key], source[key]); // follows __proto__ straight up } else { target[key] = source[key]; } } return target; } // The attacker controls the JSON body. They never touch a real user record. deepMerge({}, JSON.parse('{"__proto__":{"isAdmin":true}}')); const sessionUser = {}; // created elsewhere, never granted admin if (sessionUser.isAdmin) { /* ACCESS GRANTED -- inherited from the prototype */ } What I understood about preventing it: function safeMerge(target, source) { for (const key of Object.keys(source)) { // 1. refuse the keys that reach the prototype chain if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue; const val = source[key]; if (val && typeof val === 'object') { // 2. build children with a null prototype so they inherit nothing target[key] = safeMerge(Object.create(null), val); } else { target[key] = val; } } return target; } // Rules: // - Merge only own, expected keys; allow-list the schema, do not black-list. // - Reject/strip __proto__, constructor, prototype on ANY untrusted input. // - Use null-prototype objects (Object.create(null)) or a Map for configs. // - Freeze the prototypes you never intend to change (Object.freeze(Object.prototype)). // - Authorization must read an own field (hasOwnProperty / explicit column), // never a truthy inherited one. Sandbox check (local only, /tmp, no network, no target, Node v22.23.1): $ node prototype_pollution.js before attack isAdmin = undefined after attack isAdmin = true -> ACCESS GRANTED (bypass) fixed merge isAdmin = undefined -> denied (safe) What I understood: the first line is the world before the attack — a brand new object has no isAdmin , so the check would be undefined and the guard would hold. Then one merge of one JSON body, and a **completely different, never-touched object** answers true . That is the part I had been missing: the attacker's input never became a user; it became a property of the *ancestor that every user inherits from*. The authorization code was correct — it read sessionUser.isAdmin faithfully. It just could not tell the difference between "this user was granted admin" and "every object in this process now says admin". The fixed line shows the same payload going in and changing nothing, because the merge refuses to follow __proto__ and the child object it builds inherits from nothing. The lesson lands right next to day 6 (IDOR): access checks are only as strong as the identity they actually read. Read an owned, explicit field — not one that an untrusted merge could have handed to everyone. ---

Day 13 notes

Concept #13: PCA from scratch — PC1 = [0.707, 0.707] keeps 93.7% of the variance vs 50.0% for dropping a column. ✔ Security #13: prototype pollution (CWE-1321) — {"__proto__":{"isAdmin":true}} turns undefined into true on an untouched object; null-proto + key guard blocks it. ✔ 1587 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 013 of 1600 · Matías Rathgeb


[ inicio ]   [ proyectos ]   [ posts ]   [ daylog ]


Página estática. Sin cookies, sin javascript, sin fuentes externas.
Contacto: ver inicio.