If 51% of the hashrate was controlled by bad actors mining invalid blocks, this would become the longest chain. Where do nodes come into the 51% attack? The canonical chain is the longest chain. Is this true even if less than majority of the nodes accept it. I assume that the canonical chain is the one which majority of full nodes accept as the canonical chain, but how does this fut into block height. Would a 51% attack have to be 51% of hash power and nodes or just hash power? If so, why?
A 51% attack involves just 51% of the hashrate, no nodes are involved.
With a majority of the hashrate, miners can construct a new branch in the chain that overtakes the chain that was previously accepted.
It has to be an otherwise valid chain, as otherwise nodes would reject it. The attack doesn't let the 51% attackers make the network accept any invalid transactions - it can just roll them back.