Compare commits

...

14 commits

10 changed files with 263 additions and 115 deletions

View file

@ -29,11 +29,16 @@ Matrix clients. (#35)
### New Features ### New Features
- Implemented `/_telodendria/admin/v1/deactivate/[localpart]` for admins to be able to
deactivate users.
- Moved all administrator API endpoints to `/_telodendria/admin/v1`, because later revisions - Moved all administrator API endpoints to `/_telodendria/admin/v1`, because later revisions
of the administrator API may break clients, so we want a way to give those breaking revisions of the administrator API may break clients, so we want a way to give those breaking revisions
new endpoints. new endpoints.
- Implemented `/_telodendria/admin/v1/deactivate/[localpart]` for admins to be able to
deactivate users.
- Implemented the following APIs for managing registration tokens:
- **GET** `/_telodendria/admin/tokens`
- **GET** `/_telodendria/admin/tokens/[token]`
- **POST** `/_telodendria/admin/tokens`
- **DELETE** `/_telodendria/admin/tokens/[token]`
## v0.3.0 ## v0.3.0

View file

@ -30,8 +30,10 @@
#include <Cytoplasm/Json.h> #include <Cytoplasm/Json.h>
#include <Cytoplasm/Util.h> #include <Cytoplasm/Util.h>
#include <Cytoplasm/Str.h> #include <Cytoplasm/Str.h>
#include <User.h>
#include <Cytoplasm/Int64.h> #include <Cytoplasm/Int64.h>
#include <Cytoplasm/Log.h>
#include <User.h>
int int
RegTokenValid(RegTokenInfo * token) RegTokenValid(RegTokenInfo * token)
@ -99,8 +101,7 @@ RegTokenDelete(RegTokenInfo * token)
{ {
return 0; return 0;
} }
Free(token->name); RegTokenInfoFree(token);
Free(token->owner);
Free(token); Free(token);
return 1; return 1;
} }
@ -113,6 +114,8 @@ RegTokenGetInfo(Db * db, char *token)
DbRef *tokenRef; DbRef *tokenRef;
HashMap *tokenJson; HashMap *tokenJson;
char *errp = NULL;
if (!RegTokenExists(db, token)) if (!RegTokenExists(db, token))
{ {
return NULL; return NULL;
@ -126,36 +129,25 @@ RegTokenGetInfo(Db * db, char *token)
tokenJson = DbJson(tokenRef); tokenJson = DbJson(tokenRef);
ret = Malloc(sizeof(RegTokenInfo)); ret = Malloc(sizeof(RegTokenInfo));
if (!RegTokenInfoFromJson(tokenJson, ret, &errp))
{
Log(LOG_ERR, "RegTokenGetInfo(): Database decoding error: %s", errp);
RegTokenFree(ret);
return NULL;
}
ret->db = db; ret->db = db;
ret->ref = tokenRef; ret->ref = tokenRef;
ret->owner =
StrDuplicate(JsonValueAsString(HashMapGet(tokenJson, "created_by")));
ret->name = StrDuplicate(token);
ret->expires =
JsonValueAsInteger(HashMapGet(tokenJson, "expires_on"));
ret->created =
JsonValueAsInteger(HashMapGet(tokenJson, "created_on"));
ret->uses =
JsonValueAsInteger(HashMapGet(tokenJson, "uses"));
ret->used =
JsonValueAsInteger(HashMapGet(tokenJson, "used"));
ret->grants =
UserDecodePrivileges(HashMapGet(tokenJson, "grants"));
return ret; return ret;
} }
void void
RegTokenFree(RegTokenInfo * tokeninfo) RegTokenFree(RegTokenInfo *tokeninfo)
{ {
if (tokeninfo) if (tokeninfo)
{ {
Free(tokeninfo->name); RegTokenInfoFree(tokeninfo);
Free(tokeninfo->owner);
Free(tokeninfo); Free(tokeninfo);
} }
} }
@ -167,6 +159,9 @@ RegTokenClose(RegTokenInfo * tokeninfo)
return 0; return 0;
} }
/* Write object to database. */
DbJsonSet(tokeninfo->ref, RegTokenInfoToJson(tokeninfo));
return DbUnlock(tokeninfo->db, tokeninfo->ref); return DbUnlock(tokeninfo->db, tokeninfo->ref);
} }
static int static int
@ -202,7 +197,6 @@ RegTokenInfo *
RegTokenCreate(Db * db, char *name, char *owner, UInt64 expires, Int64 uses, int privileges) RegTokenCreate(Db * db, char *name, char *owner, UInt64 expires, Int64 uses, int privileges)
{ {
RegTokenInfo *ret; RegTokenInfo *ret;
HashMap *tokenJson;
UInt64 timestamp = UtilServerTs(); UInt64 timestamp = UtilServerTs();
@ -235,26 +229,12 @@ RegTokenCreate(Db * db, char *name, char *owner, UInt64 expires, Int64 uses, int
return NULL; return NULL;
} }
ret->name = StrDuplicate(name); ret->name = StrDuplicate(name);
ret->owner = StrDuplicate(owner); ret->created_by = StrDuplicate(owner);
ret->used = Int64Create(0, 0); ret->used = Int64Create(0, 0);
ret->uses = uses; ret->uses = uses;
ret->created = timestamp; ret->created_on = timestamp;
ret->expires = expires; ret->expires_on = expires;
ret->grants = privileges; ret->grants = UserEncodePrivileges(privileges);
/* Write user info to database. */
tokenJson = DbJson(ret->ref);
HashMapSet(tokenJson, "created_by",
JsonValueString(ret->owner));
HashMapSet(tokenJson, "created_on",
JsonValueInteger(ret->created));
HashMapSet(tokenJson, "expires_on",
JsonValueInteger(ret->expires));
HashMapSet(tokenJson, "used",
JsonValueInteger(ret->used));
HashMapSet(tokenJson, "uses",
JsonValueInteger(ret->uses));
HashMapSet(tokenJson, "grants", UserEncodePrivileges(privileges));
return ret; return ret;
} }

View file

@ -87,6 +87,8 @@ RouterBuild(void)
R("/_telodendria/admin/v1/privileges", RoutePrivileges); R("/_telodendria/admin/v1/privileges", RoutePrivileges);
R("/_telodendria/admin/v1/privileges/(.*)", RoutePrivileges); R("/_telodendria/admin/v1/privileges/(.*)", RoutePrivileges);
R("/_telodendria/admin/v1/deactivate/(.*)", RouteAdminDeactivate); R("/_telodendria/admin/v1/deactivate/(.*)", RouteAdminDeactivate);
R("/_telodendria/admin/v1/tokens/(.*)", RouteAdminTokens);
R("/_telodendria/admin/v1/tokens", RouteAdminTokens);
#undef R #undef R

View file

@ -0,0 +1,212 @@
/*
* Copyright (C) 2022-2023 Jordan Bancino <@jordan:bancino.net>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <Routes.h>
#include <Cytoplasm/Json.h>
#include <Cytoplasm/HashMap.h>
#include <Cytoplasm/Str.h>
#include <Cytoplasm/Memory.h>
#include <RegToken.h>
#include <User.h>
ROUTE_IMPL(RouteAdminTokens, path, argp)
{
RouteArgs *args = argp;
HashMap *request = NULL;
HashMap *response = NULL;
char *token;
char *username;
char *name;
char *msg;
Db *db = args->matrixArgs->db;
User *user = NULL;
HttpRequestMethod method = HttpRequestMethodGet(args->context);
Array *tokensarray;
Array *tokens;
RegTokenInfo *info;
RegTokenAdminRequest *req;
size_t i;
Int64 maxuses;
Int64 lifetime;
if (method != HTTP_GET && method != HTTP_POST && method != HTTP_DELETE)
{
msg = "Route only supports GET, POST, and DELETE";
HttpResponseStatus(args->context, HTTP_BAD_REQUEST);
return MatrixErrorCreate(M_UNRECOGNIZED, msg);
}
response = MatrixGetAccessToken(args->context, &token);
if (response)
{
goto finish;
}
user = UserAuthenticate(db, token);
if (!user)
{
HttpResponseStatus(args->context, HTTP_BAD_REQUEST);
response = MatrixErrorCreate(M_UNKNOWN_TOKEN, NULL);
goto finish;
}
if (!(UserGetPrivileges(user) & USER_ISSUE_TOKENS))
{
msg = "User doesn't have the ISSUE_TOKENS privilege.";
HttpResponseStatus(args->context, HTTP_FORBIDDEN);
response = MatrixErrorCreate(M_FORBIDDEN, msg);
goto finish;
}
switch (method)
{
case HTTP_GET:
if (ArraySize(path) == 0)
{
tokensarray = ArrayCreate();
/* Get all registration tokens */
tokens = DbList(db, 2, "tokens", "registration");
response = HashMapCreate();
for (i = 0; i < ArraySize(tokens); i++)
{
char *tokenname = ArrayGet(tokens, i);
HashMap *jsoninfo;
info = RegTokenGetInfo(db, tokenname);
jsoninfo = RegTokenInfoToJson(info);
RegTokenClose(info);
RegTokenFree(info);
ArrayAdd(tokensarray, JsonValueObject(jsoninfo));
}
JsonSet(response, JsonValueArray(tokensarray), 1, "tokens");
DbListFree(tokens);
break;
}
info = RegTokenGetInfo(db, ArrayGet(path, 0));
if (!info)
{
msg = "Token doesn't exist.";
HttpResponseStatus(args->context, HTTP_BAD_REQUEST);
response = MatrixErrorCreate(M_INVALID_PARAM, msg);
goto finish;
}
response = RegTokenInfoToJson(info);
RegTokenClose(info);
RegTokenFree(info);
break;
case HTTP_POST:
request = JsonDecode(HttpServerStream(args->context));
if (!request)
{
HttpResponseStatus(args->context, HTTP_BAD_REQUEST);
response = MatrixErrorCreate(M_NOT_JSON, NULL);
goto finish;
}
req = Malloc(sizeof(RegTokenAdminRequest));
req->max_uses = Int64Neg(Int64Create(0, 1));
req->lifetime = Int64Create(0, 0);
req->name = NULL;
if (!RegTokenAdminRequestFromJson(request, req, &msg))
{
RegTokenAdminRequestFree(req);
Free(req);
HttpResponseStatus(args->context, HTTP_BAD_REQUEST);
response = MatrixErrorCreate(M_BAD_JSON, msg);
goto finish;
}
if (!req->name)
{
req->name = StrRandom(16);
}
username = UserGetName(user);
name = req->name;
maxuses = req->max_uses;
lifetime = req->lifetime;
info = RegTokenCreate(db, name, username, maxuses, lifetime, 0);
if (!info)
{
RegTokenClose(info);
RegTokenFree(info);
RegTokenAdminRequestFree(req);
Free(req);
HttpResponseStatus(args->context, HTTP_BAD_REQUEST);
msg = "Cannot create token";
response = MatrixErrorCreate(M_INVALID_PARAM, msg);
goto finish;
}
response = RegTokenInfoToJson(info);
RegTokenClose(info);
RegTokenFree(info);
RegTokenAdminRequestFree(req);
Free(req);
break;
case HTTP_DELETE:
if (ArraySize(path) == 0)
{
msg = "No registration token given to DELETE /tokens/[token].";
HttpResponseStatus(args->context, HTTP_BAD_REQUEST);
response = MatrixErrorCreate(M_INVALID_PARAM, msg);
goto finish;
}
info = RegTokenGetInfo(db, ArrayGet(path, 0));
RegTokenDelete(info);
/* As this is a No Content, let's not set any data in the
* response */
HttpResponseStatus(args->context, HTTP_NO_CONTENT);
default:
/* Fallthrough, as those are naturally kept out beforehand */
break;
}
finish:
UserUnlock(user);
JsonFree(request);
return response;
}

View file

@ -98,15 +98,15 @@ ROUTE_IMPL(RoutePrivileges, path, argp)
switch (HttpRequestMethodGet(args->context)) switch (HttpRequestMethodGet(args->context))
{ {
case HTTP_POST: case HTTP_POST:
privileges = UserDecodePrivileges(val); privileges = UserDecodePrivileges(JsonValueAsArray(val));
break; break;
case HTTP_PUT: case HTTP_PUT:
privileges = UserGetPrivileges(user); privileges = UserGetPrivileges(user);
privileges |= UserDecodePrivileges(val); privileges |= UserDecodePrivileges(JsonValueAsArray(val));
break; break;
case HTTP_DELETE: case HTTP_DELETE:
privileges = UserGetPrivileges(user); privileges = UserGetPrivileges(user);
privileges &= ~UserDecodePrivileges(val); privileges &= ~UserDecodePrivileges(JsonValueAsArray(val));
break; break;
default: default:
/* Impossible */ /* Impossible */

View file

@ -276,7 +276,7 @@ ROUTE_IMPL(RouteRegister, path, argp)
if (info) if (info)
{ {
UserSetPrivileges(user, info->grants); UserSetPrivileges(user, UserDecodePrivileges(info->grants));
RegTokenClose(info); RegTokenClose(info);
RegTokenFree(info); RegTokenFree(info);
} }

View file

@ -768,7 +768,7 @@ UserSetPrivileges(User * user, int privileges)
return 1; return 1;
} }
val = UserEncodePrivileges(privileges); val = JsonValueArray(UserEncodePrivileges(privileges));
if (!val) if (!val)
{ {
return 0; return 0;
@ -779,31 +779,26 @@ UserSetPrivileges(User * user, int privileges)
} }
int int
UserDecodePrivileges(JsonValue * val) UserDecodePrivileges(Array * arr)
{ {
int privileges = USER_NONE; int privileges = USER_NONE;
size_t i; size_t i;
Array *arr;
if (!val) if (!arr)
{ {
goto finish; goto finish;
} }
if (JsonValueType(val) == JSON_ARRAY) for (i = 0; i < ArraySize(arr); i++)
{ {
arr = JsonValueAsArray(val); JsonValue *val = ArrayGet(arr, i);
for (i = 0; i < ArraySize(arr); i++) if (!val || JsonValueType(val) != JSON_STRING)
{ {
val = ArrayGet(arr, i); continue;
if (!val || JsonValueType(val) != JSON_STRING)
{
continue;
}
privileges |= UserDecodePrivilege(JsonValueAsString(val));
} }
privileges |= UserDecodePrivilege(JsonValueAsString(val));
} }
finish: finish:
@ -851,7 +846,7 @@ UserDecodePrivilege(const char *p)
} }
} }
JsonValue * Array *
UserEncodePrivileges(int privileges) UserEncodePrivileges(int privileges)
{ {
Array *arr = ArrayCreate(); Array *arr = ArrayCreate();
@ -883,7 +878,7 @@ UserEncodePrivileges(int privileges)
#undef A #undef A
finish: finish:
return JsonValueArray(arr); return arr;
} }
UserId * UserId *

View file

@ -42,54 +42,7 @@
#include <Cytoplasm/Db.h> #include <Cytoplasm/Db.h>
#include <Cytoplasm/Int64.h> #include <Cytoplasm/Int64.h>
/** #include <Schema/RegToken.h>
* This structure describes a registration token that is in the
* database.
*/
typedef struct RegTokenInfo
{
Db *db;
DbRef *ref;
/*
* The token itself.
*/
char *name;
/*
* Who created this token. Note that this can be NULL if the
* token was created by Telodendria itself.
*/
char *owner;
/*
* How many times the token was used.
*/
Int64 used;
/*
* How many uses are allowed.
*/
Int64 uses;
/*
* Timestamp when this token was created.
*/
UInt64 created;
/*
* Timestamp when this token expires, or 0 if it does not
* expire.
*/
UInt64 expires;
/*
* A bit field describing the privileges this token grants. See
* the User API documentation for the privileges supported.
*/
int grants;
} RegTokenInfo;
/** /**
* ``Use'' the specified registration token by increasing the used * ``Use'' the specified registration token by increasing the used
@ -132,7 +85,6 @@ RegTokenCreate(Db *, char *, char *, UInt64, Int64, int);
* .Fn RegTokenClose . * .Fn RegTokenClose .
*/ */
extern void RegTokenFree(RegTokenInfo *); extern void RegTokenFree(RegTokenInfo *);
/** /**
* Return a boolean value indicating whether or not the specified token * Return a boolean value indicating whether or not the specified token
* is valid. A registration token is only valid if it has not expired * is valid. A registration token is only valid if it has not expired

View file

@ -105,6 +105,8 @@ ROUTE(RouteRoomAliases);
ROUTE(RouteAdminDeactivate); ROUTE(RouteAdminDeactivate);
ROUTE(RouteAdminTokens);
#undef ROUTE #undef ROUTE
#endif #endif

View file

@ -286,13 +286,13 @@ extern int UserSetPrivileges(User *, int);
* Decode the JSON that represents the user privileges into a packed * Decode the JSON that represents the user privileges into a packed
* bit field for simple manipulation. * bit field for simple manipulation.
*/ */
extern int UserDecodePrivileges(JsonValue *); extern int UserDecodePrivileges(Array *);
/** /**
* Encode the packed bit field that represents user privileges as a * Encode the packed bit field that represents user privileges as a
* JSON value. * JSON value.
*/ */
extern JsonValue *UserEncodePrivileges(int); extern Array *UserEncodePrivileges(int);
/** /**
* Convert a string privilege into its bit in the bit field. This is * Convert a string privilege into its bit in the bit field. This is