use of com.google.gerrit.server.account.AuthRequest in project gerrit by GerritCodeReview.
the class AbstractQueryChangesTest method visible.
@Test
public void visible() throws Exception {
TestRepository<Repo> repo = createProject("repo");
Change change1 = insert(repo, newChange(repo));
Change change2 = insert(repo, newChangePrivate(repo));
String q = "project:repo";
// Bad request for query with non-existent user
assertThatQueryException(q + " visibleto:notexisting");
// Current user can see all changes
assertQuery(q, change2, change1);
assertQuery(q + " visibleto:self", change2, change1);
// Second user cannot see first user's private change
Account.Id user2 = createAccount("user2");
assertQuery(q + " visibleto:" + user2.get(), change1);
assertQuery(q + " visibleto:user2", change1);
String g1 = createGroup("group1", "Administrators");
gApi.groups().id(g1).addMembers("user2");
// By default when a group is created without any permission granted,
// nothing is visible to it; having members or not has nothing to do with it
assertQuery(q + " visibleto:" + g1);
// change is visible to group ONLY when access is granted
grant(Project.nameKey("repo"), "refs/*", Permission.READ, false, AccountGroup.uuid(gApi.groups().id(g1).get().id));
assertQuery(q + " visibleto:" + g1, change1);
// Both changes are visible to InternalUser
try (ManualRequestContext ctx = oneOffRequestContext.open()) {
assertQuery(q, change2, change1);
}
requestContext.setContext(newRequestContext(user2));
assertQuery("is:visible", change1);
Account.Id user3 = createAccount("user3");
// Explicitly authenticate user2 and user3 so that display name gets set
AuthRequest authRequest = authRequestFactory.createForUser("user2");
authRequest.setDisplayName("Another User");
authRequest.setEmailAddress("user2@example.com");
accountManager.authenticate(authRequest);
authRequest = authRequestFactory.createForUser("user3");
authRequest.setDisplayName("Another User");
authRequest.setEmailAddress("user3@example.com");
accountManager.authenticate(authRequest);
// Switch to user3
requestContext.setContext(newRequestContext(user3));
Change change3 = insert(repo, newChange(repo), user3);
Change change4 = insert(repo, newChangePrivate(repo), user3);
// User3 can see both their changes and the first user's change
assertQuery(q + " visibleto:" + user3.get(), change4, change3, change1);
// User2 cannot see user3's private change
assertQuery(q + " visibleto:" + user2.get(), change3, change1);
// Query as user3 by display name matching user2 and user3; bad request
assertFailingQuery(q + " visibleto:\"Another User\"", "\"Another User\" resolves to multiple accounts");
}
use of com.google.gerrit.server.account.AuthRequest in project gerrit by GerritCodeReview.
the class HttpLoginServlet method doGet.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
final String token = LoginUrlToken.getToken(req);
CacheHeaders.setNotCacheable(rsp);
final String user = authFilter.getRemoteUser(req);
if (user == null || "".equals(user)) {
logger.atSevere().log("Unable to authenticate user by %s request header." + " Check container or server configuration.", authFilter.getLoginHeader());
final Document doc = //
HtmlDomUtil.parseFile(HttpLoginServlet.class, "ConfigurationError.html");
replace(doc, "loginHeader", authFilter.getLoginHeader());
replace(doc, "ServerName", req.getServerName());
replace(doc, "ServerPort", ":" + req.getServerPort());
replace(doc, "ContextPath", req.getContextPath());
final byte[] bin = HtmlDomUtil.toUTF8(doc);
rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
rsp.setContentType("text/html");
rsp.setCharacterEncoding(UTF_8.name());
rsp.setContentLength(bin.length);
try (ServletOutputStream out = rsp.getOutputStream()) {
out.write(bin);
}
return;
}
final AuthRequest areq = authRequestFactory.createForUser(user);
areq.setDisplayName(authFilter.getRemoteDisplayname(req));
areq.setEmailAddress(authFilter.getRemoteEmail(req));
final AuthResult arsp;
try {
arsp = accountManager.authenticate(areq);
} catch (AccountException e) {
logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String remoteExternalId = authFilter.getRemoteExternalIdToken(req);
if (remoteExternalId != null) {
try {
logger.atFine().log("Associating external identity \"%s\" to user \"%s\"", remoteExternalId, user);
updateRemoteExternalId(arsp, remoteExternalId);
} catch (AccountException | ConfigInvalidException e) {
logger.atSevere().withCause(e).log("Unable to associate external identity \"%s\" to user \"%s\"", remoteExternalId, user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
final StringBuilder rdr = new StringBuilder();
if (arsp.isNew() && authConfig.getRegisterPageUrl() != null) {
rdr.append(authConfig.getRegisterPageUrl());
} else {
rdr.append(urlProvider.get(req));
if (arsp.isNew() && !token.startsWith(PageLinks.REGISTER + "/")) {
rdr.append('#' + PageLinks.REGISTER);
}
rdr.append(token);
}
webSession.get().login(arsp, true);
rsp.sendRedirect(rdr.toString());
}
use of com.google.gerrit.server.account.AuthRequest in project gerrit by GerritCodeReview.
the class ProjectOAuthFilter method verify.
private boolean verify(HttpServletRequest req, Response rsp) throws IOException {
AuthInfo authInfo;
// first check if there is a BASIC authentication header
String hdr = req.getHeader(AUTHORIZATION);
if (hdr != null && hdr.startsWith(BASIC)) {
authInfo = extractAuthInfo(hdr, encoding(req));
if (authInfo == null) {
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
} else {
// if there is no BASIC authentication header, check if there is
// a cookie starting with the prefix "git-"
Cookie cookie = findGitCookie(req);
if (cookie != null) {
authInfo = extractAuthInfo(cookie);
if (authInfo == null) {
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
} else {
// an anonymous connection, or there might be a session cookie
return true;
}
}
// if there is authentication information but no secret => 401
if (Strings.isNullOrEmpty(authInfo.tokenOrSecret)) {
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
Optional<AccountState> who = accountCache.getByUsername(authInfo.username).filter(a -> a.account().isActive());
if (!who.isPresent()) {
logger.atWarning().log("%s: account inactive or not provisioned in Gerrit", authenticationFailedMsg(authInfo.username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
Account account = who.get().account();
AuthRequest authRequest = authRequestFactory.createForExternalUser(authInfo.username);
authRequest.setEmailAddress(account.preferredEmail());
authRequest.setDisplayName(account.fullName());
authRequest.setPassword(authInfo.tokenOrSecret);
authRequest.setAuthPlugin(authInfo.pluginName);
authRequest.setAuthProvider(authInfo.exportName);
try {
AuthResult authResult = accountManager.authenticate(authRequest);
WebSession ws = session.get();
ws.setUserAccountId(authResult.getAccountId());
ws.setAccessPathOk(AccessPath.GIT, true);
ws.setAccessPathOk(AccessPath.REST_API, true);
return true;
} catch (AccountException e) {
logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(authInfo.username, req));
rsp.sendError(SC_UNAUTHORIZED);
return false;
}
}
use of com.google.gerrit.server.account.AuthRequest in project gerrit by GerritCodeReview.
the class OAuthSession method authenticateAndRedirect.
private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp, OAuthToken token) throws IOException {
AuthRequest areq = authRequestFactory.create(externalIdKeyFactory.parse(user.getExternalId()));
AuthResult arsp;
try {
String claimedIdentifier = user.getClaimedIdentity();
if (!Strings.isNullOrEmpty(claimedIdentifier)) {
if (!authenticateWithIdentityClaimedDuringHandshake(areq, rsp, claimedIdentifier)) {
return;
}
} else if (linkMode) {
if (!authenticateWithLinkedIdentity(areq, rsp)) {
return;
}
}
areq.setUserName(user.getUserName());
areq.setEmailAddress(user.getEmailAddress());
areq.setDisplayName(user.getDisplayName());
arsp = accountManager.authenticate(areq);
accountId = arsp.getAccountId();
tokenCache.put(accountId, token);
} catch (AccountException e) {
logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
webSession.get().login(arsp, true);
String suffix = redirectToken.substring(OAuthWebFilter.GERRIT_LOGIN.length() + 1);
suffix = CharMatcher.anyOf("/").trimLeadingFrom(Url.decode(suffix));
StringBuilder rdr = new StringBuilder(urlProvider.get(req));
rdr.append(suffix);
rsp.sendRedirect(rdr.toString());
}
use of com.google.gerrit.server.account.AuthRequest in project gerrit by GerritCodeReview.
the class AccountIdHandler method createAccountByLdap.
private Account.Id createAccountByLdap(String user) throws CmdLineException, IOException {
if (!ExternalId.isValidUsername(user)) {
throw new CmdLineException(owner, localizable("user \"%s\" not found"), user);
}
try {
AuthRequest req = authRequestFactory.createForUser(user);
req.setSkipAuthentication(true);
return accountManager.authenticate(req).getAccountId();
} catch (AccountException e) {
String msg = "user \"%s\" not found";
logger.atSevere().withCause(e).log(msg, user);
throw new CmdLineException(owner, localizable(msg), user);
}
}
Aggregations