GitLabgitlab-org
cli
main
1package login
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9 "regexp"
10 "strings"
12 "gitlab.com/gitlab-org/cli/internal/fsx"
13)
15// mavenSettingsTemplate is written when no ~/.m2/settings.xml exists yet.
16const mavenSettingsTemplate = "<settings>\n <servers>\n </servers>\n</settings>\n"
18// mavenServersCloseRe locates the closing </servers> tag, capturing its
19// indentation, so a new <server> block can be inserted just before it and
20// indented one level deeper than the section it joins.
21var mavenServersCloseRe = regexp.MustCompile(`(?m)^([ \t]*)</servers>`)
23// mavenServersSelfClosingRe matches a self-closing <servers/>, capturing its
24// indentation. The element is valid and means "no servers configured", but it
25// has no closing tag to insert a block before, so it has to be expanded into
26// a real section instead.
27//
28// The trailing class accepts \r so a CRLF file's line separator is consumed
29// whole. Without it the \n is left behind on its own and the expansion leaves
30// a line holding nothing but a carriage return.
31var mavenServersSelfClosingRe = regexp.MustCompile(`(?m)^([ \t]*)<servers[ \t]*/>[ \t\r]*\n?`)
33// mavenSettingsCloseRe locates the closing </settings> tag, capturing its
34// indentation, so a whole <servers> section can be added to a settings.xml
35// that has none — a file holding only <mirrors> or <profiles> is common.
36var mavenSettingsCloseRe = regexp.MustCompile(`(?m)^([ \t]*)</settings>`)
38// mavenSettingsCloseAnyRe matches a </settings> tag wherever it sits, including
39// one sharing a line with another element. It only shapes the error message for
40// a file mavenSettingsCloseRe cannot place a section in.
41var mavenSettingsCloseAnyRe = regexp.MustCompile(`</settings>`)
43// mavenServersOpenRe matches a <servers> opening tag, self-closing or not,
44// anywhere in the file. It guards the "add a whole section" path: a file whose
45// <servers> element the line-anchored patterns above can't place a block into
46// (both tags on one line, for example) already has one, and adding a second
47// would produce invalid XML.
48var mavenServersOpenRe = regexp.MustCompile(`<servers[ \t]*/?>`)
50// mavenServerBlockRe matches a single <server>...</server> block. Since
51// </server> tags don't nest, a lazy match from one <server> to the nearest
52// following </server> always captures exactly one block, never spanning
53// into a neighboring block — unlike a regex that also requires a specific
54// <id> to appear within the same lazy span, which can cross an unrelated
55// block's boundary when the target block isn't the first one in the file.
56var mavenServerBlockRe = regexp.MustCompile(`[ \t]*<server>[\s\S]*?</server>\n?`)
58// mavenServerCloseRe locates a single block's </server> tag at the start of
59// its own line, capturing the leading indentation so a child element
60// inserted before it lines up with the block's existing children.
61var mavenServerCloseRe = regexp.MustCompile(`(?m)^([ \t]*)</server>`)
63var (
64 mavenUsernameRe = regexp.MustCompile(`(?s)<username>.*?</username>`)
65 mavenPasswordRe = regexp.MustCompile(`(?s)<password>.*?</password>`)
66)
68// mavenCommentRe matches one XML comment. XML forbids "--" inside a comment, so
69// a lazy scan to the first "-->" always ends at that comment's real terminator.
70var mavenCommentRe = regexp.MustCompile(`(?s)<!--.*?-->`)
72// mavenMaskComments returns a copy of content with every byte inside an XML
73// comment replaced by a space, keeping line separators so line-anchored
74// patterns still see the same lines, and keeping length so an index into the
75// copy addresses the same byte in content. Every pattern in this file is
76// matched against the copy and every slice is taken from content.
77//
78// Every pattern here is otherwise comment-blind, which is not a theoretical
79// concern: the settings.xml that ships with apache-maven consists almost
80// entirely of commented-out <server> and <servers> examples. Without masking,
81// the first </servers> in such a file is inside a comment, so the new block is
82// inserted there, and the <id> it writes then makes findMavenServerBlock claim
83// the commented block on every later refresh, so the live section never
84// receives credentials at all.
85//
86// Masking rather than discarding matches that start inside a comment, which is
87// what this used to do: the lazy patterns can start at a tag named in a prose
88// comment ("add one <server> entry per registry") and run to the live element's
89// closing tag, so discarding that match discards the live element with it. The
90// live <server> block then looks absent and gets a duplicate <id> appended,
91// where Maven silently keeps the stale first block, and a live <password> gets
92// a second <password> inserted next to it, which makes settings.xml
93// non-parseable. Masking removes the commented tag instead of the match around
94// it, so the live element is still found.
95func mavenMaskComments(content string) string {
96 masked := []byte(content)
97 for _, span := range mavenCommentRe.FindAllStringIndex(content, -1) {
98 for i := span[0]; i < span[1]; i++ {
99 if masked[i] != '\n' && masked[i] != '\r' {
100 masked[i] = ' '
101 }
102 }
103 }
104 return string(masked)
105}
107// mavenIndent returns the indentation to give a generated element, from the
108// [start, end) span a pattern captured as the leading whitespace of its line.
109// start is the start of that line, since every pattern capturing an indent here
110// is anchored with ^.
111//
112// The span is captured from the mask, where a comment sharing the line
113// ("<!-- x --></servers>") reads as blanks, so it can cover bytes that are not
114// whitespace in content at all. Only the line's real leading whitespace is
115// kept: otherwise the new element is indented by the width of somebody's
116// comment.
117func mavenIndent(content string, start, end int) string {
118 indent := content[start:end]
119 if i := strings.IndexFunc(indent, func(r rune) bool { return r != ' ' && r != '\t' }); i >= 0 {
120 indent = indent[:i]
121 }
122 return indent
123}
125// mavenXMLText escapes the characters that cannot appear literally in XML text
126// content. Only the credential values go through it: the token comes straight
127// from the server response, and a token format that ever carried an "&" would
128// otherwise write XML that Maven rejects and that these regexes can no longer
129// find on the next refresh.
130//
131// alias is deliberately not escaped. registryAliasRe restricts an explicit
132// --registry-alias to [a-zA-Z0-9._-] and defaultRegistryAlias sanitizes a
133// derived one, so there is nothing to escape today. If that ever loosens, the
134// <id> written here and the idRe that finds the block again in
135// upsertMavenServer have to start escaping together, or a refresh would stop
136// matching the block it wrote.
137var mavenXMLText = strings.NewReplacer("&", "&", "<", "<", ">", ">")
139// loginMaven configures path, or ~/.m2/settings.xml when path is empty, with a
140// <server> block keyed by <id>alias</id> so that Maven authenticates against
141// the registry using HTTP Basic auth ("__token__" / token). If a <server> with
142// this alias's <id> already exists, its credentials are updated in place;
143// everything else in the file is preserved byte-for-byte, including on the
144// error path.
145//
146// The registry URL is not a parameter: Maven's <server> block carries only the
147// alias/token pair, and the URL itself lives in the caller's pom.xml or
148// settings <repositories>, keyed by the same alias.
149func loginMaven(path, alias, token string) error {
150 if path == "" {
151 home, err := homeDir()
152 if err != nil {
153 return err
154 }
155 path = filepath.Join(home, ".m2", "settings.xml")
156 }
157 dir := filepath.Dir(path)
159 content, err := os.ReadFile(path)
160 switch {
161 case err == nil:
162 // An existing but empty file has no <servers> section and no
163 // </settings> tag to add one to, so it would otherwise fail with
164 // "found neither a <servers> section nor a </settings> tag". Treated
165 // like a missing file instead: `touch ~/.m2/settings.xml`, or an
166 // interrupted editor session, is a plausible way to get here.
167 if len(bytes.TrimSpace(content)) == 0 {
168 content = []byte(mavenSettingsTemplate)
169 }
170 case os.IsNotExist(err):
171 content = []byte(mavenSettingsTemplate)
172 default:
173 return fmt.Errorf("reading %s: %w", path, err)
174 }
176 updated, err := upsertMavenServer(string(content), alias, token)
177 if err != nil {
178 return fmt.Errorf("updating %s: %w", path, err)
179 }
181 if err := os.MkdirAll(dir, 0o700); err != nil {
182 return fmt.Errorf("creating %s: %w", dir, err)
183 }
184 if err := fsx.WriteOwnerOnly(path, []byte(updated)); err != nil {
185 return fmt.Errorf("writing %s: %w", path, err)
186 }
188 return nil
189}
191// upsertMavenServer returns content with a <server> block for alias that
192// authenticates as "__token__"/token, handling the settings.xml shapes that
193// occur in practice: an existing block for this alias, an existing <servers>
194// section, a self-closing <servers/>, and no <servers> element at all.
195func upsertMavenServer(content, alias, token string) (string, error) {
196 // \s* around the alias because Maven trims element text, so
197 // "<id> my-alias </id>" is the same id as "<id>my-alias</id>". Matching only
198 // the untrimmed spelling appended a second block with the same id, and Maven
199 // keeps using the stale first one.
200 idRe := regexp.MustCompile(`<id>\s*` + regexp.QuoteMeta(alias) + `\s*</id>`)
201 masked := mavenMaskComments(content)
203 if loc := findMavenServerBlock(masked, idRe); loc != nil {
204 block, err := updateMavenServerCredentials(content[loc[0]:loc[1]], masked[loc[0]:loc[1]], token)
205 if err != nil {
206 return "", err
207 }
208 return content[:loc[0]] + block + content[loc[1]:], nil
209 }
211 if m := mavenServersCloseRe.FindStringSubmatchIndex(masked); m != nil {
212 indent := mavenIndent(content, m[2], m[3]) + " "
213 return content[:m[0]] + mavenServerBlock(alias, token, indent) + content[m[0]:], nil
214 }
216 if m := mavenServersSelfClosingRe.FindStringSubmatchIndex(masked); m != nil {
217 indent := mavenIndent(content, m[2], m[3])
218 return content[:m[0]] + mavenServersSection(alias, token, indent) + content[m[1]:], nil
219 }
221 // Only a live <servers> blocks the "add a whole section" path. A file whose
222 // only <servers> is inside a comment has no real one, so adding a section
223 // before </settings> is correct there, and refusing would hand the user
224 // advice about tags they never wrote.
225 if mavenServersOpenRe.MatchString(masked) {
226 return "", errors.New("found a <servers> element this command cannot edit; put its <servers> and </servers> tags on their own lines, or add the <server> block by hand")
227 }
229 if m := mavenSettingsCloseRe.FindStringSubmatchIndex(masked); m != nil {
230 indent := mavenIndent(content, m[2], m[3]) + " "
231 return content[:m[0]] + mavenServersSection(alias, token, indent) + content[m[0]:], nil
232 }
234 // A </settings> that shares a line with something else exists but is not
235 // where mavenSettingsCloseRe looks, so it needs its own message: saying the
236 // file has no </settings> tag when it plainly has one sends the user looking
237 // for the wrong problem.
238 if mavenSettingsCloseAnyRe.MatchString(masked) {
239 return "", errors.New("found a </settings> tag this command cannot use: it does not start its own line; put </settings> on its own line, or add the <servers> section by hand")
240 }
242 return "", errors.New("found neither a <servers> section nor a </settings> tag to add one to")
243}
245// updateMavenServerCredentials rewrites only <username> and <password> inside
246// a single <server> block, so a user's own children — <configuration> HTTP
247// headers, <filePermissions>, comments — survive. Replacing the whole block
248// with the canonical four lines would silently delete them on every routine
249// token refresh.
250// Both children are placed or neither is: on error the caller drops the
251// half-updated block, so a <server> is never left with a rewritten <username>
252// and a stale or missing <password>.
253//
254// masked is block with its comment interiors blanked, per mavenMaskComments.
255func updateMavenServerCredentials(block, masked, token string) (string, error) {
256 block, masked, err := setMavenServerChild(block, masked, mavenUsernameRe, "username", "__token__")
257 if err != nil {
258 return "", err
259 }
260 block, _, err = setMavenServerChild(block, masked, mavenPasswordRe, "password", token)
261 if err != nil {
262 return "", err
263 }
264 return block, nil
265}
267// setMavenServerChild replaces the first <name> element in block with value, or
268// inserts one just before </server> when the block has none. It returns the
269// updated block along with masked kept in step with it, so a second call sees a
270// mask that still matches the block it is handed. It returns an error when it
271// can place neither element, which happens when the block's </server> does not
272// start its own line, as in a one-line <server><id>x</id></server>.
273//
274// That error is the point: mavenServerBlockRe matches such a block happily
275// while mavenServerCloseRe cannot, so returning the block untouched reported a
276// successful login that had written nothing at all.
277//
278// Only the first match is replaced, not all of them, so a nested element using
279// the same tag name is left alone. The residual limitation is that the first
280// match is assumed to be the <server>'s own child: a block that put a
281// <configuration> containing its own <username> ahead of the server's would
282// have the wrong one rewritten. Matching on indentation instead would be
283// stricter but has the worse failure mode: a miss inserts a second <username>,
284// and duplicate elements are invalid where editing a nested tag is merely
285// wrong.
286func setMavenServerChild(block, masked string, re *regexp.Regexp, name, value string) (string, string, error) {
287 element := "<" + name + ">" + mavenXMLText.Replace(value) + "</" + name + ">"
289 // Matching masked, not block, so a commented-out <password> ahead of the live
290 // one cannot absorb the replacement: that would leave the live element
291 // holding the expiring token while the command reported success. The
292 // replacement text is live, so splicing it into masked as well keeps the two
293 // strings the same length and the mask correct for the next call.
294 if loc := re.FindStringIndex(masked); loc != nil {
295 return block[:loc[0]] + element + block[loc[1]:], masked[:loc[0]] + element + masked[loc[1]:], nil
296 }
298 m := mavenServerCloseRe.FindStringSubmatchIndex(masked)
299 if m == nil {
300 return "", "", fmt.Errorf("found a <server> block this command cannot edit: its <%s> is missing and its </server> tag does not start a line; put </server> on its own line, or set <%s> by hand", name, name)
301 }
302 insert := mavenIndent(block, m[2], m[3]) + " " + element + "\n"
304 return block[:m[0]] + insert + block[m[0]:], masked[:m[0]] + insert + masked[m[0]:], nil
305}
307// mavenServersSection renders a whole <servers> section, indented at indent,
308// holding a single <server> block for alias.
309func mavenServersSection(alias, token, indent string) string {
310 return indent + "<servers>\n" +
311 mavenServerBlock(alias, token, indent+" ") +
312 indent + "</servers>\n"
313}
315// mavenServerBlock renders a canonical <server> block, indented at indent.
316func mavenServerBlock(alias, token, indent string) string {
317 return indent + "<server>\n" +
318 indent + " <id>" + alias + "</id>\n" +
319 indent + " <username>__token__</username>\n" +
320 indent + " <password>" + mavenXMLText.Replace(token) + "</password>\n" +
321 indent + "</server>\n"
322}
324// findMavenServerBlock returns the [start, end) byte range of the single
325// <server>...</server> block in masked whose body matches idRe, or nil if no
326// block matches. It scans block-by-block (via mavenServerBlockRe's
327// non-crossing match) rather than matching <id> and </server> in one lazy
328// span, so a target block that isn't the first <server> in the file can
329// never consume a preceding, unrelated block.
330//
331// masked is the whole file with its comment interiors blanked, per
332// mavenMaskComments, so a commented-out example carrying this alias does not get
333// its credentials rewritten in place while the live section goes without. The
334// returned range still addresses the original file.
335func findMavenServerBlock(masked string, idRe *regexp.Regexp) []int {
336 for _, loc := range mavenServerBlockRe.FindAllStringIndex(masked, -1) {
337 if idRe.MatchString(masked[loc[0]:loc[1]]) {
338 return loc
339 }
340 }
341 return nil
342}
Diagnostics8 git calls · 255 ms
CallStatusSizeTime0255 ms
discover200185 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB · hit3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:02001.8 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=1857 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=1857 git.pkt.payload.max=1830 git.sideband.band1.bytes=1830 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1830 git.pack.trailer=fb03183b7909876778f740d196d7516811003517Open pack map
fetchtree:0200242 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=242 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=5da85e254ab77f5f6e7e1419be57d524a9f8208e git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=242 git.pkt.payload.max=215 git.sideband.band1.bytes=215 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=215 git.pack.trailer=bd426fb1ae09d9fdcf755902c6903cd2eea819b2Open pack map
fetchtree:0200494 B · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=494 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=400358373377bb8e4922d8b821520ebdf8130c4d git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=494 git.pkt.payload.max=467 git.sideband.band1.bytes=467 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=467 git.pack.trailer=363b27e4d94209a9331c11b44fe1ce6e5f4e6e81Open pack map
fetch2005.6 KiB238 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=238 git.response.bytes=5765 git.response.cache=MISS git.response.duration_ms=238 git.fetch.wants=f13409756a309a54dc327c4d36f8088c6acb0e26 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=5765 git.pkt.payload.max=5738 git.sideband.band1.bytes=5738 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://gitlab.com/gitlab-org/cli
- Ref
- refs/heads/main
- Commit
- 0dd7574dce9e385c5c30540e6c15657adc6bdce9
- cf-ray
- a5e300e518d2f3c9
- Request
- 9c00e926…
- Protocol
- v2 · sha1
- Agent
- git/2.56.g1891de4-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format