Upwork Scout 作者分析 JSON 欄位改名如何令工作篩選器放行所有職位
My Job Filters Fail Open. A Renamed JSON Field Would Turn Them All Off.
Upwork Scout 作者發現,逐筆容忍缺失資料的解析器與預設放行的篩選器結合後,第三方 JSON 欄位改名可能令整批職位繞過用戶設定的客戶條件。他提出但尚未實作批次健康檢查,統計成功解析及含客戶資料、日期的職位數,並在整批資料異常時回傳 502;若該批完全沒有客戶資料,相關客戶篩選便不會放行職位。文章亦建議保存刪除個人資料的真實 JSON 樣本,為解析結果加入測試。
Upwork Scout is a small SaaS I run that emails freelancers new Upwork jobs matching their filters: categories, keywords, budget, client country, payment verified, minimum client spend, and an optional AI fit score on top. The jobs come from an Apify actor I do not own. I send it a boolean search, it sends back a JSON array, and I turn each item into a job document.
This week I reread the two files that sit on either side of that boundary: the parser that reads the actor's JSON, and the matcher that decides whether a job reaches your inbox. Each one is reasonable on its own. Together they make a promise I never meant to make: if the actor renames a field, the filters for that field quietly turn off, and nobody gets an error.
I have not seen this happen in production. I found it by reading the code. Here is how it fits together.
The parser forgives everything
The actor's output shape is not mine, so I wrote the parser to be tolerant. Every field is read through a small helper that tries a list of paths and returns the first one that has a value:
const pick = (o: any, paths: string[]): any => {
for (const p of paths) {
const v = p.split(".").reduce((a, k) => (a == null ? a : a[k]), o);
if (v !== undefined && v !== null && v !== "") return v;
}
return null;
};
The posted date alone has nine candidate paths, from data.opening.publishTime down to createdOn, because over time I have seen the same data in different places. The client block is read from data.buyer.*, and every value goes through numOrNull, strOrNull or boolOrNull:
const client: JobClient = {
country: strOrNull(pick(r, ["data.buyer.location.country"])),
paymentVerified: boolOrNull(pick(r, ["data.buyerExtra.isPaymentMethodVerified"])),
totalSpent: numOrNull(pick(r, ["data.buyer.stats.totalCharges.amount"])),
rating: numOrNull(pick(r, ["data.buyer.stats.score"])),
hires: numOrNull(pick(r, ["data.buyer.stats.totalAssignments"])),
// ...
};
const hasClientData = Object.values(client).some((v) => v !== null);
If none of those paths exist, the job still parses. It just has client: null. That was deliberate. I did not want one renamed field to throw away a perfectly good job.
There is one place the parser is strict. If the URL does not contain a job id that matches ~0?([0-9a-f]{12,}), or there is no title, parseItem returns null and the item is dropped. No log, no counter.
The matcher lets unknowns through
The matcher has a policy written at the top of the file, and I still agree with it:
// Missing-data policy (consistent across all filters): when a job lacks the
// data a filter needs (v1-era docs, or Upwork hid it), the job PASSES and the
// UI/email flags the unknown instead. Filters only reject on positive evidence.
So every client filter is guarded by a null check:
if (f.paymentVerifiedOnly && c?.paymentVerified === false) return false;
if (f.minClientSpend != null && c?.totalSpent != null && c.totalSpent < f.minClientSpend) return false;
if (f.clientCountries.length && c?.country && !matchCountry(c.country, f.clientCountries)) return false;
The reasoning: Upwork genuinely hides some client data, and old job documents from v1 do not have these fields at all. If "payment verified only" rejected every job where I could not see the flag, users would miss real jobs and blame the product. A false positive costs you a few seconds of reading. A false negative costs you a job you never knew existed. For a job alert tool, failing open is the right default for one missing field on one job.
Put the two together
Now imagine the actor ships a new version where data.buyer becomes data.client. Nothing crashes. Here is what happens, step by step:
-
pickfinds nothing for every client path.clientbecomesnullfor every job. - In the matcher,
c?.paymentVerified === falseis never true.c?.totalSpent != nullis never true.c?.countryis never truthy. - Every client filter passes every job.
A user who set "United States only, payment verified, at least $10k spent" starts receiving every job in their category. The emails look normal. The scan reports success. The only visible change is that the small "Client:" line under each job disappears, because the email template just skips it when there is no client data. Nobody files a bug about a line that is not there.
The same shape applies to dates. The freshness check in the scan route is:
if (j.postedAt && now - j.postedAt > JOB_MAX_AGE_H * 3600_000) continue;
If the date paths all miss, postedAt is null, the condition is false, and the job counts as fresh no matter how old it is. Deduplication against stored jobs stops the same job being sent twice, but the first time an old job shows up, it gets alerted as new.
And the strict case is the mirror image. If the URL format changes so the id regex stops matching, every item is dropped. But billedItems is just items.length, so the run still records the spend, reports newJobs: 0, and returns 200. I wrote about a cousin of this before, when my public job pages went empty and my code could not tell me why. Same lesson, different door: tolerant code is quiet code.
The per-job policy is right. The per-batch policy is missing.
The bug is not "fail open" and it is not "tolerant parsing". Both are correct for a single job. What is missing is any check at the level of the whole batch.
One job with no client data is Upwork hiding something. A whole run where zero out of forty jobs have client data is a schema change. Those two situations look identical to code that only ever asks about one job at a time.
So the fix I am planning, and have not shipped yet, works at the batch level:
// planned, not in the repo yet
type ParseHealth = {
billed: number; // raw items the actor returned
parsed: number; // items that survived parseItem
withClient: number; // parsed jobs with any client data
withDate: number; // parsed jobs with a postedAt
};
function batchLooksBroken(h: ParseHealth): string | null {
if (h.billed >= 5 && h.parsed === 0) return "every item dropped: id or title path changed?";
if (h.parsed >= 10 && h.withClient === 0) return "no client data on any job: buyer path changed?";
if (h.parsed >= 10 && h.withDate === 0) return "no dates on any job: date paths changed?";
return null;
}
Three things change once that exists:
The scan reports it. Those four numbers go into the run's stats next to billedItems and newJobs, so the log line itself shows when parsing degrades, not just when fetching fails.
The run stops pretending. If batchLooksBroken returns a reason, the route returns a 502. The GitHub Actions job that pings the scan only fails when the status is not 200, so this is the difference between a red run and a green one.
Client filters fail closed for that batch only. If the batch has zero client data, a user with a client filter set should get nothing from that batch rather than everything. One missing field on one job still passes, exactly like today. A missing field on every job means the data source changed, and "you got no alerts for an hour" is a much better failure than "you got forty alerts that ignore your filters".
A fixture I should have written on day one
The parser has a comment that says parseItem is "Exported for tests". There are no tests. The only check in the repo is a smoke script that hits the live pages and API.
The cheapest useful test here is not clever. It is one real item from the actor, saved as a JSON file with personal details removed, and a test that asserts the parsed job has a non-null client, postedAt, budget and skills. When the actor changes, the first thing I do is pull a fresh item, drop it next to the old one, and see which assertions break. That turns "the emails feel noisier lately" into a diff.
I already had the evidence for this. The header comment in the parser says the field paths were "verified against a real dataset item". I verified them once, by hand, and kept the conclusion instead of the item.
What I would tell myself before writing the parser
- Tolerant parsing and fail-open filtering are both fine. Just never let them meet without a counter in between.
- Count what you drop.
billed,parsed, and "parsed with the field I filter on" are three numbers and they cost nothing. - Decide per batch, not only per item. The question "is this field missing?" has a different right answer from "is this field missing everywhere?"
- A filter a user set is a promise. If you cannot evaluate it for a whole batch, say so, rather than silently treating it as satisfied.
- Keep a raw fixture from the third party you do not control. Your mental model of their schema is not a test.
If you are building anything on top of a scraper or a third-party API you do not own, check whether your "unknown passes" rule has a ceiling. Mine did not. If you want to see the product this lives in, it is Upwork Scout, and the matching pipeline behind it is in an earlier post about running cheap filters before the LLM.
How do you handle this in your own pipelines: do your filters fail open, fail closed, or does it depend on how much of the batch is missing?
來源:DEV Community · dev.to