Compare commits

...

30 Commits

Author SHA1 Message Date
536f11bbfd dovwiefiwuef' 2025-09-26 16:37:55 +03:00
271f3289e5 fix 2025-09-26 16:06:15 +03:00
ac56849a3b fix 2025-09-26 15:54:02 +03:00
0050a4130b fix 2025-09-25 23:37:30 +03:00
828d5853d6 fix 2025-09-25 23:35:22 +03:00
197d699fda fix 2025-09-25 23:33:22 +03:00
ce10a8595d fix 2025-09-25 23:21:25 +03:00
94eea2d425 fix 2025-09-25 22:59:59 +03:00
3eb40713b1 fix 2025-09-25 22:37:14 +03:00
a1183aab56 fix 2025-09-25 17:23:58 +03:00
de7e645f11 fix 2025-09-25 17:14:45 +03:00
67d2c839a5 fix 2025-09-24 17:52:44 +03:00
0f773262a1 fix 2025-09-24 17:15:33 +03:00
30dcbcb407 fix 2025-09-24 17:10:57 +03:00
98832beb27 fix 2025-09-24 17:05:07 +03:00
4008a92a49 fix 2025-09-24 15:59:36 +03:00
2b6d82229c fix 2025-09-24 15:47:39 +03:00
d0c6d44528 fix 2025-09-23 23:40:12 +03:00
e429b56384 fix 2025-09-23 23:35:58 +03:00
5b174702d8 fix 2025-09-23 23:34:17 +03:00
703fcaec39 fix 2025-09-23 23:21:04 +03:00
69a4634f8a fix 2025-09-23 23:14:48 +03:00
e349c5e0f3 fix 2025-09-23 23:11:25 +03:00
48b47cfa88 fix 2025-09-23 23:07:05 +03:00
660dd1854f fix 2025-09-23 22:54:10 +03:00
69692faac5 fix 2025-09-23 22:49:51 +03:00
95153cd55b fix 2025-09-23 22:46:49 +03:00
9f3c42e3f9 fix 2025-09-23 17:20:13 +03:00
67f9dc73e5 fix 2025-09-23 17:14:11 +03:00
58b4bc47a6 fix 2025-09-23 16:29:00 +03:00
4 changed files with 138 additions and 51 deletions

View File

@@ -1,5 +1,6 @@
[
[ "selfprivacy", "domain" ],
[ "selfprivacy", "username" ],
[ "selfprivacy", "modules", "auth", "enable" ],
[ "selfprivacy", "modules", "mastodon" ],
[ "selfprivacy", "passthru", "auth" ],

View File

@@ -1,6 +1,5 @@
{
# TODO: check whether there is no TODOs
# TODO: check whether there is no hedgegdoc mentions
description = "Mastodon module";
outputs = { ... }:

View File

@@ -1,6 +1,6 @@
import os
import time
import json
import time
import requests
import psycopg2 as ps
@@ -8,55 +8,141 @@ def read_file(path):
with open(path, "r", encoding="utf-8") as f:
return f.read()
def getenv(name):
try:
return os.environ[name]
except KeyError:
print(f"Missing environment variable {name}. You should NOT run this script by hand, please use systemd mastodon-kanidm-sync.service.")
print(f"[ERROR] Missing environment variable {name}. You should NOT run this script by hand, please use systemd mastodon-kanidm-sync.service.")
exit(1)
# Import configuration
KANIDM_URL = getenv("KANIDM_URL")
KANIDM_TOKEN = read_file(getenv("KANIDM_TOKEN_PATH")).strip()
# USERDATA = read_file(getenv("USERDATA_FILE_PATH")).strip()
OWNER_USERNAME = getenv("OWNER_USERNAME")
SLEEP_TIME = int(getenv("SLEEP_TIME"))
conn = ps.connect(
dbname=getenv("POSTGRES_DBNAME"),
user=getenv("POSTGRES_USER"),
host=getenv("POSTGRES_HOST")
)
def sync_mastodon():
# Fetch kanidm users list from userdata file
# Userdata file is json list with information about what users are configured by kanidm
try:
USERDATA = read_file(getenv("USERDATA_FILE_PATH")).strip()
userdata = json.loads(USERDATA)
print("[INFO] ")
except FileNotFoundError:
userdata = []
cur = conn.cursor()
cur.execute('''
SELECT identities.uid, users.id, user_roles.name
FROM users
JOIN identities
ON users.id = identities.id
LEFT JOIN user_roles
ON users.role_id = user_roles.id;
'''
)
# Load database
conn = ps.connect(
dbname=getenv("POSTGRES_DBNAME"),
user=getenv("POSTGRES_USER"),
host=getenv("POSTGRES_HOST")
)
state = cur.fetchall()
print(state) # DEBUG
print(type(state)) # DEBUG
# Fetch current userdata from database
cur = conn.cursor()
cur.execute('''
SELECT identities.uid, users.id, user_roles.name
FROM users
JOIN identities
ON users.id = identities.id
LEFT JOIN user_roles
ON users.role_id = user_roles.id;
'''
)
kanidm_users_raw = requests.get(
f"{KANIDM_URL}/v1/person",
headers={
"Authorization": f"Bearer {KANIDM_TOKEN}",
"Content-Type": "application/json",
},
timeout=5,
).json()
state = cur.fetchall()
for i in kanidm_users_raw:
i = i["attrs"]
uid = i["name"]
# if uid in db_users:
# print(uid)
print(uid)
users = {}
for i in state:
users[i[0]] = {
"id": i[1],
"role": i[2],
"isKanidmUser": False
}
cur.close()
conn.close()
# Fetch Kanidm userdata
kanidm_users_raw = requests.get(
f"{KANIDM_URL}/v1/person",
headers={
"Authorization": f"Bearer {KANIDM_TOKEN}",
"Content-Type": "application/json",
},
timeout=5,
).json()
def give_role(uid, role, putUserdata = True):
if (uid not in userdata) and (putUserdata):
userdata.append(uid)
users[uid]["isKanidmUser"] = True
users[uid]["role"] = role
print(f"[INFO] {uid} is marked as {role}")
for i in kanidm_users_raw:
i = i["attrs"]
for uid in i["name"]: # [user].attrs.name is a list
if uid in users: # Don't apply anything for users who have no mastodon access (sp.mastodon.users) or didn't register
if uid == OWNER_USERNAME:
give_role(uid, "Owner", False)
continue
for group in i["memberof"]:
if group.startswith("sp.mastodon.admins@") or group.startswith("sp.admins@"):
give_role(uid, "Admin")
break
elif group.startswith("sp.mastodon.moderators@"):
give_role(uid, "Moderator")
break
elif uid in userdata:
# If user, who previously had a role, has no roles set by Kanidm, delete them from userdata list so allow setting roles directly by mastodon
give_role(uid, None, False)
userdata.remove(uid)
print("[DEBUG]", users)
# Fetch RoleIDs
cur = conn.cursor()
cur.execute("SELECT id, name FROM user_roles;")
roles_raw = cur.fetchall()
roles = {}
for i in roles_raw:
roles[i[1]] = i[0]
# Give roles
for uid in users:
if not users[uid]["isKanidmUser"]:
continue
if users[uid]["role"]:
rolename = users[uid]["role"]
roleid = roles[rolename]
else:
roleid = "NULL"
sqlcommand = f"UPDATE users SET role_id = {roleid} WHERE id = {users[uid]["id"]};"
print("[DEBUG] SQL:", sqlcommand)
cur.execute(sqlcommand)
conn.commit()
cur.close()
conn.close()
print("[INFO] Final userdata.json file content: ", userdata)
def write_userdata(mode):
with open(getenv("USERDATA_FILE_PATH"), mode) as f:
f.write(json.dumps(userdata))
f.close()
try:
write_userdata("w")
except FileNotFoundError:
print("[INFO] userdata.json file doesn't exist. Creating it")
write_userdata("x")
while True:
sync_mastodon()
time.sleep(SLEEP_TIME)

View File

@@ -91,13 +91,13 @@ in
enableUnixSocket = false;
configureNginx = true;
database.createLocally = true;
streamingProcesses = 3;
streamingProcesses = 2;
smtp = {
createLocally = false;
fromAddress = "mastodon@${sp.domain}";
user = "mastodon";
fromAddress = "noreply.mastodon@${sp.domain}";
user = "noreply.mastodon";
passwordFile = secrets.passwordFile;
authenticate = true;
@@ -105,8 +105,7 @@ in
port = 465;
};
extraConfig = {
# "SMTP_ENABLE_STARTTLS" = "never";
"SMTP_ENABLE_STARTTLS_AUTO" = "true";
"SMTP_ENABLE_STARTTLS_AUTO" = "true"; # Simple NixOS MailServer doesn't allow connections without SSL
"SMTP_ENABLE_STARTTLS" = "always";
"SMTP_TLS" = "true";
"SMTP_SSL" = "true";
@@ -114,10 +113,8 @@ in
"DISALLOW_UNAUTHENTICATED_API_ACCESS" = lib.boolToString cfg.dissallowUnauthenticatedAPI;
};
};
users.users.mastodon.isSystemUser = lib.mkForce false;
users.users.mastodon.isNormalUser = lib.mkForce true;
selfprivacy.emails."mastodon" = {
selfprivacy.emails."noreplymastodon" = {
hashedPasswordFile = secrets.hashedPasswordFile;
systemdTargets = [ "mastodon-email-password-setup.service" ];
sendOnly = true;
@@ -128,6 +125,7 @@ in
enable = true;
wantedBy = [ "multi-user.target" "mastodon-web.service" "postfix.service" ];
serviceConfig = {
Slice = "mastodon.slice";
Type = "oneshot";
ExecStart = pkgs.writeShellScript "gen-mastodon-email-password" ''
export password=$(head -c 32 /dev/urandom | base64 | sed 's/[+=\\/A-Z]//g')
@@ -150,7 +148,6 @@ in
services.mastodon-kanidm-sync = {
after = [
# "mastodon.service" # TODO: ??
"postgresql.service"
"kanidm.service"
];
@@ -166,6 +163,9 @@ in
POSTGRES_DBNAME = db.name;
POSTGRES_USER = db.user;
POSTGRES_HOST = db.host;
USERDATA_FILE_PATH = "/var/lib/mastodon/.userdata.json";
OWNER_USERNAME = sp.username;
SLEEP_TIME = "30";
};
serviceConfig = {
Slice = "mastodon.slice";
@@ -176,7 +176,7 @@ in
doCheck = false;
libraries = with pkgs.python3Packages; [
requests
psycopg
psycopg2
];
} (builtins.readFile ./mastodon-kanidm-sync.py);
};
@@ -185,7 +185,7 @@ in
services.mastodon-web = {
unitConfig.RequiresMountsFor = lib.mkIf sp.useBinds "/volumes/${cfg.location}/mastodon";
serviceConfig = {
Slice = "hedgedoc.slice";
Slice = "mastodon.slice";
LoadCredential = ["client-secret:${oauthClientSecretFP}"];
ExecStart = lib.mkForce (pkgs.writeShellScript "run-mastodon-with-client-secret" ''
export OIDC_CLIENT_SECRET=$(cat $CREDENTIALS_DIRECTORY/client-secret)
@@ -209,6 +209,7 @@ in
};
};
services.kanidm.provision.groups."sp.mastodon.moderators" = {};
selfprivacy.auth.clients.${oauthClientID} = {
inherit usersGroup;
inherit adminsGroup;