How does Bitcoin Core know it's on the longest chain?
First of all, finding the longest chain is not the goal, but the chain with the most accumulated proof-of-work [1]
Now, finding the most-work chain is the entire goal of the full node. The whole meaning of its existence is finding the most-work chain, and so you can pick almost any line out of the networking and validation modules of the code and explain it in those terms.
To be a bit more specific:

The full node connects to at least 8 peers. More recent versions connect to 2 extra peers in 'blocks only' mode. Peers are chosen to be as diverse as possible (by IP subnet or AS map). If a new block has not been added within a certain timeout (I think it's 40 minutes) Bitcoin Core adds one more outgoing peer.
The full node sends a getheaders request to each peer and keeps track of the best block each peer knows about.
If a peer has a valid block header with greater accumulated work than our current tip, we ask it for the corresponding blocks. If those blocks are valid, it becomes our new chain tip. A reorganization may or may not be necessary to get to that state.

If you understand conceptually how headers-first sync works, the function FindNextBlocksToDownload() is the next step. This is where the node decides if a peer has headers with greater work than its current chain tip, and requests those blocks from that peer.
So all we can do is connect to a lot of peers and assume that at least one of them knows about the most-work chain. This makes peer discovery and choosing which peers to connect to of critical importance.