Moved share permission parsing to jsonb implementation of ef core. Improved auth handling for shares
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
using System.ComponentModel.DataAnnotations.Schema;
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
|
using MoonlightServers.ApiServer.Models;
|
||||||
|
|
||||||
namespace MoonlightServers.ApiServer.Database.Entities;
|
namespace MoonlightServers.ApiServer.Database.Entities;
|
||||||
|
|
||||||
@@ -9,8 +10,7 @@ public class ServerShare
|
|||||||
public int UserId { get; set; }
|
public int UserId { get; set; }
|
||||||
public Server Server { get; set; }
|
public Server Server { get; set; }
|
||||||
|
|
||||||
[Column(TypeName = "jsonb")]
|
public ServerShareContent Content { get; set; } = new();
|
||||||
public string Permissions { get; set; }
|
|
||||||
|
|
||||||
[Column(TypeName="timestamp with time zone")]
|
[Column(TypeName="timestamp with time zone")]
|
||||||
public DateTime CreatedAt { get; set; }
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
|||||||
namespace MoonlightServers.ApiServer.Database.Migrations
|
namespace MoonlightServers.ApiServer.Database.Migrations
|
||||||
{
|
{
|
||||||
[DbContext(typeof(ServersDataContext))]
|
[DbContext(typeof(ServersDataContext))]
|
||||||
[Migration("20250605210823_AddedServerShares")]
|
[Migration("20250606121013_AddedShares")]
|
||||||
partial class AddedServerShares
|
partial class AddedShares
|
||||||
{
|
{
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
@@ -194,10 +194,6 @@ namespace MoonlightServers.ApiServer.Database.Migrations
|
|||||||
b.Property<DateTime>("CreatedAt")
|
b.Property<DateTime>("CreatedAt")
|
||||||
.HasColumnType("timestamp with time zone");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
b.Property<string>("Permissions")
|
|
||||||
.IsRequired()
|
|
||||||
.HasColumnType("jsonb");
|
|
||||||
|
|
||||||
b.Property<int>("ServerId")
|
b.Property<int>("ServerId")
|
||||||
.HasColumnType("integer");
|
.HasColumnType("integer");
|
||||||
|
|
||||||
@@ -434,6 +430,50 @@ namespace MoonlightServers.ApiServer.Database.Migrations
|
|||||||
.OnDelete(DeleteBehavior.Cascade)
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
.IsRequired();
|
.IsRequired();
|
||||||
|
|
||||||
|
b.OwnsOne("MoonlightServers.ApiServer.Models.ServerShareContent", "Content", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<int>("ServerShareId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b1.HasKey("ServerShareId");
|
||||||
|
|
||||||
|
b1.ToTable("Servers_ServerShares");
|
||||||
|
|
||||||
|
b1.ToJson("Content");
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("ServerShareId");
|
||||||
|
|
||||||
|
b1.OwnsMany("MoonlightServers.ApiServer.Models.ServerSharePermission", "Permissions", b2 =>
|
||||||
|
{
|
||||||
|
b2.Property<int>("ServerShareContentServerShareId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b2.Property<int>("__synthesizedOrdinal")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b2.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b2.Property<int>("Type")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b2.HasKey("ServerShareContentServerShareId", "__synthesizedOrdinal");
|
||||||
|
|
||||||
|
b2.ToTable("Servers_ServerShares");
|
||||||
|
|
||||||
|
b2.WithOwner()
|
||||||
|
.HasForeignKey("ServerShareContentServerShareId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b1.Navigation("Permissions");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.Navigation("Content")
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
b.Navigation("Server");
|
b.Navigation("Server");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
|||||||
namespace MoonlightServers.ApiServer.Database.Migrations
|
namespace MoonlightServers.ApiServer.Database.Migrations
|
||||||
{
|
{
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public partial class AddedServerShares : Migration
|
public partial class AddedShares : Migration
|
||||||
{
|
{
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
protected override void Up(MigrationBuilder migrationBuilder)
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
@@ -20,9 +20,9 @@ namespace MoonlightServers.ApiServer.Database.Migrations
|
|||||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
UserId = table.Column<int>(type: "integer", nullable: false),
|
UserId = table.Column<int>(type: "integer", nullable: false),
|
||||||
ServerId = table.Column<int>(type: "integer", nullable: false),
|
ServerId = table.Column<int>(type: "integer", nullable: false),
|
||||||
Permissions = table.Column<string>(type: "jsonb", nullable: false),
|
|
||||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
|
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||||
|
Content = table.Column<string>(type: "jsonb", nullable: false)
|
||||||
},
|
},
|
||||||
constraints: table =>
|
constraints: table =>
|
||||||
{
|
{
|
||||||
@@ -191,10 +191,6 @@ namespace MoonlightServers.ApiServer.Database.Migrations
|
|||||||
b.Property<DateTime>("CreatedAt")
|
b.Property<DateTime>("CreatedAt")
|
||||||
.HasColumnType("timestamp with time zone");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
b.Property<string>("Permissions")
|
|
||||||
.IsRequired()
|
|
||||||
.HasColumnType("jsonb");
|
|
||||||
|
|
||||||
b.Property<int>("ServerId")
|
b.Property<int>("ServerId")
|
||||||
.HasColumnType("integer");
|
.HasColumnType("integer");
|
||||||
|
|
||||||
@@ -431,6 +427,50 @@ namespace MoonlightServers.ApiServer.Database.Migrations
|
|||||||
.OnDelete(DeleteBehavior.Cascade)
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
.IsRequired();
|
.IsRequired();
|
||||||
|
|
||||||
|
b.OwnsOne("MoonlightServers.ApiServer.Models.ServerShareContent", "Content", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<int>("ServerShareId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b1.HasKey("ServerShareId");
|
||||||
|
|
||||||
|
b1.ToTable("Servers_ServerShares");
|
||||||
|
|
||||||
|
b1.ToJson("Content");
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("ServerShareId");
|
||||||
|
|
||||||
|
b1.OwnsMany("MoonlightServers.ApiServer.Models.ServerSharePermission", "Permissions", b2 =>
|
||||||
|
{
|
||||||
|
b2.Property<int>("ServerShareContentServerShareId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b2.Property<int>("__synthesizedOrdinal")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b2.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b2.Property<int>("Type")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b2.HasKey("ServerShareContentServerShareId", "__synthesizedOrdinal");
|
||||||
|
|
||||||
|
b2.ToTable("Servers_ServerShares");
|
||||||
|
|
||||||
|
b2.WithOwner()
|
||||||
|
.HasForeignKey("ServerShareContentServerShareId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b1.Navigation("Permissions");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.Navigation("Content")
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
b.Navigation("Server");
|
b.Navigation("Server");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using Microsoft.EntityFrameworkCore;
|
|||||||
using MoonCore.Extended.SingleDb;
|
using MoonCore.Extended.SingleDb;
|
||||||
using Moonlight.ApiServer.Configuration;
|
using Moonlight.ApiServer.Configuration;
|
||||||
using MoonlightServers.ApiServer.Database.Entities;
|
using MoonlightServers.ApiServer.Database.Entities;
|
||||||
|
using MoonlightServers.ApiServer.Models;
|
||||||
|
|
||||||
namespace MoonlightServers.ApiServer.Database;
|
namespace MoonlightServers.ApiServer.Database;
|
||||||
|
|
||||||
@@ -30,4 +31,26 @@ public class ServersDataContext : DatabaseContext
|
|||||||
Database = configuration.Database.Database
|
Database = configuration.Database.Database
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
base.OnModelCreating(modelBuilder);
|
||||||
|
|
||||||
|
#region Shares
|
||||||
|
|
||||||
|
modelBuilder.Ignore<ServerShareContent>();
|
||||||
|
modelBuilder.Ignore<ServerSharePermission>();
|
||||||
|
|
||||||
|
modelBuilder.Entity<ServerShare>(builder =>
|
||||||
|
{
|
||||||
|
builder.OwnsOne(x => x.Content, navigationBuilder =>
|
||||||
|
{
|
||||||
|
navigationBuilder.ToJson();
|
||||||
|
|
||||||
|
navigationBuilder.OwnsMany(x => x.Permissions);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -164,8 +164,13 @@ public class FilesController : Controller
|
|||||||
if (server == null)
|
if (server == null)
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
throw new HttpApiException("No server with this id found", 404);
|
||||||
|
|
||||||
if (!await AuthorizeService.Authorize(User, server, permission => permission.Name == "files" && permission.Type >= type))
|
var authorizeResult = await AuthorizeService.Authorize(
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
User, server,
|
||||||
|
permission => permission.Name == "files" && permission.Type >= type
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!authorizeResult.Succeeded)
|
||||||
|
throw new HttpApiException("No permission for the requested resource", 403);
|
||||||
|
|
||||||
return server;
|
return server;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,8 +68,13 @@ public class PowerController : Controller
|
|||||||
if (server == null)
|
if (server == null)
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
throw new HttpApiException("No server with this id found", 404);
|
||||||
|
|
||||||
if (!await AuthorizeService.Authorize(User, server, permission => permission is { Name: "power", Type: ServerPermissionType.ReadWrite }))
|
var authorizeResult = await AuthorizeService.Authorize(
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
User, server,
|
||||||
|
permission => permission.Name == "power" && permission.Type >= ServerPermissionType.ReadWrite
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!authorizeResult.Succeeded)
|
||||||
|
throw new HttpApiException("No permission for the requested resource", 403);
|
||||||
|
|
||||||
return server;
|
return server;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -148,7 +148,9 @@ public class ServersController : Controller
|
|||||||
if (server == null)
|
if (server == null)
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
throw new HttpApiException("No server with this id found", 404);
|
||||||
|
|
||||||
if (!await AuthorizeService.Authorize(User, server))
|
var authorizationResult = await AuthorizeService.Authorize(User, server);
|
||||||
|
|
||||||
|
if (!authorizationResult.Succeeded)
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
throw new HttpApiException("No server with this id found", 404);
|
||||||
|
|
||||||
return new ServerDetailResponse()
|
return new ServerDetailResponse()
|
||||||
@@ -256,8 +258,10 @@ public class ServersController : Controller
|
|||||||
if (server == null)
|
if (server == null)
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
throw new HttpApiException("No server with this id found", 404);
|
||||||
|
|
||||||
if (!await AuthorizeService.Authorize(User, server, filter))
|
var authorizeResult = await AuthorizeService.Authorize(User, server, filter);
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
|
||||||
|
if (!authorizeResult.Succeeded)
|
||||||
|
throw new HttpApiException("No permission for the requested resource", 403);
|
||||||
|
|
||||||
return server;
|
return server;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,8 +47,13 @@ public class SettingsController : Controller
|
|||||||
if (server == null)
|
if (server == null)
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
throw new HttpApiException("No server with this id found", 404);
|
||||||
|
|
||||||
if (!await AuthorizeService.Authorize(User, server, permission => permission is { Name: "settings", Type: ServerPermissionType.ReadWrite }))
|
var authorizeResult = await AuthorizeService.Authorize(
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
User, server,
|
||||||
|
permission => permission is { Name: "settings", Type: >= ServerPermissionType.ReadWrite }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!authorizeResult.Succeeded)
|
||||||
|
throw new HttpApiException("No permission for the requested resource", 403);
|
||||||
|
|
||||||
return server;
|
return server;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -132,9 +132,13 @@ public class VariablesController : Controller
|
|||||||
if (server == null)
|
if (server == null)
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
throw new HttpApiException("No server with this id found", 404);
|
||||||
|
|
||||||
if (!await AuthorizeService.Authorize(User, server,
|
var authorizeResult = await AuthorizeService.Authorize(
|
||||||
permission => permission.Name == "variables" && permission.Type >= type))
|
User, server,
|
||||||
throw new HttpApiException("No server with this id found", 404);
|
permission => permission.Name == "variables" && permission.Type >= type
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!authorizeResult.Succeeded)
|
||||||
|
throw new HttpApiException("No permission for the requested resource", 403);
|
||||||
|
|
||||||
return server;
|
return server;
|
||||||
}
|
}
|
||||||
|
|||||||
6
MoonlightServers.ApiServer/Models/ServerShareContent.cs
Normal file
6
MoonlightServers.ApiServer/Models/ServerShareContent.cs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
namespace MoonlightServers.ApiServer.Models;
|
||||||
|
|
||||||
|
public class ServerShareContent
|
||||||
|
{
|
||||||
|
public List<ServerSharePermission> Permissions { get; set; } = [];
|
||||||
|
}
|
||||||
@@ -24,50 +24,54 @@ public class ServerAuthorizeService
|
|||||||
ShareRepository = shareRepository;
|
ShareRepository = shareRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> Authorize(ClaimsPrincipal user, Server server, Func<ServerSharePermission, bool>? filter = null)
|
public async Task<AuthorizationResult> Authorize(ClaimsPrincipal user, Server server, Func<ServerSharePermission, bool>? filter = null)
|
||||||
{
|
{
|
||||||
var userIdClaim = user.FindFirst("userId");
|
var userIdClaim = user.FindFirst("userId");
|
||||||
|
|
||||||
// User specific authorization
|
// User specific authorization
|
||||||
if (userIdClaim != null && await AuthorizeViaUser(userIdClaim, server, filter))
|
if (userIdClaim != null)
|
||||||
return true;
|
{
|
||||||
|
var result = await AuthorizeViaUser(userIdClaim, server, filter);
|
||||||
|
|
||||||
|
if (result.Succeeded)
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
// Permission specific authorization
|
// Permission specific authorization
|
||||||
return await AuthorizeViaPermission(user);
|
return await AuthorizeViaPermission(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<bool> AuthorizeViaUser(Claim userIdClaim, Server server, Func<ServerSharePermission, bool>? filter = null)
|
private async Task<AuthorizationResult> AuthorizeViaUser(Claim userIdClaim, Server server, Func<ServerSharePermission, bool>? filter = null)
|
||||||
{
|
{
|
||||||
var userId = int.Parse(userIdClaim.Value);
|
var userId = int.Parse(userIdClaim.Value);
|
||||||
|
|
||||||
if (server.OwnerId == userId)
|
if (server.OwnerId == userId)
|
||||||
return true;
|
return AuthorizationResult.Success();
|
||||||
|
|
||||||
var possibleShare = await ShareRepository
|
var possibleShare = await ShareRepository
|
||||||
.Get()
|
.Get()
|
||||||
.FirstOrDefaultAsync(x => x.Server.Id == server.Id && x.UserId == userId);
|
.FirstOrDefaultAsync(x => x.Server.Id == server.Id && x.UserId == userId);
|
||||||
|
|
||||||
if (possibleShare == null)
|
if (possibleShare == null)
|
||||||
return false;
|
return AuthorizationResult.Failed();
|
||||||
|
|
||||||
// If no filter has been specified every server share is valid
|
// If no filter has been specified every server share is valid
|
||||||
// no matter which permission the share actually has
|
// no matter which permission the share actually has
|
||||||
if (filter == null)
|
if (filter == null)
|
||||||
return true;
|
return AuthorizationResult.Success();
|
||||||
|
|
||||||
var permissionsOfShare = ParsePermissions(possibleShare.Permissions);
|
if(possibleShare.Content.Permissions.Any(filter))
|
||||||
|
return AuthorizationResult.Success();
|
||||||
|
|
||||||
return permissionsOfShare.Any(filter);
|
return AuthorizationResult.Failed();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<bool> AuthorizeViaPermission(ClaimsPrincipal user)
|
private async Task<AuthorizationResult> AuthorizeViaPermission(ClaimsPrincipal user)
|
||||||
{
|
{
|
||||||
var authorizeResult = await AuthorizationService.AuthorizeAsync(
|
return await AuthorizationService.AuthorizeAsync(
|
||||||
user,
|
user,
|
||||||
"permissions:admin.servers.get"
|
"permissions:admin.servers.get"
|
||||||
);
|
);
|
||||||
|
|
||||||
return authorizeResult.Succeeded;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private ServerSharePermission[] ParsePermissions(string permissionsString)
|
private ServerSharePermission[] ParsePermissions(string permissionsString)
|
||||||
@@ -96,34 +100,4 @@ public class ServerAuthorizeService
|
|||||||
|
|
||||||
return result.ToArray();
|
return result.ToArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool CheckSharePermission(ServerShare share, string permission, ServerPermissionType type)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrEmpty(share.Permissions))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
var permissions = share.Permissions.Split(';', StringSplitOptions.RemoveEmptyEntries);
|
|
||||||
|
|
||||||
foreach (var sharePermission in permissions)
|
|
||||||
{
|
|
||||||
if (!sharePermission.StartsWith(permission))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
var typeParts = sharePermission.Split(':', StringSplitOptions.RemoveEmptyEntries);
|
|
||||||
|
|
||||||
// Missing permission type
|
|
||||||
if (typeParts.Length != 2)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
// Parse type id
|
|
||||||
if (!int.TryParse(typeParts[1], out var typeId))
|
|
||||||
return false; // Malformed
|
|
||||||
|
|
||||||
var requiredId = (int)type;
|
|
||||||
|
|
||||||
return typeId >= requiredId;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user