implemented user impersonization

This commit is contained in:
2025-07-02 23:20:21 +02:00
parent ea6ca9e45d
commit 5100ac244a
12 changed files with 198 additions and 63 deletions

View File

@@ -16,8 +16,10 @@ import java.net.InetSocketAddress;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
public class Application { public class Application {
private static final System.Logger LOG = System.getLogger("Umbrella"); private static final System.Logger LOG = System.getLogger("Umbrella");
private static final String USER_DB = "/home/srichter/workspace/umbrella/data/umbrella.db"; private static final String USER_DB = "/home/srichter/workspace/umbrella/data/umbrella.db";
private static final String LOGIN_SERVICE_DB = "/home/srichter/workspace/umbrella/data/umbrella.db";
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
ColorLogger.setRootLogLevel(DEBUG); ColorLogger.setRootLogLevel(DEBUG);
LOG.log(INFO, "Starting Umbrella:"); LOG.log(INFO, "Starting Umbrella:");
@@ -25,10 +27,11 @@ public class Application {
var threads = 16; var threads = 16;
var connectionProvider = new ConnectionProvider(); var connectionProvider = new ConnectionProvider();
var userDb = new SqliteDB(connectionProvider.get(USER_DB)); var userDb = new SqliteDB(connectionProvider.get(USER_DB));
var loginServicedb = new SqliteDB(connectionProvider.get(LOGIN_SERVICE_DB));
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.setExecutor(Executors.newFixedThreadPool(threads)); server.setExecutor(Executors.newFixedThreadPool(threads));
new WebHandler().bindPath("/").on(server); new WebHandler().bindPath("/").on(server);
new UserModule(userDb).bindPath("/api/user").on(server); new UserModule(userDb,loginServicedb).bindPath("/api/user").on(server);
new Translations().bindPath("/api/translations").on(server); new Translations().bindPath("/api/translations").on(server);
LOG.log(INFO,"Started web server at {0}",port); LOG.log(INFO,"Started web server at {0}",port);
server.start(); server.start();

View File

@@ -40,7 +40,7 @@ subprojects {
dependencies { dependencies {
testImplementation(platform("org.junit:junit-bom:5.10.0")) testImplementation(platform("org.junit:junit-bom:5.10.0"))
testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.junit.jupiter:junit-jupiter")
implementation("de.srsoftware:tools.http:6.0.3") implementation("de.srsoftware:tools.http:6.0.4")
implementation("de.srsoftware:tools.logging:1.3.2") implementation("de.srsoftware:tools.logging:1.3.2")
} }

View File

@@ -13,12 +13,24 @@
const resp = await fetch(url,{credentials:'include'}); const resp = await fetch(url,{credentials:'include'});
if (resp.ok){ if (resp.ok){
const json = await resp.json(); const json = await resp.json();
for (let user of json) users.push(user); for (let u of json) users.push(u);
} }
}); });
async function impersonate(userId){
const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/${userId}/impersonate`;
const resp = await fetch(url,{
method: 'POST',
credentials: 'include'
});
if (resp.ok){
const json = await resp.json();
for (let key of Object.keys(json)) user[key] = json[key];
}
}
</script> </script>
<fieldset> <fieldset tabindex="0">
<legend>{t('user.list')}</legend> <legend>{t('user.list')}</legend>
<table> <table>
<thead> <thead>
@@ -38,6 +50,9 @@
<td>{u.email}</td> <td>{u.email}</td>
<td>{u.language}</td> <td>{u.language}</td>
<td> <td>
{#if user.permissions.includes('IMPERSONATE')}
<button onclick={() => impersonate(u.id)}>{t('user.impersonate')}</button>
{/if}
{#if user.permissions.includes('UPDATE_USERS')} {#if user.permissions.includes('UPDATE_USERS')}
<button onclick={() => router.navigate(`/user/${u.id}/edit`)}>{t('user.edit')}</button> <button onclick={() => router.navigate(`/user/${u.id}/edit`)}>{t('user.edit')}</button>
{/if} {/if}

View File

@@ -0,0 +1,45 @@
<script>
import { onMount } from 'svelte';
import { t } from '../../translations.svelte.js';
import { useTinyRouter } from 'svelte-tiny-router';
import { user } from '../../user.svelte.js';
const router = useTinyRouter();
let services = $state([]);
onMount(async () => {
const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/service/buttons`;
const resp = await fetch(url,{credentials:'include'});
if (resp.ok){
const json = await resp.json();
for (let service of json) services.push(service);
}
});
</script>
<fieldset tabindex="0">
<legend>{t('user.login_services')} <button>{t('user.add_login_service')}</button></legend>
<table>
<thead>
<tr>
<th>{t('user.service')}</th>
<th>{t('user.actions')}</th>
</tr>
</thead>
<tbody>
{#each services as service,i}
<tr>
<td>{service}</td>
<td>
<button>{t('user.connect_service')}</button>
{#if user.permissions.includes('MANAGE_LOGIN_SERVICES')}
<button>{t('user.edit')}</button>
<button>{t('user.delete')}</button>
{/if}
</td>
</tr>
{/each}
</tbody>
</table>
</fieldset>

View File

@@ -5,6 +5,7 @@
import EditPassword from './EditPassword.svelte'; import EditPassword from './EditPassword.svelte';
import UserList from './List.svelte'; import UserList from './List.svelte';
import LoginServiceList from './LoginServices.svelte';
const router = useTinyRouter(); const router = useTinyRouter();
@@ -90,4 +91,5 @@
{#if user.permissions.includes('LIST_USERS')} {#if user.permissions.includes('LIST_USERS')}
<UserList /> <UserList />
{/if} {/if}
<LoginServiceList />

View File

@@ -20,8 +20,11 @@
"user" : { "user" : {
"actions": "Aktionen", "actions": "Aktionen",
"abort": "abbrechen", "abort": "abbrechen",
"add_login_service": "Login-Service anlegen",
"connect_service": "mit Service verbinden",
"CREATE_USERS": "NUTZER ANLEGEN", "CREATE_USERS": "NUTZER ANLEGEN",
"data_sent": "Daten übermittelt", "data_sent": "Daten übermittelt",
"delete": "löschen",
"DELETE_USERS": "NUTZER LÖSCHEN", "DELETE_USERS": "NUTZER LÖSCHEN",
"edit": "Bearbeiten", "edit": "Bearbeiten",
"editing": "Nutzer {0} bearbeiten", "editing": "Nutzer {0} bearbeiten",
@@ -29,6 +32,7 @@
"email": "E-Mail", "email": "E-Mail",
"failed": "fehlgeschlagen", "failed": "fehlgeschlagen",
"id": "Id", "id": "Id",
"impersonate": "zu Nutzer wechseln",
"IMPERSONATE": "NUTZER WECHSELN", "IMPERSONATE": "NUTZER WECHSELN",
"language": "Sprache", "language": "Sprache",
"list": "Benutzer-Liste", "list": "Benutzer-Liste",
@@ -46,6 +50,7 @@
"repeat_new_password": "Wiederholung", "repeat_new_password": "Wiederholung",
"saved": "gespeichert", "saved": "gespeichert",
"save_user": "Nutzer speichern", "save_user": "Nutzer speichern",
"service": "Service",
"theme": "Design", "theme": "Design",
"your_profile": "dein Profil", "your_profile": "dein Profil",
"update": "aktualisieren", "update": "aktualisieren",

View File

@@ -9,10 +9,9 @@ public class Paths {
public static final String IMPERSONATE = "impersonate"; public static final String IMPERSONATE = "impersonate";
public static final String INSTALL = "install"; public static final String INSTALL = "install";
public static final String JAVASCRIPT = "js"; public static final String JAVASCRIPT = "js";
public static final String LOGIN = "login";
public static final String MENU = "menu"; public static final String MENU = "menu";
public static final String NOTIFY = "notify"; public static final String NOTIFY = "notify";
public static final String OIDC_BUTTONS = "oidc_buttons"; public static final String BUTTONS = "buttons";
public static final String OIDC_LOGIN = "oidc_login"; public static final String OIDC_LOGIN = "oidc_login";
public static final String OPENID_LOGIN = "openid_login"; public static final String OPENID_LOGIN = "openid_login";
public static final String SESSION = "session"; public static final String SESSION = "session";

View File

@@ -6,11 +6,12 @@ import static de.srsoftware.umbrella.core.Constants.*;
import static de.srsoftware.umbrella.core.Paths.LIST; import static de.srsoftware.umbrella.core.Paths.LIST;
import static de.srsoftware.umbrella.core.Paths.LOGOUT; import static de.srsoftware.umbrella.core.Paths.LOGOUT;
import static de.srsoftware.umbrella.core.ResponseCode.*; import static de.srsoftware.umbrella.core.ResponseCode.*;
import static de.srsoftware.umbrella.core.ResponseCode.HTTP_SERVER_ERROR;
import static de.srsoftware.umbrella.user.Constants.*; import static de.srsoftware.umbrella.user.Constants.*;
import static de.srsoftware.umbrella.user.Paths.LOGIN; import static de.srsoftware.umbrella.user.Paths.*;
import static de.srsoftware.umbrella.user.Paths.WHOAMI; import static de.srsoftware.umbrella.user.Paths.IMPERSONATE;
import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION.LIST_USERS; import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION;
import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION.UPDATE_USERS; import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION.*;
import static java.lang.System.Logger.Level.WARNING; import static java.lang.System.Logger.Level.WARNING;
import static java.net.HttpURLConnection.*; import static java.net.HttpURLConnection.*;
import static java.time.temporal.ChronoUnit.DAYS; import static java.time.temporal.ChronoUnit.DAYS;
@@ -19,8 +20,8 @@ import com.sun.net.httpserver.HttpExchange;
import de.srsoftware.tools.Path; import de.srsoftware.tools.Path;
import de.srsoftware.tools.PathHandler; import de.srsoftware.tools.PathHandler;
import de.srsoftware.tools.SessionToken; import de.srsoftware.tools.SessionToken;
import de.srsoftware.umbrella.core.ResponseCode;
import de.srsoftware.umbrella.core.UmbrellaException; import de.srsoftware.umbrella.core.UmbrellaException;
import de.srsoftware.umbrella.user.api.LoginServiceDb;
import de.srsoftware.umbrella.user.api.UserDb; import de.srsoftware.umbrella.user.api.UserDb;
import de.srsoftware.umbrella.user.model.*; import de.srsoftware.umbrella.user.model.*;
import java.io.IOException; import java.io.IOException;
@@ -35,6 +36,7 @@ public class UserModule extends PathHandler {
private static final BadHasher BAD_HASHER; private static final BadHasher BAD_HASHER;
private static final System.Logger LOG = System.getLogger("User"); private static final System.Logger LOG = System.getLogger("User");
private final UserDb users; private final UserDb users;
private final LoginServiceDb logins;
static { static {
try { try {
@@ -44,8 +46,9 @@ public class UserModule extends PathHandler {
} }
} }
public UserModule(UserDb userDb){ public UserModule(UserDb userDb, LoginServiceDb loginDb){
users = userDb; users = userDb;
logins = loginDb;
} }
private HttpExchange addCors(HttpExchange ex){ private HttpExchange addCors(HttpExchange ex){
@@ -77,6 +80,7 @@ public class UserModule extends PathHandler {
switch (head) { switch (head) {
case LIST: return getUserList(ex, user); case LIST: return getUserList(ex, user);
case LOGOUT: return logout(ex, sessionToken); case LOGOUT: return logout(ex, sessionToken);
case SERVICE: return getService(ex,user,path);
case WHOAMI: return getUser(ex, user); case WHOAMI: return getUser(ex, user);
}; };
@@ -149,20 +153,102 @@ public class UserModule extends PathHandler {
} }
} }
private boolean getUserList(HttpExchange ex, UmbrellaUser user) throws IOException { @Override
if (user instanceof DbUser dbUser && dbUser.permissions().contains(LIST_USERS)){ public boolean doPost(Path path, HttpExchange ex) throws IOException {
try { addCors(ex);
var list = users.list(0, null).stream().map(UmbrellaUser::toMap).toList(); var head = path.pop();
return sendContent(ex,list); Long targetId = null;
} catch (UmbrellaException e) { try {
return sendContent(ex,e.statusCode(),e.getMessage()); targetId = Long.parseLong(head);
} head = path.pop();
} catch (NumberFormatException ignored) {}
switch (head){
case IMPERSONATE: return impersonate(ex,targetId);
case LOGIN: return postLogin(ex);
} }
return sendContent(ex,HTTP_FORBIDDEN,"You are not allowed to list users!"); return super.doPost(path, ex);
}
private boolean getService(HttpExchange ex, UmbrellaUser user, Path path) throws IOException {
var head = path.pop();
return switch (head){
case BUTTONS -> getOidcButtons(ex);
case LIST -> getServiceList(ex,user);
case null, default -> super.doGet(path,ex);
};
}
private boolean getOidcButtons(HttpExchange ex) throws IOException {
try {
var services = logins.listLoginServices().stream().map(LoginService::name);
return sendContent(ex,services);
} catch (UmbrellaException e) {
return sendContent(ex,e.statusCode(),e.getMessage());
} catch (IOException e) {
return sendContent(ex,HTTP_SERVER_ERROR,e.getMessage());
}
}
private boolean getServiceList(HttpExchange ex, UmbrellaUser user) throws IOException {
if (!(user instanceof DbUser dbUser && dbUser.permissions().contains(MANAGE_LOGIN_SERVICES))) return sendEmptyResponse(HTTP_FORBIDDEN,ex);
try {
var services = logins.listLoginServices().stream().map(LoginService::toMap);
return sendContent(ex,services);
} catch (UmbrellaException e) {
return sendContent(ex,e.statusCode(),e.getMessage());
} catch (IOException e) {
return sendContent(ex,HTTP_SERVER_ERROR,e.getMessage());
}
}
private boolean getUser(HttpExchange ex, UmbrellaUser user) throws IOException {
if (user != null) return sendContent(ex,user);
return sendEmptyResponse(HTTP_UNAUTHORIZED,ex);
}
private boolean getUserList(HttpExchange ex, UmbrellaUser user) throws IOException {
if (!(user instanceof DbUser dbUser && dbUser.permissions().contains(LIST_USERS))) return sendContent(ex,HTTP_FORBIDDEN,"You are not allowed to list users!");
try {
var list = users.list(0, null).stream().map(UmbrellaUser::toMap).toList();
return sendContent(ex,list);
} catch (UmbrellaException e) {
return sendContent(ex,e.statusCode(),e.getMessage());
}
}
private boolean impersonate(HttpExchange ex, Long targetId) throws IOException {
var sessionToken = SessionToken.from(ex).map(Token::of);
if (sessionToken.isEmpty()) return sendEmptyResponse(HTTP_UNAUTHORIZED,ex);
try {
var requestingUser = users.load(users.load(sessionToken.get()));
if (!(requestingUser instanceof DbUser dbUser && dbUser.permissions().contains(PERMISSION.IMPERSONATE))) return sendEmptyResponse(HTTP_FORBIDDEN,ex);
if (targetId == null) return sendContent(ex,HTTP_UNPROCESSABLE,"user id missing");
var targetUser = users.load(targetId);
users.getSession(targetUser)
.cookie()
.addTo(ex.getResponseHeaders());
return sendContent(ex,targetUser.toMap());
} catch (UmbrellaException e) {
return sendContent(ex,e.statusCode(),e.getMessage());
}
}
public boolean logout(HttpExchange ex, Optional<Token> optToken) throws IOException {
if (optToken.isPresent()){
var token = optToken.get();
try {
users.dropSession(token);
} catch (UmbrellaException ignored){
}
new SessionToken(token.toString(),"/", Instant.now().minus(1, DAYS),true).addTo(ex);
return sendEmptyResponse(HTTP_OK,ex);
}
return sendEmptyResponse(HTTP_UNAUTHORIZED,ex);
} }
private boolean patchPassword(HttpExchange ex, UmbrellaUser requestingUser) throws IOException { private boolean patchPassword(HttpExchange ex, UmbrellaUser requestingUser) throws IOException {
if (!(requestingUser instanceof DbUser user)) return sendContent(ex, ResponseCode.HTTP_SERVER_ERROR,"DbUser expected"); if (!(requestingUser instanceof DbUser user)) return sendContent(ex, HTTP_SERVER_ERROR,"DbUser expected");
JSONObject json; JSONObject json;
try { try {
json = json(ex); json = json(ex);
@@ -184,35 +270,6 @@ public class UserModule extends PathHandler {
} }
} }
@Override
public boolean doPost(Path path, HttpExchange ex) throws IOException {
addCors(ex);
var p = path.toString();
switch (p){
case LOGIN: return postLogin(ex);
}
return super.doPost(path, ex);
}
private boolean getUser(HttpExchange ex, UmbrellaUser user) throws IOException {
if (user != null) return sendContent(ex,user);
return sendEmptyResponse(HTTP_UNAUTHORIZED,ex);
}
public boolean logout(HttpExchange ex, Optional<Token> optToken) throws IOException {
if (optToken.isPresent()){
var token = optToken.get();
try {
users.dropSession(token);
} catch (UmbrellaException ignored){
}
new SessionToken(token.toString(),"/", Instant.now().minus(1, DAYS),true).addTo(ex);
return sendEmptyResponse(HTTP_OK,ex);
}
return sendEmptyResponse(HTTP_UNAUTHORIZED,ex);
}
private boolean postLogin(HttpExchange ex) throws IOException { private boolean postLogin(HttpExchange ex) throws IOException {
var json = json(ex); var json = json(ex);
if (!(json.has(USERNAME) && json.get(USERNAME) instanceof String username)) return sendContent(ex, HTTP_UNPROCESSABLE,"Username missing"); if (!(json.has(USERNAME) && json.get(USERNAME) instanceof String username)) return sendContent(ex, HTTP_UNPROCESSABLE,"Username missing");
@@ -230,6 +287,16 @@ public class UserModule extends PathHandler {
} }
} }
static int score(String password){
if (password == null) return 0;
var score = 0;
for (int i=0; i<password.length(); i++){
int c = password.charAt(i);
score += Character.isDigit(c) || Character.isLetter(c) ? 1 : 3;
}
return score;
}
private boolean update(HttpExchange ex, DbUser user, JSONObject json) throws UmbrellaException, IOException { private boolean update(HttpExchange ex, DbUser user, JSONObject json) throws UmbrellaException, IOException {
var id = user.id(); var id = user.id();
var name = json.has(NAME) && json.get(NAME) instanceof String s && !s.isBlank() ? s : user.name(); var name = json.has(NAME) && json.get(NAME) instanceof String s && !s.isBlank() ? s : user.name();
@@ -241,16 +308,6 @@ public class UserModule extends PathHandler {
return sendContent(ex,HTTP_OK,saved); return sendContent(ex,HTTP_OK,saved);
} }
static int score(String password){
if (password == null) return 0;
var score = 0;
for (int i=0; i<password.length(); i++){
int c = password.charAt(i);
score += Character.isDigit(c) || Character.isLetter(c) ? 1 : 3;
}
return score;
}
private static boolean weak(String password){ private static boolean weak(String password){
return score(password) < 14; return score(password) < 14;
}; };

View File

@@ -40,4 +40,13 @@ footer {
color: black; color: black;
padding: 5px; padding: 5px;
border-radius: 6px; border-radius: 6px;
}
fieldset[tabindex="0"]{
max-height: 55px;
overflow: hidden;
}
fieldset[tabindex="0"]:focus-within{
max-height: unset;
} }