Repository navigation
[maven-3.10.x] Support token authentication (bearer and custom token headers) for settings servers - #14173
[maven-3.10.x] Support token authentication (bearer and custom token headers) for settings servers#14173cstamas wants to merge 7 commits into
Conversation
Maven Resolver 2.0.27 adds bearer token authentication: HTTP transports
(except Wagon) send it preemptively as an Authorization: Bearer header,
and it takes precedence over username and password.
A <server> in settings.xml can now declare it:
<server>
<id>internal</id>
<bearerToken>...</bearerToken>
</server>
- settings model 1.4.0 gets the new bearerToken field; the sample
settings.xml now uses the 1.4.0 namespace
- the token is decrypted like the password and passphrase, and a token
left encrypted is warned about
- the token is handed to the resolver session authentication
- the legacy ArtifactRepository Authentication carries the token, so
older plugins that convert repositories back and forth keep it
- the settings validator warns when a token is set together with a
username or password, as those are ignored
The Wagon transport is left as is and ignores the token.
gnodet-bot
left a comment
There was a problem hiding this comment.
Overall this is a solid, well-structured enhancement. Bearer token support is correctly threaded through all five layers (settings model → decrypter → session factory → legacy compat → artifact bridge), and the integration test covers the full round-trip including the reverse path through RepositoryUtils.toRepo(). Two minor observations below.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
| <cipherVersion>2.0</cipherVersion> | ||
| <jxpathVersion>1.4.0</jxpathVersion> | ||
| <resolverVersion>2.0.26</resolverVersion> | ||
| <resolverVersion>2.0.27-SNAPSHOT</resolverVersion> |
There was a problem hiding this comment.
🔖 Tracking note: resolverVersion is set to 2.0.27-SNAPSHOT, pending merge/release of apache/maven-resolver#2372 (currently open). This must be updated to the final 2.0.27 release before this PR can be merged.
There was a problem hiding this comment.
Acknowledged. This tracks apache/maven-resolver#2372, and resolverVersion will be switched to 2.0.27 once it is released, before merge. Note that #2372 now also carries the token-header rework this PR builds on since 912af7a.
Some repositories expect the token in a header other than
Authorization: Bearer, for example GitLab with Private-Token, Job-Token
or Deploy-Token. Maven Resolver 2.0.27 models this as a token header
(header name plus full header value) carried in the authentication, so
it stays bound to the repository origin and is never sent elsewhere,
unlike a <configuration><httpHeaders> entry.
The server <bearerToken> (settings model 1.4.0, not released yet) is
replaced by <token> and an optional <tokenHeader>:
<server>
<id>gitlab</id>
<token>...</token>
<tokenHeader>Private-Token</tokenHeader>
</server>
Without <tokenHeader> the token is sent as Authorization: Bearer and
username and password are ignored; any other header is sent as is,
together with them.
- the legacy ArtifactRepository Authentication carries token and
tokenHeader as the resolver hands them back, and is rebuilt with
addTokenHeader so a bearer token does not turn into "Bearer Bearer"
- the settings validator rejects header names the HTTP transports would
refuse (not an RFC 9110 field name, or a transport-controlled header),
warns about a tokenHeader without a token, and warns about username or
password only when the token is sent as Authorization
gnodet-bot
left a comment
There was a problem hiding this comment.
Following up on my earlier review — the previous suggestion about testing the all-three-set case (token + username + password) is fully addressed by the new testValidateServerAuthorizationTokenWithUsernameIsWarnedAbout test, and the resolverVersion SNAPSHOT tracking note (the other open thread) still stands pending the resolver release.
The generalization from bearerToken to token/tokenHeader is clean and correct end-to-end:
- The
Bearer Bearerdouble-prefix guard inRepositoryUtils.toAuthentication()is handled correctly: when reading back from the session, the header isAuthorizationand the value is alreadyBearer tok3n, soaddTokenHeader("Authorization", "Bearer tok3n")is used directly — no double-prefix. Verified by the newbearerTokenReachesSessionAndLegacyRepositoryPathassertions. - The
validateToken()method correctly validates RFC 9110 field names, blocks transport-controlled headers, skips placeholder values, and applies the Authorization-specific warning only when the token replaces username/password on the wire. - All five layers (settings model → decrypter → session factory → legacy compat → artifact bridge) are consistently updated, including the
tokenHeadernot being decrypted (correct — it's a header name, not a secret).
LGTM.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
gnodet-bot
left a comment
There was a problem hiding this comment.
Re-review status (SHA 912af7af vs prior 5dd4321):
| # | Prior Finding | Status |
|---|---|---|
| 1 | resolverVersion set to 2.0.27-SNAPSHOT — must be a final release before merge |
|
| 2 | Add all-three-set test case (token + username + password) |
✅ Addressed — validateToken("token", "authorization", "user", "pwd") on line 337 covers this. Thread outdated due to file rewrite. |
The new commit is a well-executed generalization: bearerToken → token + tokenHeader, correctly threaded through all five layers (settings MDO → decrypter → session factory → legacy compat → artifact bridge). The addBearerToken / addTokenHeader dispatch in both DefaultRepositorySystemSessionFactory and RepositoryUtils.toAuthentication() correctly prevents the Bearer Bearer ... double-prefix on the round-trip path, as verified by the test comment on line 219. The validateToken() method is thorough: RFC 9110 header-name validation, forbidden transport-controlled headers, ${-placeholder pass-through, and the nuanced distinction that only Authorization-bound tokens conflict with username/password while custom headers (e.g. Private-Token) coexist with them. No new issues found in the incremental diff.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
…r test Review feedback: the bearer token case with both username and password set was only implied by the other assertions.
| AuthenticationBuilder authBuilder = new AuthenticationBuilder(); | ||
| authBuilder.addUsername(server.getUsername()).addPassword(server.getPassword()); | ||
| authBuilder.addPrivateKey(server.getPrivateKey(), server.getPassphrase()); | ||
| if (server.getTokenHeader() == null || server.getTokenHeader().isEmpty()) { |
There was a problem hiding this comment.
empty is a valid use case IMHO
| | | ||
| <server> | ||
| <id>tokenServer</id> | ||
| <token>token</token> |
There was a problem hiding this comment.
why making it specific, we already have
<property>
<name>Authorization</name>
<value>Bearer xxxx</value>
</property>in httpHeaders which avoids to have two inconsistent cases using token (bearer and a do what you want as schema case)
so literally we are just aliasing what is already there in terms of configuration so I would remove that
|
This isn't an alias nor duplication.
Bearer tokens are credentials, and credentials belong in In fact, what you ask for is to "legalize" a hack users did (as circumvention) to treat http headers as secret. But some others use it for "marker" or anything else. With your saying, we should treat them as "secret" and "marker" use case would be gone (so it would be this or that). I personally would never promote hacks as "valid solution", they were a "known circumvention", and we should provide real support for required things, like this PR does. |
The model moved to 1.4.0 for token and tokenHeader, but the site still linked the 1.2.0 XSD.
|
I think the support of a new auth method is a new feature instead of a bugfix? |
|
@cstamas this is pure duplication for me, let me explain with your points:
Well it is supported in maven 4 and not the hardest part to port to maven 3
Same applies to headers (and the proxy behavior too) so worth making happening for httpheaders as well
About conflicts it is the same for the new Overall the point is with as much efforts you do better since you enhance an existing and used features instead of creating a new one. Side note: I think a neat compromise for the secret can be a config property - 90% of resolver configuration is not wired in maven except with properties anyway - which does list header names to hide and we set the dozen of well known values as default, will make it working for everyone for free when upgrading which is way better than making people having to maintain multiple settings (local and CI for ex) for some time and/or not having the feature at all. So with a bit more thought I think this is the opposite of where we want to go. |
|
@rmannibucau's point about enhancing The That said, I think you're both right about one thing: if we were to retrofit My view: merge this PR — it's the semantically correct place for token credentials, it's well-implemented, and it unblocks users who want first-class support. Then open a follow-up to give The alternative (block this PR and retrofit |
|
@gnodet but don't we duplicate a feature then? since httpheaders superseeds almost everything there we shouldnt duplicate ways to do and focus on a solid solution only IMHO. maybe worth a thread on the list 🤔 |
|
Those are exactly the properties that make On the list thread: I'm fine with that if there's a genuine design question open. But the question here seems settled: credentials belong in |
it does in maven 4 and we can make it happening easily in maven 3 so I don't see it as a good point to create a new feature and force everybody to migrate
Literally as much as the new token, the fix you mention is not about token or not - this part is pure frontend, so this must be fixed anyway in all cases so to summarize: we have several fixes this PR does only for a new configuration we must do for httpHeaders whatever we implement, so better to have a single configuration option with a general benefit for everybody rather than a new breaking implementation IMHO So I still don't see a valid point to go that new path which doesnt enable anything new assuming we do the same code for what already exists since years - it is debt fix not a new feature to be concrete |
|
Good points, and I think we're closer to agreement than it appears. On decryption — you're right, that's doable in Maven 3 as well, happy to concede that. On origin-scoping, though, I'd push back a little. That said, I do agree that we should also improve Would you be open to that framing? Happy to help with the |
Agree on that but we must do it anyway and once done the token proposal is way less relevant than it is right now.
Hmm, I'm not sure I do agree there. Assume we did it for httpheaders - since we must do it, what does this PR brings? nothing valuable since you can already do everything with a natural semantic and configuration with httpheaders right? So why adding it to make it superseeded just after? |
|
Personally:
All in all, I refuse to treat httpHeaders as secret, as it would be a breaking change. They are not secret and never were secret. Token is the right place for secrets, it goes into auth context just like password and everything else is. Also, controls for HTTP headers were already done: And (carefully) read Javadoc of it. FYI, I find this nitpicking very counter-productive, real waste of everyone's cycles here. |
|
@cstamas some statements are wrong IMHO
you do since you make token more correct from an impl perspective and the only option since you dont fix httpheaders impl
agree it breaks as most fix of this kind so like everytime we'll get the fix and a toggle to disable it but we cant make it better doing the proper fix
true or wrong I think we shouldn't care must, 1. they are used like that since years and 2. they are semantically and from a schema perspective way more correct than token proposal which is limiting, specific and potentially semantically wrong.
this one is 100% wrong, just have a look to gitlab doc for ex. You didn't want it to be secrets -> likely, it always hadbeen secrets -> likely. So personally I'll be on the end user side and not defend a trivial implementation choice over end user experience - and once again it is not hard to do.
Not sure the point, this is not cause we did something wrong that we can't fix it (same origin point).
it is not nitpicking, you loose time and I prefer it versus making hundreds or thousands of projects loosing time for a forced migration we are not able to justify technically. |
Settings servers now carry the bearer token in <token> (sent as "Authorization: Bearer <token>") and any number of other token headers in <tokenHeaders><tokenHeader><name/><value/></tokenHeader></tokenHeaders>, for example Private-Token for GitLab, or CF-Access-Client-Id and CF-Access-Client-Secret for Cloudflare Access. Token header values are decrypted like passwords. Follows the Resolver token API (apache/maven-resolver#2372): tokens are read back from the authentication context via http.token.headers and http.token.value.<Name>, and the legacy Authentication carries all token headers so nothing is lost on round trip. The settings validator also rejects Sec-* header names, which HttpURLConnection silently drops.
gnodet-bot
left a comment
There was a problem hiding this comment.
Following up on my earlier review — the multi-header redesign introduced in the latest commit is well-engineered.
Status of previous findings:
- 🔖
resolverVersionset to2.0.27-SNAPSHOT— still open (see inline comment below)
New commit assessment (d6be4588 — "Support multiple token headers per server, align with Resolver token API"):
- Validation is thorough: RFC 9110 field-name regex blocks commas (safe for the comma-separated
HTTP_TOKEN_HEADERSprotocol),Sec-*check is case-insensitive (regionMatches(true, ...)), forbidden headers are lowercased before lookup — all correct. - Decryption covers both
<token>and each<tokenHeader>/<value>, with clone isolation verified by the newDefaultSettingsDecrypterTest. - Round-trip tests cover single bearer, single custom header (GitLab), and multiple headers (Cloudflare) through settings → session → ArtifactRepository → RemoteRepository. The
Bearer Bearerdouble-prefix guard is preserved. - Settings model versioning is correct: new elements gated at
1.4.0+, Modello bumped to 1.4.0, shippedsettings.xmlnamespace updated.
No new code issues. The only remaining blocker is the SNAPSHOT dependency.
This review was generated by an AI agent, Hermès on behalf of @gnodet.
| <jxpathVersion>1.4.0</jxpathVersion> | ||
| <resolverVersion>2.0.26</resolverVersion> | ||
| <resolverVersion>2.0.27-SNAPSHOT</resolverVersion> | ||
| <slf4jVersion>2.0.20</slf4jVersion> |
There was a problem hiding this comment.
🔖 Tracking note (re-raised): resolverVersion is still set to 2.0.27-SNAPSHOT. Resolver PR #2372 is still open, and the maven-resolver-2.0.27 release on repository.apache.org/Maven Central is a draft — not yet available. The new APIs used by this PR (AuthenticationBuilder.addBearerToken(), addTokenHeader(), AuthenticationContext.HTTP_TOKEN_HEADERS, HTTP_TOKEN_VALUE_PREFIX) do not exist in the released 2.0.26, so this PR will not compile against any published Resolver artifact. Must wait for 2.0.27 to be released before merging.
The settings validator duplicated the Resolver HTTP transport rules for token header names and values (RFC 9110 field name, transport-controlled headers, Sec-*), and had to be synced on every Resolver change; the Resolver now also rejects Proxy-* names. maven-settings-builder has no Resolver dependency and keeps only the structural checks: missing name, duplicate header (any letter case, including the token as Authorization), missing value, and an Authorization token next to username or password. DefaultRepositorySystemSessionFactory now checks each token and token header with HttpTransporterUtils.isValidTokenHeaderName/isValidTokenValue when it builds the repository authentication, and fails with an error naming the server and the header, never the token. Empty values are not sent, as the validator warns.
gnodet-bot
left a comment
There was a problem hiding this comment.
Following up on my earlier review — the validation refactoring in the latest commit (3bb9172c) is clean and well-tested.
New commit assessment ("Validate token headers with the Resolver rules instead of a copy"):
- Removing the duplicate validation from
DefaultSettingsValidatorand delegating semantic checks (RFC 9110 field names,Proxy-*,Sec-*, forbidden headers, value encoding) toDefaultRepositorySystemSessionFactory.addTokens()viaHttpTransporterUtils.isValidTokenHeaderName/isValidTokenValueis the right design. DRY, and sync-free: future Resolver changes (e.g., addingProxy-*prefix rejection) are automatically picked up. HttpTransporterUtils.isValidTokenHeaderName(null)returnsfalse(the resolver method starts withname != null && ...), andisValidTokenValue(null)similarly returnsfalse. Null safety is maintained inaddTokens().- The
DefaultSettingsValidatorstill catches null/empty names early withStringUtils.isEmpty(name)→ ERROR, so theaddTokens()path is a secondary defence. Both layers are consistent. - The duplicate-name condition refactoring (
else if (!name.contains("${") && !names.add(...))) is semantically correct — a valid unique name causesnames.addto returntrue, making the outer conditionfalse→ no violation; a duplicate name causesfalse→ conditiontrue→ violation. - The new tests in
DefaultRepositorySystemSessionFactoryTestcover empty-value suppression, Proxy-/Sec-/Host/format rejection, and value encoding for both header values and bearer tokens, including the secret-must-not-appear check inassertInvalidTokens. DefaultSettingsValidatorTestis correctly trimmed: the test renamed totestValidateServerTokenHeaderNameIsRequirednow only asserts structural checks (empty/null name), not semantic ones.testValidateServerTokenValueis fully removed as the value validation has moved.
Still open (re-raised from prior review): resolverVersion is 2.0.27-SNAPSHOT (see inline comment below).
This review was generated by an AI agent, Hermès on behalf of @gnodet.
| <cipherVersion>2.0</cipherVersion> | ||
| <jxpathVersion>1.4.0</jxpathVersion> | ||
| <resolverVersion>2.0.26</resolverVersion> | ||
| <resolverVersion>2.0.27-SNAPSHOT</resolverVersion> |
There was a problem hiding this comment.
🔖 Tracking note (re-raised): resolverVersion is still 2.0.27-SNAPSHOT. Resolver PR apache/maven-resolver#2372 ("Add HTTP token header authentication (bearer, custom and multiple headers) to HTTP transports") is still open — 2.0.27 has not been released to Maven Central. This PR cannot be merged until the resolver release is final and this property is updated to the released version.
Follows apache/maven#14173 and #14179: <token> is a bearer token only, and any number of other token headers go in <tokenHeaders><tokenHeader><name/><value/></tokenHeader></tokenHeaders> (GitLab Private-Token, Cloudflare Access client id and secret, ...). Token header values can be encrypted like a password, and the documented errors now include Proxy-* and Sec-* names and duplicate headers.
gnodet
left a comment
There was a problem hiding this comment.
Introducing a new settings schema element in a micro release (3.10.x) seems risky — settings written with the new <token>/<tokenHeader> elements would be silently ignored or fail to parse on 3.9.x and earlier 3.10.x, breaking forward-compatibility expectations users have for a micro release.
#14203 is an alternative that achieves the same goals (encrypted, origin-scoped token authentication) without a schema change, by wiring the existing <configuration><httpHeaders> path into the resolver's AuthenticationBuilder. The tradeoff is a slightly more verbose user-side config, but no new XML elements in the settings schema.
Worth discussing which approach is more appropriate for a micro release.
Maven Resolver 2.0.27 adds token header authentication (apache/maven-resolver#2372): a repository
Authenticationcan carry any number of HTTP token headers, each a header name plus the full header value. HTTP transports (except Wagon) send them preemptively, and only to the repository origin (scheme, host, port). This PR exposes them insettings.xml:This replaces the GitLab-documented
<configuration><httpHeaders>route. Its values are not decrypted, and they are not bound to the repository origin: headers are keyed by repository id only, so a POM repository with the same id on another host would receive the token.Changes:
Settings model 1.4.0 (1.3.0 already shipped in 3.10.0) adds to
<server>:token: a bearer token, sent asAuthorization: Bearer <token>;tokenHeaders: a list oftokenHeader(name,value), each sent as is.An
Authorizationtoken takes precedence over username and password; any other header is sent along with them. The sampleconf/settings.xmlnow uses the 1.4.0 namespace (it was still on 1.2.0) and shows both forms.DefaultSettingsDecrypterdecryptstokenand every token header value like the password. The session factory warns when one is left encrypted.DefaultRepositorySystemSessionFactorymapstokentoAuthenticationBuilder.addBearerToken(token)and each token header toaddTokenHeader(name, value). It first checks each one with the Resolver's own rules (HttpTransporterUtils.isValidTokenHeaderName/isValidTokenValue), so a header the transports would reject or silently drop fails the build up front. Those rules cover RFC 9110 field names, transport-controlled headers such asHost, and theProxy-*andSec-*names that the JDK clients drop. The error names the server and the header, never the token. Empty values are not sent.Older plugin path: the
maven-artifactAuthenticationgetstokenHeaders(header name to full header value). They are read back from the resolver viaHTTP_TOKEN_HEADERS/HTTP_TOKEN_VALUE_PREFIX + name.MavenRepositorySystem,LegacyRepositorySystemandRepositoryUtils.toAuthenticationcarry all of them, so plugins convertingArtifactRepository↔RemoteRepositorykeep every token. The rebuild usesaddTokenHeader, so a bearer token does not becomeBearer Bearer ….DefaultSettingsValidatorchecks only the structure of the token settings. It does not copy the Resolver's header rules, so they are not synced by hand on every Resolver change, andmaven-settings-builderstays Resolver-free.<token>together with anAuthorizationtoken header.Authorization, since they are then ignored. A custom header such asPrivate-Tokengoes along with Basic auth.The Wagon transport is left as is and ignores the tokens.
Changed since the first review: the single
<tokenHeader>naming the header for<token>is replaced by the<tokenHeaders>list.<token>is now bearer-only. This follows the resolver change to multiple token headers per repository. The header name and value rules are no longer copied into the settings validator; maven-core applies the Resolver's own checks.Depends on: apache/maven-resolver#2372, which also includes #2373 (no Basic auth without a username, needed for a token-only server).
resolverVersionis set to2.0.27-SNAPSHOT, so CI cannot build this until the resolver change is deployed. Switch to 2.0.27 once it is released.Release note:
settings-1.4.0.xsdmust be published to maven.apache.org/xsd.Site documentation: apache/maven-site#1853 documents the token settings in the settings reference and the deployment security, encryption and HTTP settings guides. It does not publish the XSD.
Tests: new cases in
DefaultSettingsDecrypterTest,DefaultSettingsValidatorTest,DefaultRepositorySystemSessionFactoryTestandLegacyRepositorySystemTest. The session factory test also checks that the Resolver rules are applied:Proxy-*,Sec-*andHostnames and invalid values are rejected without the token in the message,X-Proxy-Token,ProxyishandX-Sec-Tokenpass, and empty values are skipped. The session factory test round-trips three cases from settings to the session, onto anArtifactRepository, and back throughtoRepo:Private-Tokenheader;mvn verifypasses locally on the touched modules and their dependencies (1129 tests) against a locally installed resolver snapshot.