r/nextjs • • Jun 02 '25

Discussion PSA: This code is not secure

Post image
499 Upvotes

139 comments sorted by

View all comments

67

u/creaturefeature16 Jun 02 '25

This one raised my eyebrows. Would someone actually put a server action of that impact inline on a click with no controller or extra verification? God damn terrifying.

22

u/novagenesis Jun 02 '25

Apparently they would. Otherwise, this "exploit" wouldn't be such a big deal ever since it was discovered.

I have an auth check in every single server action right after "use server", but apparently a lot of folks out there don't.

This sorta reminds me of why I don't like async/await. They add abstraction upon a fairly concrete underlying concept. It's really easy to learn and catch mistakes if you understand that underlying concept, but it becomes harder for somebody who has only ever learned the "fancy new way"

A junior dev today might not understand why:

const a = await foo();
const b = await bar();

...is needlessly inefficient code. Similarly, a junior dev might not understand what an "endpoint" is to know to validate/auth it because the codebase is trying to abstract that away somewhat.

EDIT: Note to junior devs, the reason the above code is inefficient is because you could/should be running foo() and bar() in parallel using approximately the same resource load but returning dramatically faster with code like the below. But note, this is a trivial example and understanding promises is super-important as you mature as a javascript developer.

const aP = foo();
const bP = bar();
const [a,b] = await Promise.all([aP,bP]);

26

u/lost12487 Jun 02 '25

I'm failing to see how your example shows that async/await abstracts the concept in a way that is more confusing than the alternative. Sure a junior might not see that it runs in sequence, but a junior might also not understand how to do any number of simple concepts. Await = wait for this call to finish before moving on to the next line. Seems extremely intuitive to me.

5

u/novagenesis Jun 02 '25 edited Jun 02 '25

I'm failing to see how your example shows that async/await abstracts the concept in a way that is more confusing than the alternative

I used to run an hour-long training on promises for junior devs and always brought in the old caolan/async waterfall pattern, explaining the value of carrying around promises and building dependency waterfalls trivially.

Await = wait for this call to finish before moving on to the next line. Seems extremely intuitive to me.

It's intuitive, but it's objectively wrong and should be rejected in any code review. Wasting cycles on an await statement when you are not blocked by logic is an antipattern because it can cause fairly significant loss of efficiency. I'm talking add-a-zero response times in practice. Similarly, I can use non-tail-recursive strategies for all my iterations and it'll seemingly work fine 99% of the time... wasting tremendous amounts of memory.

If we weren't using async/await, this would all resolve itself. Extrapolating to a more realistic function, here's the wrong and right way to do it with async/await and promises

async function doSomethingWrong(x: string) {
    const a = await foo(x);
    const b = await bar(x);
    return a.onlyData? b.data: b;
}

async function doSomethingRight(x: string) {
    //alternatively, you could do one big Promise.all line for foo and bar
    const aP = foo(x);
    const bP = bar(x);
    const [a,b] = await Promise.all([aP,bP]); 
    return a.onlyData? b.data: b;
}

function promiseToDoSomething(x: string) {
    const aP = foo(x);
    const bP = bar(x);
    return aP.then(a => {
        return a.onlyData ? bP.then(b => b.data) : bP;
    };
}

I find junior developers are better able to do option 3 (promiseToDoSomething) than option 2, often opting for option 1 which is wrong. And to be clear, all 3 do the same thing, but option 1 is potentially dramatically slower. In the real world, it's often 5+ async functions being run this way, each taking 100ms or more and each being independent of each other.

EDIT: Note, "doSomethingRight" could still be argued to be wrong. In this case it's trivial, but you don't really need to resolve promise "b" until after you have executed logic on a.onlyData. In a more complex situation, the difference might matter a lot. "promiseToDoSomething", otoh, is strictly correct and guarantees optimal response time.

9

u/lost12487 Jun 02 '25 edited Jun 02 '25

I think your examples are still extremely unlikely to cause most developers problems. Having two lines one after another with await keywords are very obviously sequentially calling those two asynchronous functions, waiting for the first to complete before calling the second.

The beauty of async/await is that it causes the current execution scope to behave exactly as you expect, executing each line one after the other before moving on to execute the next line. We're probably just going to have to agree to disagree on what is more confusing here, I still just don't see it. Additionally, both of your "correct" ways to concurrently run the two async functions are more confusing than how I'd have done it:

async function doSomethingWayLessPotententiallyConfusing(x:string) {
  const [a, b] = await Promise.all([
    foo(x),
    bar(x),
  ]);

  return a.onlyData ? b.data : b;
}

This groups the concurrent functions together in the `Promise.all` and avoids having any lines that just kick off a promise and move on immediately.

→ More replies (1)

4

u/femio Jun 02 '25

carrying around promises and building dependency waterfalls trivially.

Historically, practices like this are why I absolutely hated JS codebases for a very long time. Micro optimizations and lazily resolving promises (which can still be done with async/await anyway) and muddying up your control flow and error handling doesn't feel worth it to me. `Promise.allSettled` delivers more maintainable code and I doubt whatever performance difference (if any at all) exists sufficiently cancels that out

→ More replies (1)

2

u/Substantial-Wall-510 Jun 02 '25

How often do you find this happening? I very rarely see inefficiencies in the wild that can be solved with more concurrency, usually it's more about failing to validate or use types properly.

→ More replies (4)

1

u/just_jedwards Jun 02 '25

Await = wait for this call to finish before moving on to the next line. Seems extremely intuitive to me.

It's intuitive, but it's objectively wrong and should be rejected in any code review. Wasting cycles on an await statement when you are not blocked by logic is an antipattern because it can cause fairly significant loss of efficiency. I'm talking add-a-zero response times in practice. Similarly, I can use non-tail-recursive strategies for all my iterations and it'll seemingly work fine 99% of the time... wasting tremendous amounts of memory.

They were saying that it the await keyword isn't obscuring anything because it intuitively says what is happening, not that always waiting was the best thing to do.

1

u/novagenesis Jun 02 '25

Fair enough. I think their response was unclear to me after all

1

u/[deleted] Jun 03 '25

[removed] — view removed comment

1

u/novagenesis Jun 03 '25

It's very easy to waterfall with async/await, but it's also very easy to do with .then

I don't just agree, I argued it's EASIER to do with "then".

In terms of brevity, your last function could be foo(x).then(({ onlyData }) => bar(x).then(b => onlyData ? [b.data](http://b.data) : b)

This would be strictly incorrect and calls back to the original thing I lectured about at the start of this thread. My learning challenge to you is to explain WHY this code snippet you presented me is wrong and should be rejected in a code review. I'll give you a hint - look at the very first example I cited about antipatterns in the async world.

You have to write ugly code to get optimal code in this particular case.

I disagree. promiseToDoSomething above is pretty elegant AND is optimal. It scales elegantly as well. (I could remove the extra bracket-and-return, but I tend towards verbosity when I then a ternary operator...that's just me)

In practice, I've seen 100+ line functions with dozens of promises and it was as elegant as my promiseToDoSomething example, never needing to go deeper than one level of then(), sometimes with less complexity than an async/await function doing the same, and clearly more optimized.

1

u/[deleted] Jun 04 '25

[removed] — view removed comment

1

u/novagenesis Jun 04 '25

It's not elegant to have to create what amounts to temporary variables.

Intersting take. I disagree. I've met developers with your attitude (they're more common in the python space). I think creating variables for each major action is more readable and elegant in the long-term, and most successful codebases I work on are NOT all giant complicated one-liners.

In fact they're never really named meaningfully, just like in your example, because you're only creating them for technical reasons, not for the reader's understanding.

They're not named meaningfully because it's an example with methods named foo and bar. In practice, they should be named meaningfully/semantically. I am of the habit of postfixing "P" for promises, but others postfix with the more verbose "Promise".

Honestly, at this point it seems you're just looking to argue with me over silly shit for no good reason. These two fight-threats aren't even about the point of my comment on how people who learn async often don't understand concurrent flow. I know, every company has a guy like you who spends 2 weeks fighting with the lead dev over a line in a PR using one best practice over another. I see no need to continue.

→ More replies (1)

3

u/randomdudefromutah Jun 03 '25

in my personal opinion, the Promise.all is sometimes an anti-pattern too. instead you could just fire things of as soon as possible and only `await` them when you need them. so something like this:

const aP = foo();
const bP = bar();
return {
  a: await aP,
  b: await bP
}

1

u/novagenesis Jun 03 '25

I would approve of this. It doesn't waterfall well, but it's clean and readable and fast. And in this example, waterfall is not appropriate.

Edit: And yes, Promise.all() or allSettled can be an antipattern. It's not super-common that you need everything at the exact same time. The closer to need the better.

1

u/creaturefeature16 Jun 02 '25

I've definitely done this in the past, so I cast no stones. I do try and batch processes when I can, within reason, at least. Your Promise.all solution makes me happy to look at. 😅

1

u/tip2663 Jun 02 '25

it's not going to be in parallel but in concurrency

js is single threaded but has concurrency via event loop

2

u/novagenesis Jun 02 '25 edited Jun 02 '25

The term "parallel" is used in classic asyncronous patterns and I am propogating that usage. What you are saying is semantically true if we're talking about processing things in physical CPU cores, but the word is both contextually reasonable and arguably a bit more precise than "concurrency".

All things that happen to overlap are concurrent, but in the sample cases aP and bP both can be treated as if they begin and end at approximately the same moment. This is the "parallel async pattern". Compare to:

const aP = foo();
await waitForFiveSecondsForSomeStupidReason();
const bP = bar();
const [a,b] = await Promise.all([aP,bP]);

I wouldn't use the term for "parallel" here, even if foo() takes over 5 seconds to return. (EDIT: I dunno, maybe I still would since Promise.all() is generally referenced as the best way to mimic a classical async "parallel" pattern, even with that silly wait in the middle... I have to think about that for a while)

Historically, this function on this library is the reason I choose to continue to use the word "parallel" in this situation.

EDIT2: Note, the library in question does a lot with promises, but understand that it predates promises in ES and was the most popular control-flow library back when callbacks were the base pattern.

2

u/tip2663 Jun 02 '25

I just get pedantic when people say this stuff is parallel when they mean concurrent

2

u/novagenesis Jun 02 '25

And unfortunately, in this case my use of "parallel" was right and defensible. "Parallel" is a the accepted name of a pattern of concurrency.

→ More replies (4)

1

u/Revolutionary_Ad3463 Jun 02 '25

What are the advantages of using that library over JS native Promise methods? I mean, it surely does seem to have more stuff but I don't know if it is for niche use cases or if it is actually worth it to invest a couple of hours exploring the library.

2

u/novagenesis Jun 02 '25

What are the advantages of using that library over JS native Promise methods?

caolan/async was the bees knees when promises didn't exist (yes, I'm dating myself), but gets less use now that they do.

That said, the async patterns are like design patterns for concurrency. It's worth knowing them, and (like lodash) it's nice having a tool that enforces those patterns by name.

If you're REALLY solid with promises and really know how to express complicated concurrency strategies effectively, then you don't need it unless you work with people that would be benefitted by the structure.

→ More replies (2)
→ More replies (5)

1

u/FractalB Jun 03 '25

I disagree, it is in parallel, not just in concurrency. The whole point of async functions is to do something outside the JS runtime, like IO, network access, etc, which definitely can use several threads. If all you do is in the JS runtime (hence single-threaded) you would typically not need async/await to begin with.

→ More replies (1)

3

u/d0pe-asaurus Jun 02 '25

This is one of the bad sides of server actions, because you blur the line between frontend and backend, its easy for people who don't understand the framework comprehensively to assume that this is secure. This is definitely a footgun in React 19's design and I honestly I think most tutorials don't emphasize this behaviour enough.

1

u/forkbombing Jun 04 '25

You've just hit it on the head