Jenkins#getLabel unquotes before the cache lookup, so quoted atoms and unquoted expressions collide
Jenkins and plugins versions report
Jenkins 2.568.3. Reproduced on the branch of #27428, which is based on current master. Core only, no plugins involved.
What Operating System are you using (both controller, and any agents involved in the problem)?
Linux (RHEL 8). Not OS-specific.
Reproduction steps
Test in hudson.model.labels with JenkinsRule, each case on a fresh instance:
// Case A: an atom literally named "a&&b" already exists
LabelAtom atom = j.jenkins.getLabelAtom("a&&b");
Label unspaced = j.jenkins.getLabel("a&&b"); // meant as the expression a AND b
Label spaced = j.jenkins.getLabel("a && b");
// Case B: no atom named "x&&y" exists yet
Label quoted = j.jenkins.getLabel("\"x&&y\""); // meant as the quoted atom "x&&y"
LabelAtom atom2 = j.jenkins.getLabelAtom("x&&y");Expected Results
- Case A:
getLabel("a&&b")returns the sameLabelExpression.AndasgetLabel("a && b"). - Case B:
getLabel("\"x&&y\"")returns theLabelAtomx&&y, just likeLabel.parseExpression("\"x&&y\"")does, andgetLabelAtom("x&&y")returns that atom.
Actual Results
- Case A:
getLabel("a&&b")returns theLabelAtom(the same instance asatom), whilegetLabel("a && b")returns anAnd. A job restricted toa&&bis therefore matched against the nodes carrying the atom, not against the nodes carrying bothaandb. - Case B:
getLabel("\"x&&y\"")returns aLabelExpression.And, and the followinggetLabelAtom("x&&y")throws:
java.lang.ClassCastException: class hudson.model.labels.LabelExpression$And cannot be cast to class hudson.model.labels.LabelAtomAnything else?
Jenkins#getLabel(String) unquotes the input first and then uses the unquoted string both as the key into the shared labels map, which also holds atoms keyed by name, and as the input to Label.parseExpression:
expr = QuotedStringTokenizer.unquote(expr);
while (true) {
Label l = labels.get(expr);
if (l != null)
return l;
...
labels.putIfAbsent(expr, Label.parseExpression(expr));After unquoting, the quoted atom "x&&y" and the expression x&&y are the same string. They share one cache entry, and the quoted input is parsed as an expression. The parser itself handles quotes correctly: Label.parseExpression("\"x&&y\"") returns a LabelAtom.
A possible direction: parse the original, still-quoted input, and cache raw expression strings in a map separate from the atoms, so that neither case can collide with an atom name. getLabels() and trimLabels() would then have to cover both maps.
Both cases need an atom whose name contains operator characters, which is unusual. This was split out of the review of #27428, which fixes the related whitespace issue #27403 and deliberately leaves this existing behavior unchanged.
Are you interested in contributing a fix?
Happy to review a fix.
Source: jenkinsci/jenkins