Jimmy Gopperth justified his selection over Ian Madigan at fly-half by scoring two tries as Leinster came from 14-0 down to beat Castres in France.
Scotland lock Richie Gray scored the first try for Castres with Brice Dulin getting the second in the 21st minute.
Gopperth scrambled over for a try after a fine break by Luke Fitzgerald and scored again seconds before half-time while Jordi Murphy got the third try.
Centre Remi Lamerat's late touch down earned Castres a losing bonus point.
It was far from Leinster's best display of the season but the hard-earned victory means they are virtually assured of a place in the quarter-finals.
The Irish province remain top of Pool Six, four points ahead of second-placed Northampton who ran out 29-17 victors over Ospreys in Swansea.
It was Castres' first home defeat in 19 games, but they started well, scoring a fantastic opening try when Remi Lamerat's mazy run set up Gray to score.
Lamerat then played a part in the second try, bumping off a couple of tackles before feeding winger Remi Grosso who passed back inside to full-back Dulin for a second great try for the French side.
But Castres were left kicking themselves after conceding a soft try from a scrum 10 metres from their own line, Gopperth skipping through some weak defence to dot down.
Kiwi Gopperth claimed a second try shortly after, driving over from close range to leave it 17-12 at half-time.
Gopperth then drew Leinster to within two points with a penalty and full-back Rob Kearney then nailed a long-range drop-goal to edge the Irish province into an 18-17 lead.
Momentum had truly swung Leinster's way, Gopperth kicking a quick brace of penalties for a 24-17 lead.
Flanker Murphy was played in for Leinster's third try to seal a vital win, Lamerat scoring a deserved late consolation try for the home side.
Castres: B Dulin; R Grosso, S Bai, R Lamerat, M Evans: R Tales (capt), C Garcia: Y Forestier, M-A Rallier, K Wihongi, R Gray, C Samson; M Babillot, I Diarra, P Faasalele,
Replacements: Garvey for Bai (65), Lazar for Garcia (60), Tomas for Forestier (60), Mach for Rallier (51), Peikrishvili for Wihongi (51), Caballero for Diarra (62), Desroche for Faasalele (69).
Leinster: R Kearney; D Kearney, B O'Driscoll, G D'Arcy, L Fitzgerald; J Gopperth, E Reddan; J McGrath, S Cronin, M Ross, D Toner, M McCarthy, K McLaughlin, J Murphy, J Heaslip (capt).
Replacements: Madigan for D'Arcy (75), Boss for Reddan (65), Healy for J. McGrath (60), Moore for Ross (60), Cullen for McCarthy (65), Jennings for K. McLaughlin (51).
Not used: Dundon, Kirchner.
Sin bin: S. Cronin (69).
Referee: Nigel Owens.