From afa993d76cbee0a2de06c9d40b05419cbd5e74ac Mon Sep 17 00:00:00 2001 From: Sergey Gut Date: Mon, 28 Sep 2026 02:02:05 +0400 Subject: [PATCH] feat: auth --- Dockerfile | 1 + docker-compose.yml | 3 + src/MemeVault.Api/Auth/JwtTokenService.cs | 36 +++++++ .../Auth/TelegramInitDataValidator.cs | 97 +++++++++++++++++++ .../Controllers/AuthController.cs | 25 +++++ src/MemeVault.Api/MemeVault.Api.csproj | 5 + src/MemeVault.Api/Options/JwtOptions.cs | 11 +++ src/MemeVault.Api/Options/TelegramOptions.cs | 9 ++ src/MemeVault.Api/Program.cs | 58 +++++++++-- src/MemeVault.Api/appsettings.json | 18 ++-- .../Telegram/Handlers/MessageHandler.cs | 4 +- 11 files changed, 250 insertions(+), 17 deletions(-) create mode 100644 src/MemeVault.Api/Auth/JwtTokenService.cs create mode 100644 src/MemeVault.Api/Auth/TelegramInitDataValidator.cs create mode 100644 src/MemeVault.Api/Controllers/AuthController.cs create mode 100644 src/MemeVault.Api/Options/JwtOptions.cs create mode 100644 src/MemeVault.Api/Options/TelegramOptions.cs diff --git a/Dockerfile b/Dockerfile index ec81756..417692e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -48,6 +48,7 @@ RUN --mount=type=cache,target=/root/.nuget/packages \ # ── Runtime ─────────────────────────────────────────────────────────────────── FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime +RUN apt-get update && apt-get install -y --no-install-recommends libgssapi-krb5-2 && rm -rf /var/lib/apt/lists/* WORKDIR /app COPY --from=build /app/api ./api COPY --from=build /app/bot ./bot diff --git a/docker-compose.yml b/docker-compose.yml index 60077e3..a0fc893 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -44,6 +44,9 @@ services: ASPNETCORE_URLS: http://+:8080 ConnectionStrings__Postgres: Host=postgres;Database=memevault;Username=memevault;Password=${POSTGRES_PASSWORD} ConnectionStrings__Redis: redis:6379 + Telegram__BotToken: ${TELEGRAM_BOT_TOKEN:?err} + Jwt__SecretKey: ${JWT_SECRET_KEY:?err} + Jwt__ExpiryHours: 24 bot: build: . diff --git a/src/MemeVault.Api/Auth/JwtTokenService.cs b/src/MemeVault.Api/Auth/JwtTokenService.cs new file mode 100644 index 0000000..f58bf01 --- /dev/null +++ b/src/MemeVault.Api/Auth/JwtTokenService.cs @@ -0,0 +1,36 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using MemeVault.Api.Options; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; + +namespace MemeVault.Api.Auth; + +public sealed class JwtTokenService(IOptions options) +{ + public string IssueToken(long telegramUserId, string? username) + { + var opt = options.Value; + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(opt.SecretKey)); + var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + + var claims = new List + { + new(JwtRegisteredClaimNames.Sub, telegramUserId.ToString()), + }; + + if (!string.IsNullOrEmpty(username)) + claims.Add(new Claim(JwtRegisteredClaimNames.Name, username)); + + var token = new JwtSecurityToken( + issuer: opt.Issuer, + audience: opt.Audience, + claims: claims, + notBefore: DateTime.UtcNow, + expires: DateTime.UtcNow.AddHours(opt.ExpiryHours), + signingCredentials: creds); + + return new JwtSecurityTokenHandler().WriteToken(token); + } +} diff --git a/src/MemeVault.Api/Auth/TelegramInitDataValidator.cs b/src/MemeVault.Api/Auth/TelegramInitDataValidator.cs new file mode 100644 index 0000000..aedf035 --- /dev/null +++ b/src/MemeVault.Api/Auth/TelegramInitDataValidator.cs @@ -0,0 +1,97 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using MemeVault.Api.Options; +using Microsoft.Extensions.Options; + +namespace MemeVault.Api.Auth; + +/// +/// Валидирует initData, которую Telegram передаёт в Mini App. +/// Алгоритм: https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app +/// +public sealed class TelegramInitDataValidator(IOptions options) +{ + // Максимальный возраст initData. Telegram рекомендует проверять свежесть. + private static readonly TimeSpan MaxAge = TimeSpan.FromSeconds(60); + + /// + /// Проверяет подпись initData и извлекает Telegram userId и username. + /// Возвращает false если подпись не верна или данные устарели. + /// + public bool TryValidate(string initData, out long userId, out string? username) + { + userId = 0; + username = null; + + var pairs = ParseQueryString(initData); + + if (!pairs.TryGetValue("hash", out var receivedHash)) + return false; + + // Строка для проверки: все поля кроме hash, отсортированные по ключу + var dataCheckString = string.Join('\n', + pairs + .Where(p => p.Key != "hash") + .OrderBy(p => p.Key) + .Select(p => $"{p.Key}={p.Value}")); + + // secret_key = HMAC-SHA256("WebAppData", botToken) + var secretKey = HMACSHA256.HashData( + Encoding.UTF8.GetBytes("WebAppData"), + Encoding.UTF8.GetBytes(options.Value.BotToken)); + + // expected_hash = HMAC-SHA256(secret_key, dataCheckString) + var expectedHash = HMACSHA256.HashData( + secretKey, + Encoding.UTF8.GetBytes(dataCheckString)); + + var expectedHex = Convert.ToHexString(expectedHash).ToLowerInvariant(); + + // Constant-time сравнение + if (!CryptographicOperations.FixedTimeEquals( + Encoding.UTF8.GetBytes(expectedHex), + Encoding.UTF8.GetBytes(receivedHash))) + return false; + + // Проверка свежести + if (!pairs.TryGetValue("auth_date", out var authDateStr) || + !long.TryParse(authDateStr, out var authDateUnix)) + return false; + + var authDate = DateTimeOffset.FromUnixTimeSeconds(authDateUnix); + if (DateTimeOffset.UtcNow - authDate > MaxAge) + return false; + + // Извлекаем user JSON + if (!pairs.TryGetValue("user", out var userJson)) + return false; + + using var doc = JsonDocument.Parse(userJson); + var root = doc.RootElement; + + if (!root.TryGetProperty("id", out var idProp)) + return false; + + userId = idProp.GetInt64(); + username = root.TryGetProperty("username", out var uProp) + ? uProp.GetString() + : null; + + return true; + } + + private static Dictionary ParseQueryString(string query) + { + var result = new Dictionary(StringComparer.Ordinal); + foreach (var part in query.Split('&')) + { + var eq = part.IndexOf('='); + if (eq <= 0) continue; + var key = Uri.UnescapeDataString(part[..eq]); + var val = Uri.UnescapeDataString(part[(eq + 1)..]); + result[key] = val; + } + return result; + } +} diff --git a/src/MemeVault.Api/Controllers/AuthController.cs b/src/MemeVault.Api/Controllers/AuthController.cs new file mode 100644 index 0000000..a21c16f --- /dev/null +++ b/src/MemeVault.Api/Controllers/AuthController.cs @@ -0,0 +1,25 @@ +using MemeVault.Api.Auth; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace MemeVault.Api.Controllers; + +[ApiController] +[Route("api/[controller]")] +public sealed class AuthController( + TelegramInitDataValidator validator, + JwtTokenService jwt) : ControllerBase +{ + [AllowAnonymous] + [HttpPost("telegram")] + public IActionResult Telegram([FromBody] TelegramAuthRequest request) + { + if (!validator.TryValidate(request.InitData, out var userId, out var username)) + return Unauthorized(); + + var token = jwt.IssueToken(userId, username); + return Ok(new { token }); + } +} + +public sealed record TelegramAuthRequest(string InitData); diff --git a/src/MemeVault.Api/MemeVault.Api.csproj b/src/MemeVault.Api/MemeVault.Api.csproj index 3d9dc11..a497713 100644 --- a/src/MemeVault.Api/MemeVault.Api.csproj +++ b/src/MemeVault.Api/MemeVault.Api.csproj @@ -23,4 +23,9 @@ + + + + + diff --git a/src/MemeVault.Api/Options/JwtOptions.cs b/src/MemeVault.Api/Options/JwtOptions.cs new file mode 100644 index 0000000..b23c853 --- /dev/null +++ b/src/MemeVault.Api/Options/JwtOptions.cs @@ -0,0 +1,11 @@ +namespace MemeVault.Api.Options; + +public sealed class JwtOptions +{ + public const string Section = "Jwt"; + + public string SecretKey { get; set; } = string.Empty; + public string Issuer { get; set; } = "memevault-api"; + public string Audience { get; set; } = "memevault-miniapp"; + public int ExpiryHours { get; set; } = 24; +} diff --git a/src/MemeVault.Api/Options/TelegramOptions.cs b/src/MemeVault.Api/Options/TelegramOptions.cs new file mode 100644 index 0000000..488dca3 --- /dev/null +++ b/src/MemeVault.Api/Options/TelegramOptions.cs @@ -0,0 +1,9 @@ +namespace MemeVault.Api.Options; + +public sealed class TelegramOptions +{ + public const string Section = "Telegram"; + + /// Bot token — нужен для валидации HMAC подписи initData. + public string BotToken { get; set; } = string.Empty; +} diff --git a/src/MemeVault.Api/Program.cs b/src/MemeVault.Api/Program.cs index 2592be3..3965a9b 100644 --- a/src/MemeVault.Api/Program.cs +++ b/src/MemeVault.Api/Program.cs @@ -1,28 +1,70 @@ -using Prometheus; +using MemeVault.Api.Auth; +using System.Text; +using MemeVault.Api.Options; using MemeVault.Infrastructure; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.IdentityModel.Tokens; +using Prometheus; var builder = WebApplication.CreateBuilder(args); -// ── Application ─────────────────────────────────────────────────────────────── -builder.Services.AddMediatR(cfg => - cfg.RegisterServicesFromAssembly( - typeof(MemeVault.Application.Commands.SaveMedia.SaveMediaCommand).Assembly)); - // ── Infrastructure (DB + Redis) ─────────────────────────────────────────────── builder.Services.AddInfrastructure(builder.Configuration); +// ── MediatR ─────────────────────────────────────────────────────────────────── +builder.Services.AddMediatR(cfg => + cfg.RegisterServicesFromAssembly( + typeof(MemeVault.Application.Commands.SaveMedia.SaveMediaCommand).Assembly)); + +// ── Telegram initData + JWT ─────────────────────────────────────────────────── +builder.Services.Configure( + builder.Configuration.GetSection(TelegramOptions.Section)); +builder.Services.Configure( + builder.Configuration.GetSection(JwtOptions.Section)); + +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + +var jwtOpts = builder.Configuration.GetSection(JwtOptions.Section).Get()!; + +builder.Services + .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(o => + { + o.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = jwtOpts.Issuer, + ValidAudience = jwtOpts.Audience, + IssuerSigningKey = new SymmetricSecurityKey( + Encoding.UTF8.GetBytes(jwtOpts.SecretKey)), + ClockSkew = TimeSpan.FromSeconds(30), + }; + }); + +builder.Services.AddAuthorization(); +builder.Services.AddControllers(); + +// ── OpenAPI ─────────────────────────────────────────────────────────────────── +builder.Services.AddEndpointsApiExplorer(); + var app = builder.Build(); app.UseHttpMetrics(); +app.UseAuthentication(); +app.UseAuthorization(); app.MapGet("/health", () => Results.Ok(new { status = "ok" })); - // TODO: /api/media GET — список медиа пользователя -// TODO: /api/media POST — загрузить новое медиа (файл или текст) +// TODO: /api/media/{id} PATCH — обновить caption / теги // TODO: /api/media/{id} DELETE // TODO: /api/tags GET — теги пользователя // TODO: /api/collections GET/POST — коллекции +app.MapControllers(); app.MapMetrics(); app.Run(); diff --git a/src/MemeVault.Api/appsettings.json b/src/MemeVault.Api/appsettings.json index b8ab0b5..81f9ad6 100644 --- a/src/MemeVault.Api/appsettings.json +++ b/src/MemeVault.Api/appsettings.json @@ -1,17 +1,21 @@ { - "Bot": { - "Token": "YOUR_BOT_TOKEN_HERE", - "WebhookHost": "https://your-domain.com" + "Telegram": { + "BotToken": "" + }, + "Jwt": { + "SecretKey": "", + "Issuer": "memevault-api", + "Audience": "memevault-miniapp", + "ExpiryHours": 24 }, "ConnectionStrings": { - "Postgres": "Host=db;Port=5432;Database=memevault;Username=memevault;Password=changeme" + "Postgres": "Host=localhost;Database=memevault;Username=memevault;Password=changeme", + "Redis": "localhost:6379" }, - "Redis": "redis:6379", "Logging": { "LogLevel": { "Default": "Information", - "Microsoft.AspNetCore": "Warning", - "Microsoft.EntityFrameworkCore.Database.Command": "Warning" + "Microsoft.AspNetCore": "Warning" } } } diff --git a/src/MemeVault.Bot/Telegram/Handlers/MessageHandler.cs b/src/MemeVault.Bot/Telegram/Handlers/MessageHandler.cs index 7f924ac..a5f4fdc 100644 --- a/src/MemeVault.Bot/Telegram/Handlers/MessageHandler.cs +++ b/src/MemeVault.Bot/Telegram/Handlers/MessageHandler.cs @@ -83,8 +83,8 @@ public sealed class MessageHandler var entry = new MediaGroupEntry( message.From.Id, message.Chat.Id, - source.Origin.ToString(), - source.Reference, + source.Origin?.ToString() ?? string.Empty, + source.Reference ?? string.Empty, mediaType.ToString(), message.Caption);