progmaweb
The site and account service of Progmasoft: a Next.js frontend and an ASP.NET Core API.
Clonegit clone https://git.progmasoft.com/progmaweb
Add Progmasoft OAuth, an OAuth 2.1 and OpenID Connect provider
- Commit
cffc8d884ce3620b70c80a9ab98b8f1f03887402- Author
- Leitwolf11 ·
- Parents
46e526f91e80
Changes
apps/api-tests/AccountApiFactory.cs | 53 ++- apps/api-tests/AccountStoreSelectionTests.cs | 10 + apps/api-tests/OAuthFlowTests.cs | 351 ++++++++++++++++ apps/api-tests/OAuthPolicyTests.cs | 262 ++++++++++++ apps/api-tests/OAuthTestClient.cs | 169 ++++++++ apps/api-tests/packages.lock.json | 439 +++++++++++++++++++- apps/api/Accounts/AccountService.cs | 40 +- apps/api/OAuth/Developers/ApplicationPolicy.cs | 149 +++++++ apps/api/OAuth/Developers/ApplicationRegistry.cs | 328 +++++++++++++++ apps/api/OAuth/Developers/DeveloperEndpoints.cs | 287 ++++++++++++++ apps/api/OAuth/Endpoints/AuthorizationEndpoints.cs | 290 ++++++++++++++ apps/api/OAuth/OAuthEndpoints.cs | 22 ++ apps/api/OAuth/OAuthHostFilter.cs | 54 +++ apps/api/OAuth/OAuthOptions.cs | 35 ++ apps/api/OAuth/OAuthRegistration.cs | 253 ++++++++++++ apps/api/OAuth/OAuthScopes.cs | 61 +++ .../OAuth/Pages/AllowedApplicationsEndpoints.cs | 93 +++++ apps/api/OAuth/Pages/HtmlPage.cs | 95 +++++ apps/api/OAuth/Pages/SignInEndpoints.cs | 162 ++++++++ apps/api/OAuth/Storage/OAuthDbContext.cs | 52 +++ apps/api/OAuth/Storage/OAuthSchema.cs | 204 ++++++++++ apps/api/Progmaweb.Api.csproj | 4 + apps/api/Program.cs | 21 + apps/api/appsettings.Development.json | 2 +- apps/api/appsettings.json | 2 +- apps/api/packages.lock.json | 440 +++++++++++++++++++++ docs/OAUTH.md | 99 +++++ docs/README.md | 1 + ops/README.md | 31 ++ ops/nginx/progmaweb.conf | 48 +++ 30 files changed, 4042 insertions(+), 15 deletions(-) diff --git a/apps/api-tests/AccountApiFactory.cs b/apps/api-tests/AccountApiFactory.cs index 4692f0c..926de65 100644 --- a/apps/api-tests/AccountApiFactory.cs +++ b/apps/api-tests/AccountApiFactory.cs @@ -16,12 +16,19 @@ namespace Progmasoft.Progmaweb.Api.Tests; /// </param> /// <param name="environment">Name of the hosting environment.</param> /// <param name="accountStore">Value of <c>Accounts:Store</c>; <see langword="null"/> leaves it unset.</param> +/// <param name="oauthKeys"> +/// Whether to give Progmasoft OAuth key files. Production refuses to start without them; other environments make +/// their own keys. +/// </param> internal sealed class AccountApiFactory( bool configureGoogle = true, string? accountDatabase = null, string environment = "Testing", - string? accountStore = null) : WebApplicationFactory<Program> + string? accountStore = null, + bool oauthKeys = true) : WebApplicationFactory<Program> { + private readonly string keyDirectory = Path.Combine(Path.GetTempPath(), "progmaweb-oauth-keys-" + Guid.NewGuid().ToString("N")); + protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment(environment); @@ -39,6 +46,29 @@ internal sealed class AccountApiFactory( configureGoogle ? "test-client.apps.googleusercontent.com" : string.Empty); builder.UseSetting("Authentication:Google:ClientSecret", configureGoogle ? "test-secret" : string.Empty); + // Progmasoft OAuth reads its host while services are registered, like the Google client above. Its own host + // keeps the host filter honest: the account API answers on localhost, OAuth on oauth.localhost. + builder.UseSetting("OAuth:Host", OAuthHost); + builder.UseSetting("AllowedHosts", + $"localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com;{OAuthHost}"); + if (oauthKeys && environment == "Production") + { + Directory.CreateDirectory(keyDirectory); + using System.Security.Cryptography.RSA signing = System.Security.Cryptography.RSA.Create(2048); + string signingPath = Path.Combine(keyDirectory, "signing.pem"); + string encryptionPath = Path.Combine(keyDirectory, "encryption.key"); + File.WriteAllText(signingPath, signing.ExportPkcs8PrivateKeyPem()); + File.WriteAllText(encryptionPath, + Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32))); + builder.UseSetting("OAuth:SigningKeyPath", signingPath); + builder.UseSetting("OAuth:EncryptionKeyPath", encryptionPath); + } + else + { + builder.UseSetting("OAuth:SigningKeyPath", string.Empty); + builder.UseSetting("OAuth:EncryptionKeyPath", string.Empty); + } + builder.ConfigureAppConfiguration((_, configuration) => { configuration.AddInMemoryCollection(new Dictionary<string, string?> @@ -49,6 +79,27 @@ internal sealed class AccountApiFactory( }); } + /// <summary>The host Progmasoft OAuth answers on in the tests.</summary> + public const string OAuthHost = "oauth.localhost"; + + /// <summary>A client of the OAuth host that keeps its cookies and does not follow redirections.</summary> + public HttpClient CreateOAuthClient() => CreateClient( + new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + BaseAddress = new Uri($"https://{OAuthHost}"), + HandleCookies = true + }); + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (Directory.Exists(keyDirectory)) + { + Directory.Delete(keyDirectory, recursive: true); + } + } + public HttpClient CreateAccountClient(bool handleCookies = true) => CreateClient( new WebApplicationFactoryClientOptions { diff --git a/apps/api-tests/AccountStoreSelectionTests.cs b/apps/api-tests/AccountStoreSelectionTests.cs index e9724c0..05ed31b 100644 --- a/apps/api-tests/AccountStoreSelectionTests.cs +++ b/apps/api-tests/AccountStoreSelectionTests.cs @@ -72,6 +72,16 @@ public sealed class AccountStoreSelectionTests Assert.Contains("No account database is configured", refused.Message, StringComparison.Ordinal); } + [Fact] + public void AProductionServiceWithoutOAuthKeysDoesNotStart() + { + using AccountApiFactory factory = new(environment: "Production", accountStore: "Memory", oauthKeys: false); + + InvalidOperationException refused = Assert.Throws<InvalidOperationException>(() => factory.CreateAccountClient()); + + Assert.Contains("must name the token key files in production", refused.Message, StringComparison.Ordinal); + } + [Fact] public async Task AProductionServiceThatAsksForMemoryStartsAndKeepsAccountsInMemory() { diff --git a/apps/api-tests/OAuthFlowTests.cs b/apps/api-tests/OAuthFlowTests.cs new file mode 100644 index 0000000..dcd94de --- /dev/null +++ b/apps/api-tests/OAuthFlowTests.cs @@ -0,0 +1,351 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; + +namespace Progmasoft.Progmaweb.Api.Tests; + +public sealed class OAuthFlowTests +{ + private static CancellationToken Cancel => TestContext.Current.CancellationToken; + + [Fact] + public async Task AuthorizationCodeWithPkceIssuesTokensThatCarryOnlyTheGrantedClaims() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder1", "holder@example.com"); + (string clientId, string? secret) = await browser.RegisterApplicationAsync(); + (string verifier, string challenge) = OAuthTestClient.Pkce(); + + Uri redirect = await browser.AuthorizeAsync(clientId, "openid profile email offline_access viget.packages.read", + challenge); + Assert.StartsWith(OAuthTestClient.RedirectUri, redirect.ToString(), StringComparison.Ordinal); + Assert.Equal("state-123", OAuthTestClient.Query(redirect, "state")); + string code = OAuthTestClient.Query(redirect, "code")!; + + (HttpStatusCode status, JsonElement tokens) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "authorization_code", + ["code"] = code, + ["redirect_uri"] = OAuthTestClient.RedirectUri, + ["code_verifier"] = verifier, + ["client_id"] = clientId, + ["client_secret"] = secret! + }); + Assert.True(status == HttpStatusCode.OK, tokens.ToString()); + + JsonElement identity = OAuthTestClient.Payload(tokens.GetProperty("id_token").GetString()!); + Assert.Equal($"https://{AccountApiFactory.OAuthHost}/", identity.GetProperty("iss").GetString()); + Assert.Equal(clientId, identity.GetProperty("aud").GetString()); + Assert.Equal("OAuthHolder1", identity.GetProperty("preferred_username").GetString()); + Assert.Equal("holder@example.com", identity.GetProperty("email").GetString()); + Assert.False(identity.GetProperty("email_verified").GetBoolean()); + Assert.Equal("nonce-456", identity.GetProperty("nonce").GetString()); + + using HttpClient client = factory.CreateOAuthClient(); + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", tokens.GetProperty("access_token").GetString()); + JsonElement user = await client.GetFromJsonAsync<JsonElement>("/connect/userinfo", Cancel); + Assert.Equal(identity.GetProperty("sub").GetString(), user.GetProperty("sub").GetString()); + Assert.Equal("OAuthHolder1", user.GetProperty("name").GetString()); + Assert.Equal("holder@example.com", user.GetProperty("email").GetString()); + + // The code is single use. + (HttpStatusCode reused, _) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "authorization_code", + ["code"] = code, + ["redirect_uri"] = OAuthTestClient.RedirectUri, + ["code_verifier"] = verifier, + ["client_id"] = clientId, + ["client_secret"] = secret! + }); + Assert.Equal(HttpStatusCode.BadRequest, reused); + } + + [Fact] + public async Task ScopesThatWereNotGrantedAreNotInTheTokens() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder2", "holder2@example.com"); + (string clientId, string? secret) = await browser.RegisterApplicationAsync(); + (string verifier, string challenge) = OAuthTestClient.Pkce(); + + Uri redirect = await browser.AuthorizeAsync(clientId, "openid", challenge); + (_, JsonElement tokens) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "authorization_code", + ["code"] = OAuthTestClient.Query(redirect, "code")!, + ["redirect_uri"] = OAuthTestClient.RedirectUri, + ["code_verifier"] = verifier, + ["client_id"] = clientId, + ["client_secret"] = secret! + }); + JsonElement identity = OAuthTestClient.Payload(tokens.GetProperty("id_token").GetString()!); + Assert.False(identity.TryGetProperty("email", out _)); + Assert.False(identity.TryGetProperty("preferred_username", out _)); + Assert.False(tokens.TryGetProperty("refresh_token", out _)); + } + + [Fact] + public async Task RefreshTokensRotateAndAReusedOneIsRefused() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder3", "holder3@example.com"); + (string clientId, string? secret) = await browser.RegisterApplicationAsync(); + (string verifier, string challenge) = OAuthTestClient.Pkce(); + Uri redirect = await browser.AuthorizeAsync(clientId, "openid offline_access", challenge); + (_, JsonElement first) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "authorization_code", + ["code"] = OAuthTestClient.Query(redirect, "code")!, + ["redirect_uri"] = OAuthTestClient.RedirectUri, + ["code_verifier"] = verifier, + ["client_id"] = clientId, + ["client_secret"] = secret! + }); + string refresh = first.GetProperty("refresh_token").GetString()!; + + Dictionary<string, string> refreshRequest = new() + { + ["grant_type"] = "refresh_token", + ["refresh_token"] = refresh, + ["client_id"] = clientId, + ["client_secret"] = secret! + }; + (HttpStatusCode renewed, JsonElement second) = await browser.TokenAsync(refreshRequest); + Assert.Equal(HttpStatusCode.OK, renewed); + Assert.NotEqual(refresh, second.GetProperty("refresh_token").GetString()); + + (HttpStatusCode reused, JsonElement error) = await browser.TokenAsync(refreshRequest); + Assert.Equal(HttpStatusCode.BadRequest, reused); + Assert.Equal("invalid_grant", error.GetProperty("error").GetString()); + } + + [Fact] + public async Task AnAllowedApplicationSkipsTheConsentAndWithdrawingEndsItsTokens() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder4", "holder4@example.com"); + (string clientId, string? secret) = await browser.RegisterApplicationAsync(); + (string verifier, string challenge) = OAuthTestClient.Pkce(); + Uri redirect = await browser.AuthorizeAsync(clientId, "openid offline_access", challenge); + (_, JsonElement tokens) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "authorization_code", + ["code"] = OAuthTestClient.Query(redirect, "code")!, + ["redirect_uri"] = OAuthTestClient.RedirectUri, + ["code_verifier"] = verifier, + ["client_id"] = clientId, + ["client_secret"] = secret! + }); + + HttpResponseMessage again = await browser.Browser.GetAsync( + OAuthTestClient.AuthorizePath(clientId, "openid offline_access", OAuthTestClient.Pkce().Challenge), Cancel); + Assert.Equal(HttpStatusCode.Redirect, again.StatusCode); + Assert.NotNull(OAuthTestClient.Query(again.Headers.Location!, "code")); + + string allowed = await browser.Browser.GetStringAsync("/account/applications", Cancel); + Assert.Contains("Example Client", allowed, StringComparison.Ordinal); + string action = System.Text.RegularExpressions.Regex.Match(allowed, + "action=\"(/account/applications/[^\"]+/revoke)\"").Groups[1].Value; + HttpResponseMessage withdrawn = await browser.SubmitAsync("/account/applications", action, []); + Assert.Equal(HttpStatusCode.Redirect, withdrawn.StatusCode); + + (HttpStatusCode refreshed, _) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "refresh_token", + ["refresh_token"] = tokens.GetProperty("refresh_token").GetString()!, + ["client_id"] = clientId, + ["client_secret"] = secret! + }); + Assert.Equal(HttpStatusCode.BadRequest, refreshed); + } + + [Fact] + public async Task DenyingTheConsentReturnsAccessDenied() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder5", "holder5@example.com"); + (string clientId, _) = await browser.RegisterApplicationAsync(); + + Uri redirect = await browser.AuthorizeAsync(clientId, "openid email", OAuthTestClient.Pkce().Challenge, "deny"); + Assert.Equal("access_denied", OAuthTestClient.Query(redirect, "error")); + Assert.Null(OAuthTestClient.Query(redirect, "code")); + } + + [Fact] + public async Task TheConsentPageListsEachRequestedGrant() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder6", "holder6@example.com"); + (string clientId, _) = await browser.RegisterApplicationAsync( + "profile email viget.packages.read viget.packages.publish viget.packages.yank"); + + HttpResponseMessage page = await browser.Browser.GetAsync(OAuthTestClient.AuthorizePath(clientId, + "openid profile email viget.packages.read viget.packages.publish viget.packages.yank", + OAuthTestClient.Pkce().Challenge), Cancel); + string html = await page.Content.ReadAsStringAsync(Cancel); + Assert.Contains("Read your Progmasoft account name.", html, StringComparison.Ordinal); + Assert.Contains("Read the email address you sign in and registered with.", html, StringComparison.Ordinal); + Assert.Contains("Read the packages you have published on ViGet.", html, StringComparison.Ordinal); + Assert.Contains("Publish packages to ViGet under your account.", html, StringComparison.Ordinal); + Assert.Contains("Yank packages you have published on ViGet.", html, StringComparison.Ordinal); + Assert.Contains("registered by <strong>OAuthHolder6</strong>", html, StringComparison.Ordinal); + } + + [Fact] + public async Task ViGetScopesGiveAccessTokensForViGet() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder7", "holder7@example.com"); + (string clientId, string? secret) = await browser.RegisterApplicationAsync("viget.packages.publish"); + (string verifier, string challenge) = OAuthTestClient.Pkce(); + Uri redirect = await browser.AuthorizeAsync(clientId, "openid viget.packages.publish", challenge); + (HttpStatusCode status, JsonElement tokens) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "authorization_code", + ["code"] = OAuthTestClient.Query(redirect, "code")!, + ["redirect_uri"] = OAuthTestClient.RedirectUri, + ["code_verifier"] = verifier, + ["client_id"] = clientId, + ["client_secret"] = secret! + }); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal("openid viget.packages.publish", tokens.GetProperty("scope").GetString()); + + // The access token is encrypted for the resource servers; introspection shows its audience. + using HttpClient client = factory.CreateOAuthClient(); + HttpResponseMessage response = await client.PostAsync("/connect/introspect", new FormUrlEncodedContent( + new Dictionary<string, string> + { + ["token"] = tokens.GetProperty("access_token").GetString()!, + ["client_id"] = clientId, + ["client_secret"] = secret! + }), Cancel); + JsonElement introspection = await response.Content.ReadFromJsonAsync<JsonElement>(Cancel); + Assert.True(introspection.GetProperty("active").GetBoolean(), introspection.ToString()); + Assert.Contains("viget", introspection.GetProperty("aud").ToString(), StringComparison.Ordinal); + } + + [Fact] + public async Task APublicClientUsesPkceWithoutASecret() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder8", "holder8@example.com"); + (string clientId, string? secret) = await browser.RegisterApplicationAsync("profile", isPublic: true, + redirectUris: "com.example.app:/callback"); + Assert.Null(secret); + (string verifier, string challenge) = OAuthTestClient.Pkce(); + + HttpResponseMessage page = await browser.Browser.GetAsync(OAuthTestClient.AuthorizePath(clientId, + "openid profile", challenge, "com.example.app:/callback"), Cancel); + string html = await page.Content.ReadAsStringAsync(Cancel); + List<KeyValuePair<string, string>> fields = OAuthTestClient.HiddenFields(html); + fields.Add(new("decision", "allow")); + HttpResponseMessage decided = await browser.Browser.PostAsync("/connect/authorize", + new FormUrlEncodedContent(fields), Cancel); + Uri redirect = decided.Headers.Location!; + Assert.Equal("com.example.app", redirect.Scheme); + + (HttpStatusCode status, _) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "authorization_code", + ["code"] = OAuthTestClient.Query(redirect, "code")!, + ["redirect_uri"] = "com.example.app:/callback", + ["code_verifier"] = verifier, + ["client_id"] = clientId + }); + Assert.Equal(HttpStatusCode.OK, status); + } + + [Fact] + public async Task OnPostgreSqlTheTablesAreCreatedAndAReusedRefreshTokenRevokesItsChain() + { + await using PostgresTestDatabase database = await PostgresTestDatabase.CreateAsync(); + await using AccountApiFactory factory = new(accountDatabase: database.ConnectionString); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("PostgresHolder1", "postgres1@example.com"); + (string clientId, string? secret) = await browser.RegisterApplicationAsync(); + (string verifier, string challenge) = OAuthTestClient.Pkce(); + Uri redirect = await browser.AuthorizeAsync(clientId, "openid profile offline_access", challenge); + (_, JsonElement first) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "authorization_code", + ["code"] = OAuthTestClient.Query(redirect, "code")!, + ["redirect_uri"] = OAuthTestClient.RedirectUri, + ["code_verifier"] = verifier, + ["client_id"] = clientId, + ["client_secret"] = secret! + }); + Dictionary<string, string> Refresh(string token) => new() + { + ["grant_type"] = "refresh_token", + ["refresh_token"] = token, + ["client_id"] = clientId, + ["client_secret"] = secret! + }; + + (HttpStatusCode renewed, JsonElement second) = + await browser.TokenAsync(Refresh(first.GetProperty("refresh_token").GetString()!)); + Assert.Equal(HttpStatusCode.OK, renewed); + + // Reusing the first refresh token is taken for theft: the token issued from it stops working as well. + (HttpStatusCode reused, _) = await browser.TokenAsync(Refresh(first.GetProperty("refresh_token").GetString()!)); + (HttpStatusCode chained, _) = await browser.TokenAsync(Refresh(second.GetProperty("refresh_token").GetString()!)); + Assert.Equal(HttpStatusCode.BadRequest, reused); + Assert.Equal(HttpStatusCode.BadRequest, chained); + + await using Npgsql.NpgsqlDataSource dataSource = database.OpenDataSource(); + await using Npgsql.NpgsqlCommand version = + dataSource.CreateCommand("SELECT max(version) FROM oauth_schema_versions"); + Assert.Equal(Progmasoft.OAuth.Storage.OAuthSchema.CurrentVersion, + (int)(await version.ExecuteScalarAsync(Cancel))!); + } + + [Fact] + public async Task ClientCredentialsActAsTheApplicationAndTakeNoAccountScope() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder9", "holder9@example.com"); + (string clientId, string? secret) = await browser.RegisterApplicationAsync("profile", clientCredentials: true); + + (HttpStatusCode status, JsonElement token) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "client_credentials", + ["client_id"] = clientId, + ["client_secret"] = secret! + }); + Assert.True(status == HttpStatusCode.OK, token.ToString()); + + (HttpStatusCode scoped, JsonElement error) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "client_credentials", + ["client_id"] = clientId, + ["client_secret"] = secret!, + ["scope"] = "profile" + }); + Assert.Equal(HttpStatusCode.BadRequest, scoped); + Assert.Equal("invalid_scope", error.GetProperty("error").GetString()); + + (HttpStatusCode wrongSecret, _) = await browser.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "client_credentials", + ["client_id"] = clientId, + ["client_secret"] = "not-the-secret" + }); + Assert.Equal(HttpStatusCode.Unauthorized, wrongSecret); + } +} diff --git a/apps/api-tests/OAuthPolicyTests.cs b/apps/api-tests/OAuthPolicyTests.cs new file mode 100644 index 0000000..1f84c77 --- /dev/null +++ b/apps/api-tests/OAuthPolicyTests.cs @@ -0,0 +1,262 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Net; +using System.Net.Http.Json; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Progmasoft.OAuth.Developers; +using Progmasoft.OAuth.Pages; +using Progmasoft.OAuth.Storage; + +namespace Progmasoft.Progmaweb.Api.Tests; + +public sealed class OAuthPolicyTests +{ + private static CancellationToken Cancel => TestContext.Current.CancellationToken; + + [Theory] + [InlineData("https://client.example/callback", false, true)] + [InlineData("http://127.0.0.1:8400/callback", false, true)] + [InlineData("http://[::1]:8400/callback", false, true)] + [InlineData("http://localhost:3000/callback", false, true)] + [InlineData("http://client.example/callback", false, false)] + [InlineData("https://client.example/callback#fragment", false, false)] + [InlineData("https://user:password@client.example/callback", false, false)] + [InlineData("https://*.client.example/callback", false, false)] + [InlineData("com.example.app:/callback", true, true)] + [InlineData("com.example.app:/callback", false, false)] + [InlineData("javascript:alert(1)", true, false)] + [InlineData("data:text/html,x", true, false)] + [InlineData("myapp:/callback", true, false)] + [InlineData("/relative/callback", false, false)] + public void RedirectionAddressesFollowRfc8252(string address, bool isPublic, bool accepted) => + Assert.Equal(accepted, ApplicationPolicy.IsRedirectionAddress(address, isPublic)); + + [Fact] + public void ARegistrationIsCheckedFieldByField() + { + Dictionary<string, string> errors = ApplicationPolicy.Validate(new ApplicationInput( + "x", "http://plain.example", true, [], [], ["profile", "not-a-scope"], true)); + Assert.Equal(["allowClientCredentials", "displayName", "homepage", "redirectUris", "scopes"], + errors.Keys.Order(StringComparer.Ordinal)); + Assert.Empty(ApplicationPolicy.Validate(new ApplicationInput( + "Example", string.Empty, false, ["https://client.example/callback"], [], ["profile"], true))); + } + + [Fact] + public async Task TheDiscoveryDocumentOffersOnlyOAuth21Flows() + { + await using AccountApiFactory factory = new(); + using HttpClient client = factory.CreateOAuthClient(); + JsonElement document = await client.GetFromJsonAsync<JsonElement>("/.well-known/openid-configuration", Cancel); + + Assert.Equal($"https://{AccountApiFactory.OAuthHost}/", document.GetProperty("issuer").GetString()); + string grants = document.GetProperty("grant_types_supported").ToString(); + Assert.Contains("authorization_code", grants, StringComparison.Ordinal); + Assert.Contains("refresh_token", grants, StringComparison.Ordinal); + Assert.DoesNotContain("implicit", grants, StringComparison.Ordinal); + Assert.DoesNotContain("password", grants, StringComparison.Ordinal); + Assert.Equal(["code"], document.GetProperty("response_types_supported").EnumerateArray() + .Select(value => value.GetString())); + Assert.Equal(["S256"], document.GetProperty("code_challenge_methods_supported").EnumerateArray() + .Select(value => value.GetString())); + string scopes = document.GetProperty("scopes_supported").ToString(); + foreach (string scope in new[] + { + "openid", "profile", "email", "offline_access", "viget.packages.read", "viget.packages.publish", + "viget.packages.yank" + }) + { + Assert.Contains($"\"{scope}\"", scopes, StringComparison.Ordinal); + } + } + + [Fact] + public async Task OAuthAnswersOnlyOnItsHostAndTheAccountApiNotThere() + { + await using AccountApiFactory factory = new(); + using HttpClient accounts = factory.CreateAccountClient(); + using HttpClient oauth = factory.CreateOAuthClient(); + + Assert.Equal(HttpStatusCode.NotFound, + (await accounts.GetAsync("/.well-known/openid-configuration", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await accounts.GetAsync("/signin", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await accounts.PostAsync("/connect/token", null, Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await oauth.GetAsync("/api/v1/status", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.OK, (await oauth.GetAsync("/health", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.OK, (await accounts.GetAsync("/api/v1/status", Cancel)).StatusCode); + } + + [Fact] + public async Task AuthorizationRequestsWithoutPkceOrWithAnotherFlowAreRefused() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("PolicyHolder1", "policy1@example.com"); + (string clientId, _) = await browser.RegisterApplicationAsync("profile"); + + // OpenIddict refuses some requests before it trusts the redirection address; those are answered here with + // 400 instead of being sent back to the client. Either way, no code is issued. + static async Task AssertRefusedAsync(HttpResponseMessage response, string error) + { + string answer = response.Headers.Location?.ToString() + ?? await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + Assert.True(response.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found + or HttpStatusCode.BadRequest, answer); + Assert.DoesNotContain("code=", answer, StringComparison.Ordinal); + if (response.Headers.Location is { } location) + { + Assert.Equal(error, OAuthTestClient.Query(location, "error")); + } + } + + await AssertRefusedAsync(await browser.Browser.GetAsync( + OAuthTestClient.AuthorizePath(clientId, "openid", null), Cancel), "invalid_request"); + await AssertRefusedAsync(await browser.Browser.GetAsync(OAuthTestClient.AuthorizePath(clientId, + "openid", OAuthTestClient.Pkce().Challenge, responseType: "token"), Cancel), "unsupported_response_type"); + await AssertRefusedAsync(await browser.Browser.GetAsync(OAuthTestClient.AuthorizePath(clientId, + "openid viget.packages.publish", OAuthTestClient.Pkce().Challenge), Cancel), "invalid_scope"); + + // An address that was not registered never receives a redirection. + HttpResponseMessage unknownAddress = await browser.Browser.GetAsync(OAuthTestClient.AuthorizePath(clientId, + "openid", OAuthTestClient.Pkce().Challenge, "https://attacker.example/callback"), Cancel); + Assert.Equal(HttpStatusCode.BadRequest, unknownAddress.StatusCode); + Assert.Null(unknownAddress.Headers.Location); + } + + [Fact] + public async Task AnAccountThatIsNotSignedInIsSentToTheSignInPageAndBack() + { + await using AccountApiFactory factory = new(); + OAuthTestClient developer = new(factory); + await developer.RegisterAndSignInAsync("PolicyHolder2", "policy2@example.com"); + (string clientId, _) = await developer.RegisterApplicationAsync("profile"); + + using HttpClient anonymous = factory.CreateOAuthClient(); + string path = OAuthTestClient.AuthorizePath(clientId, "openid", OAuthTestClient.Pkce().Challenge, prompt: "login"); + HttpResponseMessage response = await anonymous.GetAsync(path, Cancel); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + string location = response.Headers.Location!.ToString(); + Assert.Contains("/signin?ReturnUrl=", location, StringComparison.Ordinal); + Assert.Contains("connect%2Fauthorize", location, StringComparison.Ordinal); + Assert.DoesNotContain("prompt", Uri.UnescapeDataString(location), StringComparison.Ordinal); + + HttpResponseMessage none = await anonymous.GetAsync(OAuthTestClient.AuthorizePath(clientId, "openid", + OAuthTestClient.Pkce().Challenge, prompt: "none"), Cancel); + Assert.Equal("login_required", OAuthTestClient.Query(none.Headers.Location!, "error")); + } + + [Fact] + public async Task TheSignInPageGivesOneMessageForEveryFailureAndKeepsReturnAddressesLocal() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + HttpResponseMessage failed = await browser.SubmitAsync("/signin", "/signin", new Dictionary<string, string> + { + ["email"] = "nobody@example.com", + ["password"] = "wrong password here", + ["returnUrl"] = "https://attacker.example/" + }); + Assert.Equal(HttpStatusCode.Unauthorized, failed.StatusCode); + string html = await failed.Content.ReadAsStringAsync(Cancel); + Assert.Contains("The email address or the password is not right.", html, StringComparison.Ordinal); + Assert.Contains("name=\"returnUrl\" value=\"/\"", html, StringComparison.Ordinal); + + HttpResponseMessage forged = await browser.Browser.PostAsync("/signin", new FormUrlEncodedContent( + new Dictionary<string, string> { ["email"] = "a@example.com", ["password"] = "x" }), Cancel); + Assert.Equal(HttpStatusCode.BadRequest, forged.StatusCode); + + Assert.Equal("/", OAuthAccount.LocalReturnUrl("//attacker.example")); + Assert.Equal("/", OAuthAccount.LocalReturnUrl("/\\attacker.example")); + Assert.Equal("/developers", OAuthAccount.LocalReturnUrl("/developers")); + } + + [Fact] + public async Task ThePortalRefusesBadAddressesAndHidesOtherAccountsApplications() + { + await using AccountApiFactory factory = new(); + OAuthTestClient owner = new(factory); + await owner.RegisterAndSignInAsync("PolicyOwner1", "owner1@example.com"); + (string clientId, _) = await owner.RegisterApplicationAsync("profile"); + + HttpResponseMessage refused = await owner.SubmitAsync("/developers/new", "/developers/new", + new Dictionary<string, string> + { + ["displayName"] = "Plain HTTP", + ["clientType"] = "confidential", + ["redirectUris"] = "http://plain.example/callback" + }); + Assert.Equal(HttpStatusCode.BadRequest, refused.StatusCode); + Assert.Contains("cannot be registered", await refused.Content.ReadAsStringAsync(Cancel), + StringComparison.Ordinal); + + OAuthTestClient stranger = new(factory); + await stranger.RegisterAndSignInAsync("PolicyStranger1", "stranger1@example.com"); + Assert.Equal(HttpStatusCode.NotFound, + (await stranger.Browser.GetAsync($"/developers/{clientId}", Cancel)).StatusCode); + HttpResponseMessage deleted = await stranger.SubmitAsync("/", $"/developers/{clientId}/delete", []); + Assert.Equal(HttpStatusCode.NotFound, deleted.StatusCode); + Assert.Equal(HttpStatusCode.OK, (await owner.Browser.GetAsync($"/developers/{clientId}", Cancel)).StatusCode); + + HttpResponseMessage ownDelete = await owner.SubmitAsync($"/developers/{clientId}", + $"/developers/{clientId}/delete", []); + Assert.Equal(HttpStatusCode.Redirect, ownDelete.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, + (await owner.Browser.GetAsync($"/developers/{clientId}", Cancel)).StatusCode); + } + + [Fact] + public async Task RotatingTheSecretRetiresTheOldOne() + { + await using AccountApiFactory factory = new(); + OAuthTestClient owner = new(factory); + await owner.RegisterAndSignInAsync("PolicyOwner2", "owner2@example.com"); + (string clientId, string? secret) = await owner.RegisterApplicationAsync("profile", clientCredentials: true); + + HttpResponseMessage rotated = await owner.SubmitAsync($"/developers/{clientId}", + $"/developers/{clientId}/secret", []); + string html = await rotated.Content.ReadAsStringAsync(Cancel); + string newSecret = System.Web.HttpUtility.HtmlDecode( + System.Text.RegularExpressions.Regex.Matches(html, "<code>([^<]*)</code>")[1].Groups[1].Value); + Assert.NotEqual(secret, newSecret); + + (HttpStatusCode old, _) = await owner.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "client_credentials", ["client_id"] = clientId, ["client_secret"] = secret! + }); + (HttpStatusCode current, _) = await owner.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "client_credentials", ["client_id"] = clientId, ["client_secret"] = newSecret + }); + Assert.Equal(HttpStatusCode.Unauthorized, old); + Assert.Equal(HttpStatusCode.OK, current); + } + + [Fact] + public async Task PagesAllowTheirStylesheetByDigestAndNoScript() + { + await using AccountApiFactory factory = new(); + using HttpClient client = factory.CreateOAuthClient(); + HttpResponseMessage response = await client.GetAsync("/signin", Cancel); + string policy = string.Join(";", response.Headers.GetValues("Content-Security-Policy")); + string digest = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(HtmlPage.Stylesheet))); + Assert.Contains($"style-src 'sha256-{digest}'", policy, StringComparison.Ordinal); + Assert.Contains("default-src 'none'", policy, StringComparison.Ordinal); + Assert.Contains("frame-ancestors 'none'", policy, StringComparison.Ordinal); + Assert.DoesNotContain("script-src", policy, StringComparison.Ordinal); + } + + [Fact] + public void TheSchemaStepIsWhatEntityFrameworkGeneratesForTheModel() + { + DbContextOptions<OAuthDbContext> options = new DbContextOptionsBuilder<OAuthDbContext>() + .UseNpgsql("Host=unused").UseOpenIddict().Options; + using OAuthDbContext context = new(options); + static string Normalize(string sql) => string.Join('\n', sql.Replace("\r\n", "\n").Split('\n') + .Select(line => line.Trim()).Where(line => line.Length != 0)); + Assert.Equal(Normalize(context.Database.GenerateCreateScript()), Normalize(OAuthSchema.ModelScript)); + } +} diff --git a/apps/api-tests/OAuthTestClient.cs b/apps/api-tests/OAuthTestClient.cs new file mode 100644 index 0000000..5453027 --- /dev/null +++ b/apps/api-tests/OAuthTestClient.cs @@ -0,0 +1,169 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Net; +using System.Net.Http.Json; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Web; + +namespace Progmasoft.Progmaweb.Api.Tests; + +/// <summary>An account holder in a browser on the OAuth host, and a developer's client application.</summary> +/// <remarks>The pages are plain HTML forms; this fills them the way a browser would.</remarks> +internal sealed partial class OAuthTestClient(AccountApiFactory factory) +{ + public const string RedirectUri = "https://client.example/callback"; + + public HttpClient Browser { get; } = factory.CreateOAuthClient(); + + private static CancellationToken Cancel => TestContext.Current.CancellationToken; + + /// <summary>Creates an account through the account API and signs it in to the OAuth host.</summary> + public async Task<string> RegisterAndSignInAsync(string accountName, string email) + { + using HttpClient accounts = factory.CreateAccountClient(handleCookies: false); + HttpResponseMessage registered = await accounts.PostAsJsonAsync("/api/v1/accounts/register", + new { accountName, email, password = "correct horse battery staple" }, Cancel); + Assert.Equal(HttpStatusCode.Created, registered.StatusCode); + + HttpResponseMessage signedIn = await SubmitAsync("/signin", "/signin", new Dictionary<string, string> + { + ["email"] = email, + ["password"] = "correct horse battery staple", + ["returnUrl"] = "/" + }); + Assert.Equal(HttpStatusCode.Redirect, signedIn.StatusCode); + return accountName; + } + + /// <summary>Registers an application in the developer portal and returns its identifier and secret.</summary> + public async Task<(string ClientId, string? Secret)> RegisterApplicationAsync( + string scopes = "profile email offline_access viget.packages.read", + bool isPublic = false, + bool clientCredentials = false, + string redirectUris = RedirectUri) + { + List<KeyValuePair<string, string>> fields = + [ + new("displayName", "Example Client"), + new("homepage", "https://client.example"), + new("clientType", isPublic ? "public" : "confidential"), + new("redirectUris", redirectUris), + new("postLogoutRedirectUris", "https://client.example/signed-out") + ]; + fields.AddRange(scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries) + .Select(scope => new KeyValuePair<string, string>("scope", scope))); + if (clientCredentials) + { + fields.Add(new("allowClientCredentials", "on")); + } + + HttpResponseMessage response = await SubmitAsync("/developers/new", "/developers/new", fields); + string html = await response.Content.ReadAsStringAsync(Cancel); + Assert.True(response.StatusCode == HttpStatusCode.OK, html); + MatchCollection codes = CodePattern().Matches(html); + string clientId = codes[0].Groups[1].Value; + Assert.StartsWith("pmo_", clientId, StringComparison.Ordinal); + return (clientId, isPublic ? null : HttpUtility.HtmlDecode(codes[1].Groups[1].Value)); + } + + /// <summary>Loads a page with a form, then posts the form with the given fields and its token.</summary> + public async Task<HttpResponseMessage> SubmitAsync( + string page, + string action, + IEnumerable<KeyValuePair<string, string>> fields) + { + string html = await (await Browser.GetAsync(page, Cancel)).Content.ReadAsStringAsync(Cancel); + return await Browser.PostAsync(action, new FormUrlEncodedContent( + fields.Append(new("form-token", FormToken(html)))), Cancel); + } + + /// <summary>The token of the first form of a page.</summary> + public static string FormToken(string html) => + HttpUtility.HtmlDecode(TokenPattern().Match(html).Groups[1].Value); + + /// <summary>Every hidden field of the first form of a page, the token included.</summary> + public static List<KeyValuePair<string, string>> HiddenFields(string html) => HiddenPattern().Matches(html) + .Select(match => new KeyValuePair<string, string>( + HttpUtility.HtmlDecode(match.Groups[1].Value), HttpUtility.HtmlDecode(match.Groups[2].Value))) + .ToList(); + + /// <summary>A PKCE verifier and its S256 challenge.</summary> + public static (string Verifier, string Challenge) Pkce() + { + string verifier = Base64Url(RandomNumberGenerator.GetBytes(32)); + return (verifier, Base64Url(SHA256.HashData(Encoding.ASCII.GetBytes(verifier)))); + } + + /// <summary>The query of an authorization request.</summary> + public static string AuthorizePath(string clientId, string scope, string? challenge, string redirectUri = RedirectUri, + string responseType = "code", string? prompt = null) + { + Dictionary<string, string?> query = new() + { + ["response_type"] = responseType, + ["client_id"] = clientId, + ["redirect_uri"] = redirectUri, + ["scope"] = scope, + ["state"] = "state-123", + ["nonce"] = "nonce-456", + ["code_challenge"] = challenge, + ["code_challenge_method"] = challenge is null ? null : "S256", + ["prompt"] = prompt + }; + return "/connect/authorize?" + string.Join('&', query.Where(pair => pair.Value is not null) + .Select(pair => $"{pair.Key}={Uri.EscapeDataString(pair.Value!)}")); + } + + /// <summary>Asks for an authorization and allows it on the consent page; returns the redirection.</summary> + public async Task<Uri> AuthorizeAsync(string clientId, string scope, string challenge, string decision = "allow") + { + HttpResponseMessage consent = await Browser.GetAsync(AuthorizePath(clientId, scope, challenge), Cancel); + if (consent.StatusCode == HttpStatusCode.Redirect) + { + return consent.Headers.Location!; + } + + string html = await consent.Content.ReadAsStringAsync(Cancel); + Assert.True(consent.StatusCode == HttpStatusCode.OK, html); + List<KeyValuePair<string, string>> fields = HiddenFields(html); + fields.Add(new("decision", decision)); + HttpResponseMessage decided = await Browser.PostAsync("/connect/authorize", new FormUrlEncodedContent(fields), Cancel); + Assert.Equal(HttpStatusCode.Redirect, decided.StatusCode); + return decided.Headers.Location!; + } + + /// <summary>Posts to the token endpoint as a client would, from outside the browser.</summary> + public async Task<(HttpStatusCode Status, JsonElement Body)> TokenAsync(Dictionary<string, string> fields) + { + using HttpClient client = factory.CreateOAuthClient(); + HttpResponseMessage response = await client.PostAsync("/connect/token", new FormUrlEncodedContent(fields), Cancel); + return (response.StatusCode, await response.Content.ReadFromJsonAsync<JsonElement>(Cancel)); + } + + /// <summary>The payload of a JSON web token, without checking its signature.</summary> + public static JsonElement Payload(string jwt) + { + string part = jwt.Split('.')[1].Replace('-', '+').Replace('_', '/'); + part = part.PadRight(part.Length + (4 - part.Length % 4) % 4, '='); + return JsonDocument.Parse(Convert.FromBase64String(part)).RootElement.Clone(); + } + + /// <summary>A query parameter of an address.</summary> + public static string? Query(Uri uri, string name) => HttpUtility.ParseQueryString(uri.Query)[name]; + + private static string Base64Url(byte[] bytes) => + Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + [GeneratedRegex("name=\"form-token\" value=\"([^\"]*)\"")] + private static partial Regex TokenPattern(); + + [GeneratedRegex("<input type=\"hidden\" name=\"([^\"]*)\" value=\"([^\"]*)\">")] + private static partial Regex HiddenPattern(); + + [GeneratedRegex("<code>([^<]*)</code>")] + private static partial Regex CodePattern(); +} diff --git a/apps/api-tests/packages.lock.json b/apps/api-tests/packages.lock.json index fe3009a..29d66ff 100644 --- a/apps/api-tests/packages.lock.json +++ b/apps/api-tests/packages.lock.json @@ -52,10 +52,185 @@ "resolved": "6.0.0", "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" }, + "Microsoft.Bcl.Cryptography": { + "type": "Transitive", + "resolved": "10.0.2", + "contentHash": "LG9Yll3B5aNpxv0+D47g6LiOiKBIlodhcHdQwcYzo8VeexFLGqx5ymetmA2aBRyo9cCcWsQWrFsdbsr8LvmWDw==" + }, + "Microsoft.Data.Sqlite.Core": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "Gge8XsSCOwcbkbdmt2UDAe6kIv9Q0vA6yb3wsTStjjexaMFLTWfc/1gH4kbhJ+zWiXRTRA4lG2sOQNVfir204w==", + "dependencies": { + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.EntityFrameworkCore": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "u/z4nTQUJ5nJEXAQekgQEQZkh0delp4gL+ESHn7Z6k037c8HC5mSNu1/YdBgxGm7DtLjhOxktNl+aQMzw6wN7A==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Abstractions": "10.0.13", + "Microsoft.EntityFrameworkCore.Analyzers": "10.0.13" + } + }, + "Microsoft.EntityFrameworkCore.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "ARw+tZ3eiTosnK5nJPUGEzeUQcjyqCqs3qKA3lPtIRH5yJo3qIgxm7AvkZVIT9iWkS2083UsWe3Rj1MysW3p5A==" + }, + "Microsoft.EntityFrameworkCore.Analyzers": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zBx6VeEz/hkhlm0BJ2V+9xebUuDDIszcKvurJceQHuZPEXuXubrL6Lneo9VZiliRyJbQlB2oNKLkJXd3gHteQA==" + }, + "Microsoft.EntityFrameworkCore.Relational": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "QU/sbTtDR5wVAJRVecC1GwM7mwH8bvKOZNm+lulzMr5rhjdb8DDEFIqqdhF08JIo51DPv5uQdZ1nXoZsD5pTag==", + "dependencies": { + "Microsoft.EntityFrameworkCore": "10.0.13" + } + }, + "Microsoft.EntityFrameworkCore.Sqlite": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13", + "Microsoft.Extensions.DependencyModel": "10.0.13", + "SQLitePCLRaw.bundle_e_sqlite3": "2.1.13", + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.EntityFrameworkCore.Sqlite.Core": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==", + "dependencies": { + "Microsoft.Data.Sqlite.Core": "10.0.13", + "Microsoft.EntityFrameworkCore.Relational": "10.0.13", + "Microsoft.Extensions.DependencyModel": "10.0.13", + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.Extensions.AmbientMetadata.Application": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "/FYCIyhRLrDwIg29tB/21/Rp7XMaEP/gWR5Cxyi4GgWcN/v/XXUpU52yhQux0s2SQy1Z0C1wnhptCMvLaaT45Q==" + }, + "Microsoft.Extensions.Compliance.Abstractions": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "7I0DXMTCqpXpXg+SLLDlfedtv6DN5Lgiv+PR3MclzqKPOHNB17YP42KMNI61ckSrffh0xsuIqQyCIjvWc6vUuw==" + }, + "Microsoft.Extensions.DependencyInjection.AutoActivation": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "LXwOAsnrflu2ln+Bxj7y3Zc/Pn4HquCCRzW81oOIuRsM8F75TxwA/ZpSFZ5E1+YkVpndz7BcHY4ThFSjjA4vbQ==" + }, "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ==" + }, + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "tXmzwQeWgiycaLOtvSFnz0TPkJxXTyZrkwSVPTr83FgSiMj3BD/8eIbvrpGi5rzc2AgfKyegKo1ntJlJFey1Zg==" + }, + "Microsoft.Extensions.Http.Diagnostics": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "2pYnolFkigH7N6A5WHdGx93iZ8dIhrBnu4ZkjvB6RwbHzYmIy/iXVe12pdrViNDdeBSmKZ5FA9YP/xhwLT7q7A==", + "dependencies": { + "Microsoft.Extensions.Telemetry": "10.8.0" + } + }, + "Microsoft.Extensions.Http.Polly": { "type": "Transitive", "resolved": "10.0.11", - "contentHash": "PJPtFYsZ+r+uz9qqXWUTEyKeJ1EiBGIJtqavkg9ZXijjGSFAk4Fgi5sqIxj+uAyLZwEKgexDUQXhWhvU6l3+og==" + "contentHash": "DIxaTXWdbjRJihAIutpDIgPbpD9PwW8lW0EIawlNH4zs7coCgwPnd9rYlzXYkuKKphnjcKYlo6gXFeg6z15GLg==", + "dependencies": { + "Polly": "7.2.4", + "Polly.Extensions.Http": "3.0.0" + } + }, + "Microsoft.Extensions.Http.Resilience": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "XtbZyYVxSNn1Aj2Z0PA8yauS12hPszTWDZ3GtZ5Vww7Ai3d8Pm841jMBnTvoTf1t9mRf3eSB38V5KUWxH6/4oQ==", + "dependencies": { + "Microsoft.Extensions.Http.Diagnostics": "10.8.0", + "Microsoft.Extensions.Resilience": "10.8.0" + } + }, + "Microsoft.Extensions.Resilience": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "RH/gv0ZcCnQ3d30lxb8+T2o661TwZq/K5eMwp488goQLX1QYqWN3i8L8XlN9DhrqP2Zcf0EtsWaKpJO3yHDUTw==", + "dependencies": { + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.8.0", + "Microsoft.Extensions.Telemetry.Abstractions": "10.8.0", + "Polly.Extensions": "8.4.2", + "Polly.RateLimiting": "8.4.2" + } + }, + "Microsoft.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "IIWjDZguUJt6yNld9J4V88xuOUzpC76wBwfnRJLRmacmyTTl9jA8+KP5PuHPi7CKz/Vk/q+lQYmobiopuzapzA==", + "dependencies": { + "Microsoft.Extensions.AmbientMetadata.Application": "10.8.0", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.8.0", + "Microsoft.Extensions.Telemetry.Abstractions": "10.8.0" + } + }, + "Microsoft.Extensions.Telemetry.Abstractions": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "XHlOerNKjVrPJqbuFi196tyFhS7eNMoPUC800xJmCGsSiruE/goGoKyBKzS1HeelAGnoFPFrS+LgNitXNeEYRQ==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "10.8.0" + } + }, + "Microsoft.IdentityModel.Abstractions": { + "type": "Transitive", + "resolved": "8.19.2", + "contentHash": "HJbo/lnSfNHUfphPRT910poQc4T2/9+8svFLvzuaYHGAOJ2Tu+oEDqpX0BVP3BJ4OuUM1kylEKyaiX2fCAK3Cw==" + }, + "Microsoft.IdentityModel.JsonWebTokens": { + "type": "Transitive", + "resolved": "8.19.2", + "contentHash": "ui3fuBT4fs8kdKfBthI4NzLYIBIneEVS8UrL1JVBzAn80UiKmngBBi0BEByE7n/9c+EElcfFlCMFFTqpkBSLNA==", + "dependencies": { + "Microsoft.IdentityModel.Tokens": "8.19.2" + } + }, + "Microsoft.IdentityModel.Logging": { + "type": "Transitive", + "resolved": "8.19.2", + "contentHash": "r5YLDIxGOnkVJHrqXv/iD1FM1CgGrQOdriXuvuWvTPmKbnGANhEysq9XKmN6IHjf2a+9bAGEpnoRBsAQlvJU5w==", + "dependencies": { + "Microsoft.IdentityModel.Abstractions": "8.19.2" + } + }, + "Microsoft.IdentityModel.Protocols": { + "type": "Transitive", + "resolved": "8.19.2", + "contentHash": "sGxSsSrZXNmca6D+jHH2rVRyo2nNRd/g4H9CFbPmLLq0xgoH1U0orLWE5minfijw7+zq49tBs7txenbfAErRoQ==", + "dependencies": { + "Microsoft.IdentityModel.Tokens": "8.19.2" + } + }, + "Microsoft.IdentityModel.Tokens": { + "type": "Transitive", + "resolved": "8.19.2", + "contentHash": "GtPC1S02uH1gOO4fQ+zRysIicKmEXaYFP8PIkdJYXqMyruYhopre4ozVHp0XiDSA0+GJvOZH9prxCPvgBMg4Ww==", + "dependencies": { + "Microsoft.Bcl.Cryptography": "10.0.2", + "Microsoft.IdentityModel.Logging": "8.19.2" + } }, "Microsoft.Testing.Extensions.Telemetry": { "type": "Transitive", @@ -97,6 +272,262 @@ "resolved": "10.0.3", "contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==" }, + "Npgsql.EntityFrameworkCore.PostgreSQL": { + "type": "Transitive", + "resolved": "10.0.3", + "contentHash": "IPGrrZnRkuW7OlHDhUESZz4G5DLkW7Nej/O3Cx+0iTsgyU5XJxBgpsvTHLloo3WWuAKKbDHXBvWPVkX1deRh1Q==", + "dependencies": { + "Microsoft.EntityFrameworkCore": "[10.0.4, 11.0.0)", + "Microsoft.EntityFrameworkCore.Relational": "[10.0.4, 11.0.0)", + "Npgsql": "10.0.3" + } + }, + "OpenIddict": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "XMCdZzYZY7CRn3HgLheDI5aMuL6Tit1xO7VaiDVH/qz2Tf295RCbgpBCDcMRh3QYYBqi7RTJIiIKpqhlky91UQ==", + "dependencies": { + "OpenIddict.Abstractions": "7.7.2", + "OpenIddict.Client": "7.7.2", + "OpenIddict.Client.SystemIntegration": "7.7.2", + "OpenIddict.Client.SystemNetHttp": "7.7.2", + "OpenIddict.Client.WebIntegration": "7.7.2", + "OpenIddict.Core": "7.7.2", + "OpenIddict.Server": "7.7.2", + "OpenIddict.Validation": "7.7.2", + "OpenIddict.Validation.ServerIntegration": "7.7.2", + "OpenIddict.Validation.SystemNetHttp": "7.7.2" + } + }, + "OpenIddict.Abstractions": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "rt5feUxOneeZ15jz2koGFVbLWA9gbDu4yPgr9nArFx6YpwP+iaNZHENTi44pTxCXo6wMBaeaApjn1ZMvCu3EEw==", + "dependencies": { + "Microsoft.IdentityModel.Tokens": "8.19.2" + } + }, + "OpenIddict.AspNetCore": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "b6cqAcvJfo0OhKVD7YZkfwcRq7PsXCAb39MaHE+/NGHZ9thmXH9VtlLEdxdH5nnH4pdsWppqsLJ3cprfr9gJrA==", + "dependencies": { + "OpenIddict": "7.7.2", + "OpenIddict.Client.AspNetCore": "7.7.2", + "OpenIddict.Client.DataProtection": "7.7.2", + "OpenIddict.Server.AspNetCore": "7.7.2", + "OpenIddict.Server.DataProtection": "7.7.2", + "OpenIddict.Validation.AspNetCore": "7.7.2", + "OpenIddict.Validation.DataProtection": "7.7.2" + } + }, + "OpenIddict.Client": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "KontwqVvIJeuHilCTwVoCGu2C82To0qWGf+CSG3/iTdX6P8TLVP1pFrOsGzsdtIv/iQNU32mY+ODHcpfb5w6yg==", + "dependencies": { + "Microsoft.IdentityModel.JsonWebTokens": "8.19.2", + "Microsoft.IdentityModel.Protocols": "8.19.2", + "OpenIddict.Abstractions": "7.7.2" + } + }, + "OpenIddict.Client.AspNetCore": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "a98jz1NJOeRHUnapuIAnNh+vtq2TYKE04Ui+xP+jPTT6SXMK1CHx99sjivV//DCmjppeAl8MCpjitWCpCnvdDQ==", + "dependencies": { + "OpenIddict.Client": "7.7.2" + } + }, + "OpenIddict.Client.DataProtection": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "Yy+wKySBdjB7PCvCFP+YHDWBsgmzNbRHbpl9CoOy5tjRrWJ2OQvZg/4Wchw1bYBSri521d/IIloTp3HsZMXmNQ==", + "dependencies": { + "OpenIddict.Client": "7.7.2" + } + }, + "OpenIddict.Client.SystemIntegration": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "4Do/ynyqKdVPyY4yu/mnIxz4YAe9gc9sIMiSrra+yl1Sj0RZytOTvCcV/3r8/wJWOqsnYsg/W/lkiG8AKfq5Xg==", + "dependencies": { + "OpenIddict.Client": "7.7.2" + } + }, + "OpenIddict.Client.SystemNetHttp": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "u7Kw197UetHPvnGosaAWXmfjnP0F4OsvQG+vqyv58eJBmIs3zJKo+80AHYfs/CpOKjgZSIA56WnhStqZr5MflA==", + "dependencies": { + "Microsoft.Extensions.Http.Polly": "10.0.11", + "Microsoft.Extensions.Http.Resilience": "10.8.0", + "OpenIddict.Client": "7.7.2" + } + }, + "OpenIddict.Client.WebIntegration": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "7abzcKwUkVjMJLLamTNwE73RWLjzMKp3Fj972aQLte7XyYPKG8ZC4gMgZBPcSrL2EE/+hhemPjm8C07Yr10Gaw==", + "dependencies": { + "OpenIddict.Client": "7.7.2", + "OpenIddict.Client.SystemNetHttp": "7.7.2" + } + }, + "OpenIddict.Core": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "VsPYuXWx1YtbKFyW/O2vV/egJtTXmAOUE7AJq+I/laT3WIroeiDqHT8jDnhjIhDjHcjfNupR/u5nhWD6t5ocqg==", + "dependencies": { + "OpenIddict.Abstractions": "7.7.2" + } + }, + "OpenIddict.EntityFrameworkCore": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "OspAqs92TbxK80Oakuo2olN0w8ZkozqjaqDXkEmS6Z2fHTE3kF3JhCjVUnFMpgHoVqTVrlcxUPJAaiYxxB17Zw==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Relational": "10.0.11", + "OpenIddict.Core": "7.7.2", + "OpenIddict.EntityFrameworkCore.Models": "7.7.2" + } + }, + "OpenIddict.EntityFrameworkCore.Models": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "ESK3iS3UJR4XBDlX0YTgiE24xWM7QfO6AtoJphMx1zLhzup5JUOEXyoosP8Z/vh4B1/cj+QUTz+314Us7/hqCg==" + }, + "OpenIddict.Server": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "azPkMKSMTSlvIKwdesbSaHvTdaNWndqrw/e6P9lyP5/6QG5IhrTK3y2rHWQlv14EU9xG/YegLimP61zapq+ocg==", + "dependencies": { + "Microsoft.IdentityModel.JsonWebTokens": "8.19.2", + "OpenIddict.Abstractions": "7.7.2" + } + }, + "OpenIddict.Server.AspNetCore": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "Nde/hqZbxCbhP8KE5laXbLzsgMFEClaAPL3hiGUezob6ixsq5ga84yQ4aPVrI35sD8Cd6BOh74DkqwvWwZRrfg==", + "dependencies": { + "OpenIddict.Server": "7.7.2" + } + }, + "OpenIddict.Server.DataProtection": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "TYzZUTRNAYOSHP8mJ0qq+R+N0AWDTDSycHEZhC/qVtjBjT0J7GMTVheBP2fhfHksleAsYNLpNuAIYK27rzTqGA==", + "dependencies": { + "OpenIddict.Server": "7.7.2" + } + }, + "OpenIddict.Validation": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "B5hHtkAZsayfci4uUFmaNF2onJ/WllYbbb94oZyhG/759VB6S6f04Humye7q8dRJa1VoEN7P3I/ep32aCofQLQ==", + "dependencies": { + "Microsoft.IdentityModel.JsonWebTokens": "8.19.2", + "Microsoft.IdentityModel.Protocols": "8.19.2", + "OpenIddict.Abstractions": "7.7.2" + } + }, + "OpenIddict.Validation.AspNetCore": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "amZ0SwrgqqUZUsQbGks3qKSlAMybv0YaqbT97hS2Ph3R/IcdTFTXe770LMR32MI6TxWKvEVWCMO+itqEIJCykw==", + "dependencies": { + "OpenIddict.Validation": "7.7.2" + } + }, + "OpenIddict.Validation.DataProtection": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "y5nCO4MGWnMffUA8NiPo7Td7S/JX1MnrbZqLAoof0ZPDqgKp0a8pYrfbRRLwUWd2xLRUJuODXRnsw6I4EbuAEA==", + "dependencies": { + "OpenIddict.Validation": "7.7.2" + } + }, + "OpenIddict.Validation.ServerIntegration": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "2h1LlTkWScAFQoYaKBJ3sbAd3lM7o0gRux0XLg+8D//3Bqlla6p9VjM53DrdnyGWQ1wK3x8cmFcEqDTPePoGZw==", + "dependencies": { + "OpenIddict.Server": "7.7.2", + "OpenIddict.Validation": "7.7.2" + } + }, + "OpenIddict.Validation.SystemNetHttp": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "aEIceyMGX92VokcMBGsJtongfs1z2yQma745CPPWq0Uk9exUqitvXbPm+7TGM0lNh7Fh8hB8QhvNPctDQcIqAg==", + "dependencies": { + "Microsoft.Extensions.Http.Polly": "10.0.11", + "Microsoft.Extensions.Http.Resilience": "10.8.0", + "OpenIddict.Validation": "7.7.2" + } + }, + "Polly": { + "type": "Transitive", + "resolved": "7.2.4", + "contentHash": "bw00Ck5sh6ekduDE3mnCo1ohzuad946uslCDEENu3091+6UKnBuKLo4e+yaNcCzXxOZCXWY2gV4a35+K1d4LDA==" + }, + "Polly.Core": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" + }, + "Polly.Extensions": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", + "dependencies": { + "Polly.Core": "8.4.2" + } + }, + "Polly.Extensions.Http": { + "type": "Transitive", + "resolved": "3.0.0", + "contentHash": "drrG+hB3pYFY7w1c3BD+lSGYvH2oIclH8GRSehgfyP5kjnFnHKQuuBhuHLv+PWyFuaTDyk/vfRpnxOzd11+J8g==", + "dependencies": { + "Polly": "7.1.0" + } + }, + "Polly.RateLimiting": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", + "dependencies": { + "Polly.Core": "8.4.2" + } + }, + "SQLitePCLRaw.bundle_e_sqlite3": { + "type": "Transitive", + "resolved": "2.1.13", + "contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==", + "dependencies": { + "SQLitePCLRaw.lib.e_sqlite3": "2.1.13", + "SQLitePCLRaw.provider.e_sqlite3": "2.1.13" + } + }, + "SQLitePCLRaw.core": { + "type": "Transitive", + "resolved": "2.1.13", + "contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q==" + }, + "SQLitePCLRaw.lib.e_sqlite3": { + "type": "Transitive", + "resolved": "2.1.13", + "contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A==" + }, + "SQLitePCLRaw.provider.e_sqlite3": { + "type": "Transitive", + "resolved": "2.1.13", + "contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==", + "dependencies": { + "SQLitePCLRaw.core": "2.1.13" + } + }, "System.Security.AccessControl": { "type": "Transitive", "resolved": "6.0.1", @@ -164,7 +595,11 @@ "type": "Project", "dependencies": { "Microsoft.AspNetCore.Authentication.Google": "[10.0.11, )", - "Npgsql": "[10.0.3, )" + "Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )", + "Npgsql": "[10.0.3, )", + "Npgsql.EntityFrameworkCore.PostgreSQL": "[10.0.3, )", + "OpenIddict.AspNetCore": "[7.7.2, )", + "OpenIddict.EntityFrameworkCore": "[7.7.2, )" } } } diff --git a/apps/api/Accounts/AccountService.cs b/apps/api/Accounts/AccountService.cs index 7634948..0deadb5 100644 --- a/apps/api/Accounts/AccountService.cs +++ b/apps/api/Accounts/AccountService.cs @@ -95,8 +95,26 @@ internal sealed class AccountService( SessionService sessions, CancellationToken cancellationToken) { - if (!EmailAddressPolicy.TryNormalize(request.Email, out _, out string normalizedEmail, out _) || - request.Password is null || request.Password.Length > PasswordPolicy.MaximumLength) + AccountRecord? account = await VerifyPasswordAsync(request.Email, request.Password, cancellationToken); + return account is null ? null : await sessions.CreateAsync(account, cancellationToken); + } + + /// <summary>Checks an email address and password without opening a session.</summary> + /// <remarks> + /// Progmasoft Credentials signs the account in with its own cookie and must not open a session of the account + /// site. The verification is the one <see cref="LoginAsync"/> uses, with the same cost for an unknown address. + /// </remarks> + /// <param name="email">Email address as entered.</param> + /// <param name="password">Password as entered.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>The account, or <see langword="null"/> when the credentials are refused.</returns> + public async ValueTask<AccountRecord?> VerifyPasswordAsync( + string? email, + string? password, + CancellationToken cancellationToken) + { + if (!EmailAddressPolicy.TryNormalize(email, out _, out string normalizedEmail, out _) || + password is null || password.Length > PasswordPolicy.MaximumLength) { return null; } @@ -105,20 +123,22 @@ internal sealed class AccountService( if (account is null || account.PasswordHash is null) { // Reuse one private hash so an unknown email follows one expensive verification, like a bad password. - _ = passwordHasher.VerifyHashedPassword(DummyAccount, DummyPasswordHash, request.Password); + _ = passwordHasher.VerifyHashedPassword(DummyAccount, DummyPasswordHash, password); return null; } PasswordVerificationResult verification = - passwordHasher.VerifyHashedPassword(account, account.PasswordHash, request.Password); - if (verification is PasswordVerificationResult.Failed) - { - return null; - } - - return await sessions.CreateAsync(account, cancellationToken); + passwordHasher.VerifyHashedPassword(account, account.PasswordHash, password); + return verification is PasswordVerificationResult.Failed ? null : account; } + /// <summary>Finds an account by its identifier, for a Credentials session that names it.</summary> + /// <param name="id">Identifier of the account.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>The account, or <see langword="null"/> when it no longer exists.</returns> + public ValueTask<AccountRecord?> FindAsync(Guid id, CancellationToken cancellationToken) => + store.FindByIdAsync(id, cancellationToken); + /// <summary>Signs in with a Google identity, creating the account on first use.</summary> /// <remarks> /// An identity that is already linked signs in to its account. A new identity creates an account under the diff --git a/apps/api/OAuth/Developers/ApplicationPolicy.cs b/apps/api/OAuth/Developers/ApplicationPolicy.cs new file mode 100644 index 0000000..085d0b9 --- /dev/null +++ b/apps/api/OAuth/Developers/ApplicationPolicy.cs @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Net; + +namespace Progmasoft.OAuth.Developers; + +/// <summary>What a developer submits to register or change an application.</summary> +/// <param name="DisplayName">The name the consent page shows.</param> +/// <param name="Homepage">The address of the application's site, or empty.</param> +/// <param name="IsPublic"> +/// Whether the application cannot keep a secret: a browser or native application. Such a client has no secret and +/// may not use the client credentials grant. +/// </param> +/// <param name="RedirectUris">The addresses the authorization endpoint may send the account holder back to.</param> +/// <param name="PostLogoutRedirectUris">The addresses the end-session endpoint may send the account holder back to.</param> +/// <param name="Scopes">The scopes the application may request.</param> +/// <param name="AllowClientCredentials">Whether the application may act as itself with the client credentials grant.</param> +internal sealed record ApplicationInput( + string DisplayName, + string Homepage, + bool IsPublic, + IReadOnlyList<string> RedirectUris, + IReadOnlyList<string> PostLogoutRedirectUris, + IReadOnlyList<string> Scopes, + bool AllowClientCredentials); + +/// <summary>The rules an application registration must follow.</summary> +/// <remarks> +/// Redirection addresses are compared exactly by the authorization server, so the rules here only decide which +/// addresses may be registered: HTTPS, an <c>http</c> loopback address for software on the developer's own +/// machine, or, for public clients, a private-use scheme of a native application as RFC 8252 describes. A +/// fragment, user information or a wildcard is never accepted. +/// </remarks> +internal static class ApplicationPolicy +{ + /// <summary>The most redirection addresses one application may register, of each kind.</summary> + public const int MaximumRedirectUris = 10; + + /// <summary>The longest display name.</summary> + public const int MaximumDisplayNameLength = 64; + + /// <summary>The longest address.</summary> + public const int MaximumUriLength = 2000; + + /// <summary>Checks a submission.</summary> + /// <param name="input">The submission.</param> + /// <returns>The messages of each refused field, keyed by field name; empty when the submission is valid.</returns> + public static Dictionary<string, string> Validate(ApplicationInput input) + { + Dictionary<string, string> errors = []; + string name = input.DisplayName.Trim(); + if (name.Length is < 3 or > MaximumDisplayNameLength || name.Any(char.IsControl)) + { + errors["displayName"] = + $"Use 3 to {MaximumDisplayNameLength} characters, without control characters."; + } + + if (input.Homepage.Length != 0 && !IsHttpsAddress(input.Homepage)) + { + errors["homepage"] = "The homepage must be an https:// address."; + } + + if (input.RedirectUris.Count is 0 or > MaximumRedirectUris) + { + errors["redirectUris"] = $"Register 1 to {MaximumRedirectUris} redirection addresses, one per line."; + } + else if (input.RedirectUris.FirstOrDefault(uri => !IsRedirectionAddress(uri, input.IsPublic)) is { } wrong) + { + errors["redirectUris"] = $"{wrong} cannot be registered. {AddressRule(input.IsPublic)}"; + } + + if (input.PostLogoutRedirectUris.Count > MaximumRedirectUris) + { + errors["postLogoutRedirectUris"] = $"Register at most {MaximumRedirectUris} addresses."; + } + else if (input.PostLogoutRedirectUris.FirstOrDefault(uri => !IsRedirectionAddress(uri, input.IsPublic)) is + { } wrongLogout) + { + errors["postLogoutRedirectUris"] = $"{wrongLogout} cannot be registered. {AddressRule(input.IsPublic)}"; + } + + if (input.Scopes.Any(scope => OAuthScopes.Find(scope) is null)) + { + errors["scopes"] = "Choose scopes from the list."; + } + + if (input.IsPublic && input.AllowClientCredentials) + { + errors["allowClientCredentials"] = + "A public client has no secret and cannot use the client credentials grant."; + } + + return errors; + } + + /// <summary>Splits a text area into its non-empty lines.</summary> + /// <param name="text">The submitted text.</param> + /// <returns>Each line once, trimmed, in the submitted order.</returns> + public static IReadOnlyList<string> Lines(string? text) => (text ?? string.Empty) + .Split('\n') + .Select(line => line.Trim()) + .Where(line => line.Length != 0) + .Distinct(StringComparer.Ordinal) + .ToList(); + + private static string AddressRule(bool isPublic) => isPublic + ? "Use https://, http:// with a loopback address, or a private-use scheme such as com.example.app:/callback." + : "Use https://, or http:// with a loopback address for development."; + + private static bool IsHttpsAddress(string text) => + text.Length <= MaximumUriLength + && Uri.TryCreate(text, UriKind.Absolute, out Uri? uri) + && uri.Scheme == Uri.UriSchemeHttps + && IsClean(uri); + + /// <summary>Whether an address may be registered for redirection.</summary> + /// <param name="text">The address.</param> + /// <param name="isPublic">Whether the application is a public client.</param> + /// <returns><see langword="true"/> when the address follows the rules above.</returns> + internal static bool IsRedirectionAddress(string text, bool isPublic) + { + if (text.Length > MaximumUriLength || text.Contains('*', StringComparison.Ordinal) + || !Uri.TryCreate(text, UriKind.Absolute, out Uri? uri) || !IsClean(uri)) + { + return false; + } + + if (uri.Scheme == Uri.UriSchemeHttps) + { + return true; + } + + if (uri.Scheme == Uri.UriSchemeHttp) + { + // RFC 8252 section 7.3: loopback, never a host name that DNS could point elsewhere, except localhost + // during development. + return uri.Host == "localhost" || (IPAddress.TryParse(uri.Host.Trim('[', ']'), out IPAddress? address) + && IPAddress.IsLoopback(address)); + } + + // RFC 8252 section 7.1: a private-use scheme names the application in reverse DNS order, so it contains a + // dot; javascript:, data: and the like are refused by that rule as well as by the explicit list. + string[] refused = ["javascript", "data", "file", "vbscript", "about", "blob"]; + return isPublic && uri.Scheme.Contains('.', StringComparison.Ordinal) && !refused.Contains(uri.Scheme); + } + + private static bool IsClean(Uri uri) => uri.Fragment.Length == 0 && uri.UserInfo.Length == 0; +} diff --git a/apps/api/OAuth/Developers/ApplicationRegistry.cs b/apps/api/OAuth/Developers/ApplicationRegistry.cs new file mode 100644 index 0000000..85eb322 --- /dev/null +++ b/apps/api/OAuth/Developers/ApplicationRegistry.cs @@ -0,0 +1,328 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Security.Cryptography; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using OpenIddict.Abstractions; +using Progmasoft.OAuth.Storage; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth.Developers; + +/// <summary>An application as its owner sees it in the developer portal.</summary> +/// <param name="ClientId">The public identifier of the client.</param> +/// <param name="DisplayName">The name the consent page shows.</param> +/// <param name="Homepage">The address of the application's site, or empty.</param> +/// <param name="IsPublic">Whether the client has no secret.</param> +/// <param name="RedirectUris">The registered redirection addresses.</param> +/// <param name="PostLogoutRedirectUris">The registered end-session addresses.</param> +/// <param name="Scopes">The scopes the application may request.</param> +/// <param name="AllowClientCredentials">Whether the client credentials grant is allowed.</param> +/// <param name="CreatedAt">When the application was registered.</param> +internal sealed record RegisteredApplication( + string ClientId, + string DisplayName, + string Homepage, + bool IsPublic, + IReadOnlyList<string> RedirectUris, + IReadOnlyList<string> PostLogoutRedirectUris, + IReadOnlyList<string> Scopes, + bool AllowClientCredentials, + DateTimeOffset CreatedAt); + +/// <summary>What registering an application produced.</summary> +/// <param name="Application">The application, or <see langword="null"/> when it was refused.</param> +/// <param name="ClientSecret">The secret of a confidential client; shown once and never stored in clear.</param> +/// <param name="Errors">The messages of each refused field.</param> +internal sealed record RegistrationResult( + RegisteredApplication? Application, + string? ClientSecret, + IReadOnlyDictionary<string, string> Errors); + +/// <summary>Registers, changes and deletes the applications of an account.</summary> +/// <remarks> +/// Every operation takes the account that acts and touches only applications that account owns. An application of +/// another account is reported as absent, so that client identifiers cannot be probed through the portal. +/// </remarks> +/// <param name="applications">OpenIddict's application manager.</param> +/// <param name="database">The OAuth tables.</param> +/// <param name="options">The settings of Progmasoft OAuth.</param> +/// <param name="timeProvider">Clock of the registration times.</param> +internal sealed class ApplicationRegistry( + IOpenIddictApplicationManager applications, + OAuthDbContext database, + IOptions<OAuthOptions> options, + TimeProvider timeProvider) +{ + /// <summary>The property of the application that keeps its homepage.</summary> + private const string HomepageProperty = "homepage"; + + /// <summary>Lists the applications of an account, newest first.</summary> + /// <param name="accountId">The owner.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>The applications.</returns> + public async Task<IReadOnlyList<RegisteredApplication>> ListAsync(Guid accountId, CancellationToken cancellationToken) + { + List<ApplicationOwner> owned = await database.ApplicationOwners + .Where(owner => owner.AccountId == accountId) + .OrderByDescending(owner => owner.CreatedAt) + .ToListAsync(cancellationToken); + List<RegisteredApplication> result = []; + foreach (ApplicationOwner owner in owned) + { + if (await applications.FindByIdAsync(owner.ApplicationId, cancellationToken) is { } application) + { + result.Add(await DescribeAsync(application, owner.CreatedAt, cancellationToken)); + } + } + + return result; + } + + /// <summary>Finds an application of an account by its client identifier.</summary> + /// <param name="accountId">The account that asks.</param> + /// <param name="clientId">The client identifier.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>The application, or <see langword="null"/> when the account owns no such application.</returns> + public async Task<RegisteredApplication?> FindOwnedAsync( + Guid accountId, + string clientId, + CancellationToken cancellationToken) + { + (object application, ApplicationOwner owner)? found = await FindOwnedEntryAsync(accountId, clientId, cancellationToken); + return found is null ? null : await DescribeAsync(found.Value.application, found.Value.owner.CreatedAt, cancellationToken); + } + + /// <summary>Finds the account that registered an application.</summary> + /// <param name="applicationId">The OpenIddict identifier of the application.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>The owning account, or <see langword="null"/> for an application without an owner.</returns> + public async Task<Guid?> FindOwnerAsync(string applicationId, CancellationToken cancellationToken) => + (await database.ApplicationOwners.FirstOrDefaultAsync( + owner => owner.ApplicationId == applicationId, cancellationToken))?.AccountId; + + /// <summary>Registers an application for an account.</summary> + /// <param name="accountId">The owner.</param> + /// <param name="input">The submission.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>The application and its secret, or the refused fields.</returns> + public async Task<RegistrationResult> CreateAsync( + Guid accountId, + ApplicationInput input, + CancellationToken cancellationToken) + { + Dictionary<string, string> errors = ApplicationPolicy.Validate(input); + int count = await database.ApplicationOwners.CountAsync(owner => owner.AccountId == accountId, cancellationToken); + if (count >= options.Value.MaximumApplicationsPerAccount) + { + errors["displayName"] = + $"An account can register {options.Value.MaximumApplicationsPerAccount} applications. Delete one first."; + } + + if (errors.Count != 0) + { + return new RegistrationResult(null, null, errors); + } + + string clientId = "pmo_" + RandomText(15); + string? secret = input.IsPublic ? null : RandomText(32); + OpenIddictApplicationDescriptor descriptor = new() + { + ClientId = clientId, + ClientSecret = secret, + }; + Describe(descriptor, input); + object application = await applications.CreateAsync(descriptor, cancellationToken); + + DateTimeOffset now = timeProvider.GetUtcNow(); + database.ApplicationOwners.Add(new ApplicationOwner + { + ApplicationId = (await applications.GetIdAsync(application, cancellationToken))!, + AccountId = accountId, + CreatedAt = now + }); + await database.SaveChangesAsync(cancellationToken); + return new RegistrationResult(await DescribeAsync(application, now, cancellationToken), secret, + new Dictionary<string, string>()); + } + + /// <summary>Changes an application of an account. The client identifier, type and secret stay.</summary> + /// <param name="accountId">The account that asks.</param> + /// <param name="clientId">The client identifier.</param> + /// <param name="input">The new settings; <see cref="ApplicationInput.IsPublic"/> is ignored.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>The refused fields, empty on success, or <see langword="null"/> when the application is absent.</returns> + public async Task<IReadOnlyDictionary<string, string>?> UpdateAsync( + Guid accountId, + string clientId, + ApplicationInput input, + CancellationToken cancellationToken) + { + if (await FindOwnedEntryAsync(accountId, clientId, cancellationToken) is not { } found) + { + return null; + } + + bool isPublic = await applications.HasClientTypeAsync(found.application, ClientTypes.Public, cancellationToken); + ApplicationInput effective = input with { IsPublic = isPublic }; + Dictionary<string, string> errors = ApplicationPolicy.Validate(effective); + if (errors.Count != 0) + { + return errors; + } + + OpenIddictApplicationDescriptor descriptor = new(); + await applications.PopulateAsync(descriptor, found.application, cancellationToken); + Describe(descriptor, effective); + await applications.UpdateAsync(found.application, descriptor, cancellationToken); + return errors; + } + + /// <summary>Replaces the secret of a confidential application.</summary> + /// <param name="accountId">The account that asks.</param> + /// <param name="clientId">The client identifier.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>The new secret, or <see langword="null"/> for an absent or public application.</returns> + public async Task<string?> RotateSecretAsync(Guid accountId, string clientId, CancellationToken cancellationToken) + { + if (await FindOwnedEntryAsync(accountId, clientId, cancellationToken) is not { } found + || await applications.HasClientTypeAsync(found.application, ClientTypes.Public, cancellationToken)) + { + return null; + } + + string secret = RandomText(32); + OpenIddictApplicationDescriptor descriptor = new(); + await applications.PopulateAsync(descriptor, found.application, cancellationToken); + descriptor.ClientSecret = secret; + await applications.UpdateAsync(found.application, descriptor, cancellationToken); + return secret; + } + + /// <summary>Deletes an application with its authorizations and tokens.</summary> + /// <param name="accountId">The account that asks.</param> + /// <param name="clientId">The client identifier.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns><see langword="true"/> when the application was deleted.</returns> + public async Task<bool> DeleteAsync(Guid accountId, string clientId, CancellationToken cancellationToken) + { + if (await FindOwnedEntryAsync(accountId, clientId, cancellationToken) is not { } found) + { + return false; + } + + database.ApplicationOwners.Remove(found.owner); + await database.SaveChangesAsync(cancellationToken); + await applications.DeleteAsync(found.application, cancellationToken); + return true; + } + + private async Task<(object application, ApplicationOwner owner)?> FindOwnedEntryAsync( + Guid accountId, + string clientId, + CancellationToken cancellationToken) + { + if (await applications.FindByClientIdAsync(clientId, cancellationToken) is not { } application) + { + return null; + } + + string? id = await applications.GetIdAsync(application, cancellationToken); + ApplicationOwner? owner = await database.ApplicationOwners.FirstOrDefaultAsync( + entry => entry.ApplicationId == id && entry.AccountId == accountId, cancellationToken); + return owner is null ? null : (application, owner); + } + + /// <summary>Writes a submission into a descriptor: names, addresses and permissions.</summary> + /// <param name="descriptor">The descriptor to fill.</param> + /// <param name="input">The validated submission.</param> + private static void Describe(OpenIddictApplicationDescriptor descriptor, ApplicationInput input) + { + descriptor.DisplayName = input.DisplayName.Trim(); + descriptor.ApplicationType = input.IsPublic ? ApplicationTypes.Native : ApplicationTypes.Web; + descriptor.ClientType = input.IsPublic ? ClientTypes.Public : ClientTypes.Confidential; + // Every client of Progmasoft OAuth shows the consent page: none is trusted by default. + descriptor.ConsentType = ConsentTypes.Explicit; + descriptor.Properties[HomepageProperty] = JsonSerializer.SerializeToElement(input.Homepage.Trim()); + + descriptor.RedirectUris.Clear(); + foreach (string uri in input.RedirectUris) + { + descriptor.RedirectUris.Add(new Uri(uri)); + } + + descriptor.PostLogoutRedirectUris.Clear(); + foreach (string uri in input.PostLogoutRedirectUris) + { + descriptor.PostLogoutRedirectUris.Add(new Uri(uri)); + } + + descriptor.Permissions.Clear(); + descriptor.Permissions.UnionWith( + [ + Permissions.Endpoints.Authorization, + Permissions.Endpoints.Token, + Permissions.Endpoints.EndSession, + Permissions.Endpoints.Revocation, + Permissions.GrantTypes.AuthorizationCode, + Permissions.ResponseTypes.Code + ]); + if (!input.IsPublic) + { + descriptor.Permissions.Add(Permissions.Endpoints.Introspection); + } + + if (input.Scopes.Contains(Scopes.OfflineAccess)) + { + descriptor.Permissions.Add(Permissions.GrantTypes.RefreshToken); + } + + if (input.AllowClientCredentials) + { + descriptor.Permissions.Add(Permissions.GrantTypes.ClientCredentials); + } + + foreach (string scope in input.Scopes) + { + descriptor.Permissions.Add(Permissions.Prefixes.Scope + scope); + } + + descriptor.Requirements.Clear(); + descriptor.Requirements.Add(Requirements.Features.ProofKeyForCodeExchange); + } + + private async Task<RegisteredApplication> DescribeAsync( + object application, + DateTimeOffset createdAt, + CancellationToken cancellationToken) + { + var permissions = await applications.GetPermissionsAsync(application, cancellationToken); + var properties = await applications.GetPropertiesAsync(application, cancellationToken); + string homepage = properties.TryGetValue(HomepageProperty, out JsonElement value) + && value.ValueKind is JsonValueKind.String + ? value.GetString() ?? string.Empty + : string.Empty; + return new RegisteredApplication( + (await applications.GetClientIdAsync(application, cancellationToken))!, + await applications.GetDisplayNameAsync(application, cancellationToken) ?? string.Empty, + homepage, + await applications.HasClientTypeAsync(application, ClientTypes.Public, cancellationToken), + (await applications.GetRedirectUrisAsync(application, cancellationToken)).Order(StringComparer.Ordinal).ToList(), + (await applications.GetPostLogoutRedirectUrisAsync(application, cancellationToken)) + .Order(StringComparer.Ordinal).ToList(), + OAuthScopes.All + .Where(scope => permissions.Contains(Permissions.Prefixes.Scope + scope.Name)) + .Select(scope => scope.Name) + .ToList(), + permissions.Contains(Permissions.GrantTypes.ClientCredentials), + createdAt); + } + + /// <summary>Random text of the given number of bytes, as unpadded URL-safe base64.</summary> + /// <param name="bytes">How many random bytes.</param> + /// <returns>The text.</returns> + private static string RandomText(int bytes) => + Convert.ToBase64String(RandomNumberGenerator.GetBytes(bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); +} diff --git a/apps/api/OAuth/Developers/DeveloperEndpoints.cs b/apps/api/OAuth/Developers/DeveloperEndpoints.cs new file mode 100644 index 0000000..895bd9f --- /dev/null +++ b/apps/api/OAuth/Developers/DeveloperEndpoints.cs @@ -0,0 +1,287 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using Microsoft.Extensions.Options; +using Progmasoft.OAuth.Pages; +using Progmasoft.Progmaweb.Api.Accounts; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth.Developers; + +/// <summary>The developer portal: any account registers and manages its own applications here.</summary> +internal static class DeveloperEndpoints +{ + /// <summary>Maps the portal.</summary> + /// <param name="app">The application.</param> + public static void MapDeveloperPortal(this WebApplication app) + { + app.MapGet("/developers", ListAsync); + app.MapGet("/developers/new", (Delegate)NewAsync); + app.MapPost("/developers/new", CreateAsync).RequireRateLimiting("oauth"); + app.MapGet("/developers/{clientId}", ShowAsync); + app.MapPost("/developers/{clientId}", UpdateAsync).RequireRateLimiting("oauth"); + app.MapPost("/developers/{clientId}/secret", RotateAsync).RequireRateLimiting("oauth"); + app.MapPost("/developers/{clientId}/delete", DeleteAsync).RequireRateLimiting("oauth"); + } + + private static async Task<IResult> ListAsync( + HttpContext context, + ApplicationRegistry registry, + IOptions<OAuthOptions> options) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInFirst(context); + } + + IReadOnlyList<RegisteredApplication> owned = await registry.ListAsync(account.Id, context.RequestAborted); + string list = owned.Count == 0 + ? "<p>You have not registered an application yet.</p>" + : "<ul>" + string.Concat(owned.Select(application => + $"<li><a href=\"/developers/{Uri.EscapeDataString(application.ClientId)}\">" + + $"{HtmlPage.Encode(application.DisplayName)}</a> " + + $"<span class=\"note\">{(application.IsPublic ? "public" : "confidential")} · " + + $"<code>{HtmlPage.Encode(application.ClientId)}</code></span></li>")) + "</ul>"; + string body = + "<h1>Your applications</h1>" + list + + (owned.Count < options.Value.MaximumApplicationsPerAccount + ? "<p><a href=\"/developers/new\">Register an application</a></p>" + : $"<p class=\"note\">An account can register {options.Value.MaximumApplicationsPerAccount} applications.</p>") + + "<h2>Endpoints</h2>" + + "<p class=\"note\">Read the discovery document at <a href=\"/.well-known/openid-configuration\">" + + "/.well-known/openid-configuration</a>. Every client uses the authorization code flow with PKCE (S256); " + + "confidential clients authenticate at the token endpoint with their secret.</p>" + + "<p><a href=\"/\">Back</a></p>"; + return HtmlPage.Render(context, "Your applications", body); + } + + private static async Task<IResult> NewAsync(HttpContext context) + { + if (await OAuthAccount.CurrentAsync(context) is null) + { + return OAuthAccount.SignInFirst(context); + } + + return RenderForm(context, "Register an application", "/developers/new", + new ApplicationInput(string.Empty, string.Empty, false, [], [], [Scopes.Profile], false), + isNew: true, new Dictionary<string, string>()); + } + + private static async Task<IResult> CreateAsync(HttpContext context, ApplicationRegistry registry) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInFirst(context); + } + + if (!await OAuthAccount.IsGenuineFormAsync(context)) + { + return Results.BadRequest(); + } + + ApplicationInput input = await ReadAsync(context); + RegistrationResult result = await registry.CreateAsync(account.Id, input, context.RequestAborted); + if (result.Application is null) + { + return RenderForm(context, "Register an application", "/developers/new", input, isNew: true, + result.Errors, StatusCodes.Status400BadRequest); + } + + return RenderCredentials(context, "Application registered", result.Application, result.ClientSecret); + } + + private static async Task<IResult> ShowAsync(HttpContext context, ApplicationRegistry registry, string clientId) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInFirst(context); + } + + RegisteredApplication? application = await registry.FindOwnedAsync(account.Id, clientId, context.RequestAborted); + return application is null + ? NotFound(context) + : RenderDetails(context, application, new Dictionary<string, string>(), null); + } + + private static async Task<IResult> UpdateAsync(HttpContext context, ApplicationRegistry registry, string clientId) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInFirst(context); + } + + if (!await OAuthAccount.IsGenuineFormAsync(context)) + { + return Results.BadRequest(); + } + + ApplicationInput input = await ReadAsync(context); + IReadOnlyDictionary<string, string>? errors = + await registry.UpdateAsync(account.Id, clientId, input, context.RequestAborted); + RegisteredApplication? application = await registry.FindOwnedAsync(account.Id, clientId, context.RequestAborted); + if (errors is null || application is null) + { + return NotFound(context); + } + + return errors.Count == 0 + ? RenderDetails(context, application, errors, "The application was saved.") + : RenderForm(context, application.DisplayName, $"/developers/{Uri.EscapeDataString(clientId)}", + input with { IsPublic = application.IsPublic }, isNew: false, errors, + StatusCodes.Status400BadRequest); + } + + private static async Task<IResult> RotateAsync(HttpContext context, ApplicationRegistry registry, string clientId) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInFirst(context); + } + + if (!await OAuthAccount.IsGenuineFormAsync(context)) + { + return Results.BadRequest(); + } + + string? secret = await registry.RotateSecretAsync(account.Id, clientId, context.RequestAborted); + RegisteredApplication? application = await registry.FindOwnedAsync(account.Id, clientId, context.RequestAborted); + return secret is null || application is null + ? NotFound(context) + : RenderCredentials(context, "New client secret", application, secret); + } + + private static async Task<IResult> DeleteAsync(HttpContext context, ApplicationRegistry registry, string clientId) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInFirst(context); + } + + if (!await OAuthAccount.IsGenuineFormAsync(context)) + { + return Results.BadRequest(); + } + + return await registry.DeleteAsync(account.Id, clientId, context.RequestAborted) + ? Results.Redirect("/developers") + : NotFound(context); + } + + private static async Task<ApplicationInput> ReadAsync(HttpContext context) + { + IFormCollection form = await context.Request.ReadFormAsync(context.RequestAborted); + return new ApplicationInput( + form["displayName"].ToString(), + form["homepage"].ToString().Trim(), + form["clientType"] == "public", + ApplicationPolicy.Lines(form["redirectUris"]), + ApplicationPolicy.Lines(form["postLogoutRedirectUris"]), + form["scope"].Where(scope => scope is not null).Select(scope => scope!).Distinct(StringComparer.Ordinal).ToList(), + form["allowClientCredentials"] == "on"); + } + + private static IResult RenderCredentials( + HttpContext context, + string title, + RegisteredApplication application, + string? secret) + { + string body = + $"<h1>{HtmlPage.Encode(title)}</h1>" + + $"<p><strong>{HtmlPage.Encode(application.DisplayName)}</strong></p>" + + $"<label>Client identifier</label><p><code>{HtmlPage.Encode(application.ClientId)}</code></p>" + + (secret is null + ? "<p class=\"note\">A public client has no secret: it proves itself with PKCE only.</p>" + : $"<label>Client secret</label><p><code>{HtmlPage.Encode(secret)}</code></p>" + + "<p class=\"error\">Copy the secret now. It is stored only as a hash and is never shown again; " + + "if it is lost, make a new one.</p>") + + $"<p><a href=\"/developers/{Uri.EscapeDataString(application.ClientId)}\">Go to the application</a></p>"; + return HtmlPage.Render(context, title, body); + } + + private static IResult RenderDetails( + HttpContext context, + RegisteredApplication application, + IReadOnlyDictionary<string, string> errors, + string? saved) + { + string path = $"/developers/{Uri.EscapeDataString(application.ClientId)}"; + string secretForm = application.IsPublic + ? string.Empty + : HtmlPage.Form(context, path + "/secret", + "<button class=\"secondary\" type=\"submit\">Make a new client secret</button>") + + "<p class=\"note\">The old secret stops working at once.</p>"; + string body = + (saved is null ? string.Empty : $"<p role=\"status\">{HtmlPage.Encode(saved)}</p>") + + FormContent(context, application.DisplayName, path, + new ApplicationInput(application.DisplayName, application.Homepage, application.IsPublic, + application.RedirectUris, application.PostLogoutRedirectUris, application.Scopes, + application.AllowClientCredentials), + isNew: false, errors, application.ClientId) + + "<h2>Secret</h2>" + secretForm + + "<h2>Delete</h2>" + + HtmlPage.Form(context, path + "/delete", + "<p class=\"note\">Deleting the application ends every authorization and token it holds.</p>" + + "<button class=\"danger\" type=\"submit\">Delete the application</button>") + + "<p><a href=\"/developers\">Back</a></p>"; + return HtmlPage.Render(context, application.DisplayName, body); + } + + private static IResult RenderForm( + HttpContext context, + string title, + string action, + ApplicationInput input, + bool isNew, + IReadOnlyDictionary<string, string> errors, + int statusCode = StatusCodes.Status200OK) => + HtmlPage.Render(context, title, + FormContent(context, title, action, input, isNew, errors, null) + "<p><a href=\"/developers\">Back</a></p>", + statusCode); + + private static string FormContent( + HttpContext context, + string title, + string action, + ApplicationInput input, + bool isNew, + IReadOnlyDictionary<string, string> errors, + string? clientId) + { + string Error(string field) => HtmlPage.Error(errors.TryGetValue(field, out string? message) ? message : null); + string type = isNew + ? "<label>Type</label>" + + $"<label class=\"check\"><input type=\"radio\" name=\"clientType\" value=\"confidential\"{(input.IsPublic ? "" : " checked")}> " + + "Confidential: a server that keeps a client secret</label>" + + $"<label class=\"check\"><input type=\"radio\" name=\"clientType\" value=\"public\"{(input.IsPublic ? " checked" : "")}> " + + "Public: a browser or native application without a secret</label>" + : $"<p class=\"note\">{(input.IsPublic ? "Public" : "Confidential")} client · " + + $"<code>{HtmlPage.Encode(clientId)}</code></p>"; + string scopes = string.Concat(OAuthScopes.All.Select(scope => + $"<label class=\"check\"><input type=\"checkbox\" name=\"scope\" value=\"{HtmlPage.Encode(scope.Name)}\"" + + $"{(input.Scopes.Contains(scope.Name) ? " checked" : "")}> <code>{HtmlPage.Encode(scope.Name)}</code> " + + $"{HtmlPage.Encode(scope.Consent)}</label>")); + string fields = + type + + "<label for=\"displayName\">Name</label>" + Error("displayName") + + $"<input id=\"displayName\" name=\"displayName\" type=\"text\" required maxlength=\"{ApplicationPolicy.MaximumDisplayNameLength}\" value=\"{HtmlPage.Encode(input.DisplayName)}\">" + + "<label for=\"homepage\">Homepage (optional)</label>" + Error("homepage") + + $"<input id=\"homepage\" name=\"homepage\" type=\"url\" value=\"{HtmlPage.Encode(input.Homepage)}\">" + + "<label for=\"redirectUris\">Redirection addresses, one per line</label>" + Error("redirectUris") + + $"<textarea id=\"redirectUris\" name=\"redirectUris\" required>{HtmlPage.Encode(string.Join('\n', input.RedirectUris))}</textarea>" + + "<label for=\"postLogoutRedirectUris\">Addresses after sign-out (optional)</label>" + + Error("postLogoutRedirectUris") + + $"<textarea id=\"postLogoutRedirectUris\" name=\"postLogoutRedirectUris\">{HtmlPage.Encode(string.Join('\n', input.PostLogoutRedirectUris))}</textarea>" + + "<label>Scopes the application may request</label>" + Error("scopes") + scopes + + "<p class=\"note\"><code>openid</code> is always available.</p>" + + "<label>Service access</label>" + Error("allowClientCredentials") + + $"<label class=\"check\"><input type=\"checkbox\" name=\"allowClientCredentials\"{(input.AllowClientCredentials ? " checked" : "")}> " + + "Allow the client credentials grant (confidential clients only)</label>" + + $"<button type=\"submit\">{(isNew ? "Register" : "Save")}</button>"; + return $"<h1>{HtmlPage.Encode(title)}</h1>" + HtmlPage.Form(context, action, fields); + } + + private static IResult NotFound(HttpContext context) => HtmlPage.Render(context, "Not found", + "<h1>Not found</h1><p>No application of yours has this client identifier.</p>" + + "<p><a href=\"/developers\">Back</a></p>", StatusCodes.Status404NotFound); +} diff --git a/apps/api/OAuth/Endpoints/AuthorizationEndpoints.cs b/apps/api/OAuth/Endpoints/AuthorizationEndpoints.cs new file mode 100644 index 0000000..aa964da --- /dev/null +++ b/apps/api/OAuth/Endpoints/AuthorizationEndpoints.cs @@ -0,0 +1,290 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Collections.Immutable; +using System.Security.Claims; +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; +using Microsoft.IdentityModel.Tokens; +using OpenIddict.Abstractions; +using OpenIddict.Server.AspNetCore; +using OpenIddict.Validation.AspNetCore; +using Progmasoft.OAuth.Developers; +using Progmasoft.OAuth.Pages; +using Progmasoft.Progmaweb.Api.Accounts; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth.Endpoints; + +/// <summary>The protocol endpoints OpenIddict passes through: authorization, token, user information, end session.</summary> +/// <remarks> +/// OpenIddict validates every request before it reaches these handlers: the client, its redirection address, its +/// permissions, PKCE and the requested scopes. The handlers decide who the account is and what it allowed. +/// </remarks> +internal static class AuthorizationEndpoints +{ + /// <summary>Maps the endpoints.</summary> + /// <param name="app">The application.</param> + public static void MapAuthorizationEndpoints(this WebApplication app) + { + app.MapMethods("/connect/authorize", ["GET", "POST"], AuthorizeAsync).RequireRateLimiting("oauth"); + app.MapPost("/connect/token", TokenAsync).RequireRateLimiting("oauth"); + app.MapMethods("/connect/userinfo", ["GET", "POST"], UserInfo) + .RequireAuthorization(new AuthorizeAttribute + { + AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme + }); + app.MapMethods("/connect/logout", ["GET", "POST"], (Delegate)LogoutAsync); + } + + private static async Task<IResult> AuthorizeAsync( + HttpContext context, + IOpenIddictApplicationManager applications, + IOpenIddictAuthorizationManager authorizations, + ApplicationRegistry registry, + AccountService accounts) + { + OpenIddictRequest request = context.GetOpenIddictServerRequest() + ?? throw new InvalidOperationException("OpenIddict did not pass a request."); + + AccountRecord? account = await OAuthAccount.CurrentAsync(context); + if (account is null || request.HasPromptValue(PromptValues.Login)) + { + if (request.HasPromptValue(PromptValues.None)) + { + return Forbid(Errors.LoginRequired, "The account holder is not signed in."); + } + + if (account is not null) + { + await context.SignOutAsync(OAuthRegistration.CookieScheme); + } + + // The parameters come back to this endpoint after the sign-in, without prompt=login, which would + // otherwise send the account holder to the sign-in page for ever. + IEnumerable<KeyValuePair<string, string?>> parameters = request.GetParameters() + .Where(parameter => parameter.Key != Parameters.Prompt) + .Select(parameter => new KeyValuePair<string, string?>(parameter.Key, parameter.Value.ToString())); + return Results.Challenge( + new AuthenticationProperties { RedirectUri = "/connect/authorize" + QueryString.Create(parameters) }, + [OAuthRegistration.CookieScheme]); + } + + object application = await applications.FindByClientIdAsync(request.ClientId!, context.RequestAborted) + ?? throw new InvalidOperationException("OpenIddict passed an unknown client."); + string applicationId = (await applications.GetIdAsync(application, context.RequestAborted))!; + ImmutableArray<string> scopes = request.GetScopes(); + + object? authorization = null; + await foreach (object existing in authorizations.FindAsync( + account.Id.ToString(), applicationId, Statuses.Valid, AuthorizationTypes.Permanent, scopes, + context.RequestAborted)) + { + authorization = existing; + break; + } + + string? decision = context.Request.HasFormContentType + ? (await context.Request.ReadFormAsync(context.RequestAborted))["decision"].ToString() + : null; + if (!string.IsNullOrEmpty(decision)) + { + if (!await OAuthAccount.IsGenuineFormAsync(context)) + { + return Results.BadRequest(); + } + + if (decision != "allow") + { + return Forbid(Errors.AccessDenied, "The account holder did not allow the application."); + } + + ClaimsIdentity identity = CreateIdentity(account, scopes); + authorization = await authorizations.CreateAsync( + identity, account.Id.ToString(), applicationId, AuthorizationTypes.Permanent, scopes, + context.RequestAborted); + return Issue(identity, await authorizations.GetIdAsync(authorization, context.RequestAborted)); + } + + if (authorization is not null && !request.HasPromptValue(PromptValues.Consent)) + { + return Issue(CreateIdentity(account, scopes), + await authorizations.GetIdAsync(authorization, context.RequestAborted)); + } + + if (request.HasPromptValue(PromptValues.None)) + { + return Forbid(Errors.ConsentRequired, "The account holder has not allowed these scopes yet."); + } + + return await ConsentPageAsync(context, request, application, applicationId, account, applications, registry, + accounts); + } + + private static async Task<IResult> ConsentPageAsync( + HttpContext context, + OpenIddictRequest request, + object application, + string applicationId, + AccountRecord account, + IOpenIddictApplicationManager applications, + ApplicationRegistry registry, + AccountService accounts) + { + string name = await applications.GetDisplayNameAsync(application, context.RequestAborted) ?? request.ClientId!; + Guid? ownerId = await registry.FindOwnerAsync(applicationId, context.RequestAborted); + AccountRecord? owner = ownerId is { } id ? await accounts.FindAsync(id, context.RequestAborted) : null; + Uri redirect = new(request.RedirectUri!); + + string grants = "<li>Know which Progmasoft account you use.</li>" + string.Concat(request.GetScopes() + .Select(OAuthScopes.Find) + .Where(scope => scope is not null) + .Select(scope => $"<li>{HtmlPage.Encode(scope!.Consent)}</li>")); + string hidden = string.Concat(request.GetParameters() + .Where(parameter => parameter.Key != Parameters.Prompt) + .Select(parameter => HtmlPage.Hidden(parameter.Key, parameter.Value.ToString()))); + string buttons = + "<div class=\"row\"><button type=\"submit\" name=\"decision\" value=\"allow\">Allow</button>" + + "<button class=\"secondary\" type=\"submit\" name=\"decision\" value=\"deny\">Deny</button></div>"; + string body = + $"<h1>Allow {HtmlPage.Encode(name)}?</h1>" + + $"<p><strong>{HtmlPage.Encode(name)}</strong>" + + (owner is null ? string.Empty : $", registered by <strong>{HtmlPage.Encode(owner.AccountName)}</strong>,") + + " wants to:</p>" + + $"<ul>{grants}</ul>" + + $"<p class=\"note\">You will be sent back to <code>{HtmlPage.Encode(redirect.GetLeftPart(UriPartial.Authority))}</code>. " + + $"Signed in as {HtmlPage.Encode(account.AccountName)}. You can withdraw this at any time under " + + "<a href=\"/account/applications\">Applications you have allowed</a>.</p>" + + HtmlPage.Form(context, "/connect/authorize", hidden + buttons); + return HtmlPage.Render(context, "Allow access", body); + } + + private static async Task<IResult> TokenAsync( + HttpContext context, + IOpenIddictApplicationManager applications, + AccountService accounts) + { + OpenIddictRequest request = context.GetOpenIddictServerRequest() + ?? throw new InvalidOperationException("OpenIddict did not pass a request."); + + if (request.IsAuthorizationCodeGrantType() || request.IsRefreshTokenGrantType()) + { + AuthenticateResult result = + await context.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + string? subject = result.Principal?.GetClaim(Claims.Subject); + AccountRecord? account = Guid.TryParse(subject, out Guid id) + ? await accounts.FindAsync(id, context.RequestAborted) + : null; + if (account is null) + { + return Forbid(Errors.InvalidGrant, "The account no longer exists."); + } + + // The claims are written again, so that a renamed account or a changed address reaches the client with + // the next refresh, and a refresh never grants more than the original authorization. + ClaimsIdentity identity = CreateIdentity(account, result.Principal!.GetScopes()); + return Issue(identity, result.Principal!.GetAuthorizationId()); + } + + if (request.IsClientCredentialsGrantType()) + { + // A client credentials token names the application itself, not an account, so no account scope can be + // granted with it. + if (!request.GetScopes().IsEmpty) + { + return Forbid(Errors.InvalidScope, + "The client credentials grant acts as the application and takes no account scope."); + } + + object application = await applications.FindByClientIdAsync(request.ClientId!, context.RequestAborted) + ?? throw new InvalidOperationException("OpenIddict passed an unknown client."); + ClaimsIdentity identity = new(TokenValidationParameters.DefaultAuthenticationType, Claims.Name, Claims.Role); + identity.SetClaim(Claims.Subject, request.ClientId); + identity.SetClaim(Claims.Name, await applications.GetDisplayNameAsync(application, context.RequestAborted)); + identity.SetDestinations(_ => [Destinations.AccessToken]); + return Results.SignIn(new ClaimsPrincipal(identity), null, + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + } + + return Forbid(Errors.UnsupportedGrantType, "This grant type is not supported."); + } + + private static IResult UserInfo(HttpContext context) + { + ClaimsPrincipal principal = context.User; + Dictionary<string, object> claims = new(StringComparer.Ordinal) + { + [Claims.Subject] = principal.GetClaim(Claims.Subject)! + }; + if (principal.HasScope(Scopes.Profile)) + { + claims[Claims.Name] = principal.GetClaim(Claims.Name)!; + claims[Claims.PreferredUsername] = principal.GetClaim(Claims.PreferredUsername)!; + } + + if (principal.HasScope(Scopes.Email)) + { + claims[Claims.Email] = principal.GetClaim(Claims.Email)!; + claims[Claims.EmailVerified] = false; + } + + return Results.Ok(claims); + } + + private static async Task<IResult> LogoutAsync(HttpContext context) + { + await context.SignOutAsync(OAuthRegistration.CookieScheme); + // OpenIddict sends the account holder to post_logout_redirect_uri when the client registered it. + return Results.SignOut(new AuthenticationProperties { RedirectUri = "/" }, + [OpenIddictServerAspNetCoreDefaults.AuthenticationScheme]); + } + + /// <summary>The identity of an account, with the claims the granted scopes allow.</summary> + /// <param name="account">The account.</param> + /// <param name="scopes">The granted scopes.</param> + /// <returns>The identity.</returns> + private static ClaimsIdentity CreateIdentity(AccountRecord account, ImmutableArray<string> scopes) + { + ClaimsIdentity identity = new(TokenValidationParameters.DefaultAuthenticationType, Claims.Name, Claims.Role); + identity.SetClaim(Claims.Subject, account.Id.ToString()); + if (scopes.Contains(Scopes.Profile)) + { + identity.SetClaim(Claims.Name, account.AccountName); + identity.SetClaim(Claims.PreferredUsername, account.AccountName); + } + + if (scopes.Contains(Scopes.Email)) + { + identity.SetClaim(Claims.Email, account.Email); + // Registration does not verify the address; a client must not treat it as proven. + identity.SetClaim(Claims.EmailVerified, false); + } + + identity.SetScopes(scopes); + identity.SetResources(OAuthScopes.ResourcesOf(scopes)); + identity.SetDestinations(claim => claim.Type switch + { + Claims.Subject => [Destinations.AccessToken, Destinations.IdentityToken], + Claims.Name or Claims.PreferredUsername or Claims.Email or Claims.EmailVerified => + [Destinations.AccessToken, Destinations.IdentityToken], + _ => [Destinations.AccessToken] + }); + return identity; + } + + private static IResult Issue(ClaimsIdentity identity, string? authorizationId) + { + identity.SetAuthorizationId(authorizationId); + return Results.SignIn(new ClaimsPrincipal(identity), null, + OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + } + + private static IResult Forbid(string error, string description) => Results.Forbid( + new AuthenticationProperties(new Dictionary<string, string?> + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = error, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = description + }), + [OpenIddictServerAspNetCoreDefaults.AuthenticationScheme]); +} diff --git a/apps/api/OAuth/OAuthEndpoints.cs b/apps/api/OAuth/OAuthEndpoints.cs new file mode 100644 index 0000000..fa6409c --- /dev/null +++ b/apps/api/OAuth/OAuthEndpoints.cs @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using Progmasoft.OAuth.Developers; +using Progmasoft.OAuth.Endpoints; +using Progmasoft.OAuth.Pages; + +namespace Progmasoft.OAuth; + +/// <summary>Maps every page and endpoint of Progmasoft OAuth.</summary> +internal static class OAuthEndpoints +{ + /// <summary>Maps the pages and endpoints. <see cref="OAuthHostFilter"/> keeps them on the OAuth host.</summary> + /// <param name="app">The application.</param> + public static void MapProgmasoftOAuth(this WebApplication app) + { + app.MapSignInPages(); + app.MapAuthorizationEndpoints(); + app.MapDeveloperPortal(); + app.MapAllowedApplications(); + } +} diff --git a/apps/api/OAuth/OAuthHostFilter.cs b/apps/api/OAuth/OAuthHostFilter.cs new file mode 100644 index 0000000..ce9cbfc --- /dev/null +++ b/apps/api/OAuth/OAuthHostFilter.cs @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using Microsoft.Extensions.Options; + +namespace Progmasoft.OAuth; + +/// <summary>Keeps Progmasoft OAuth on its own host, and the account API off it.</summary> +/// <remarks> +/// <para> +/// The account API and the OAuth provider run in one process. OpenIddict answers its endpoints on any host, so this +/// filter, placed before authentication, answers 404 for an OAuth path on another host: tokens are only ever issued +/// under the issuer's own name. On the OAuth host it answers 404 for everything but the OAuth paths and +/// <c>/health</c>, so that the account API, whose cookies belong to the account site, is not reachable there. +/// </para> +/// <para>Nginx routes the hosts the same way; this keeps the rule when a request reaches the process directly.</para> +/// </remarks> +/// <param name="next">The next middleware.</param> +/// <param name="options">The settings that name the OAuth host.</param> +internal sealed class OAuthHostFilter(RequestDelegate next, IOptions<OAuthOptions> options) +{ + /// <summary>Paths that only the OAuth host serves; a path is matched with its sub-paths.</summary> + private static readonly string[] OAuthPaths = + [ + "/connect", + "/.well-known/openid-configuration", + "/.well-known/oauth-authorization-server", + "/.well-known/jwks", + "/signin", + "/signout", + "/developers", + "/account/applications" + ]; + + /// <summary>Answers 404 for a request on the wrong host, and passes the others on.</summary> + /// <param name="context">The request.</param> + /// <returns>A task that completes when the request has been answered.</returns> + public Task InvokeAsync(HttpContext context) + { + PathString path = context.Request.Path; + bool onOAuthHost = string.Equals(context.Request.Host.Host, options.Value.Host, StringComparison.OrdinalIgnoreCase); + bool isOAuthPath = OAuthPaths.Any(prefix => path.StartsWithSegments(prefix, StringComparison.OrdinalIgnoreCase)); + bool allowed = onOAuthHost + ? isOAuthPath || path == "/" || path.StartsWithSegments("/health", StringComparison.OrdinalIgnoreCase) + : !isOAuthPath; + if (allowed) + { + return next(context); + } + + context.Response.StatusCode = StatusCodes.Status404NotFound; + return Task.CompletedTask; + } +} diff --git a/apps/api/OAuth/OAuthOptions.cs b/apps/api/OAuth/OAuthOptions.cs new file mode 100644 index 0000000..7e32712 --- /dev/null +++ b/apps/api/OAuth/OAuthOptions.cs @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +namespace Progmasoft.OAuth; + +/// <summary>Settings of Progmasoft OAuth, the OAuth 2.1 and OpenID Connect provider of Progmasoft accounts.</summary> +internal sealed class OAuthOptions +{ + /// <summary>The configuration section of these settings.</summary> + public const string SectionName = "OAuth"; + + /// <summary>The host name Progmasoft OAuth answers on; the issuer is <c>https://{Host}/</c>.</summary> + public string Host { get; set; } = "credentials.progmasoft.com"; + + /// <summary> + /// PEM file with the RSA private key that signs identity and access tokens. Required in production; other + /// environments use a key that lives as long as the process. + /// </summary> + public string? SigningKeyPath { get; set; } + + /// <summary> + /// File with the base64 text of the 256-bit key that encrypts access tokens, authorization codes and refresh + /// tokens. Required in production, like <see cref="SigningKeyPath"/>. + /// </summary> + public string? EncryptionKeyPath { get; set; } + + /// <summary>Where a visitor without an account creates one.</summary> + public string RegistrationUrl { get; set; } = "https://account.progmasoft.com/register"; + + /// <summary>How many applications one account may register.</summary> + public int MaximumApplicationsPerAccount { get; set; } = 10; + + /// <summary>The issuer, derived from <see cref="Host"/>.</summary> + public Uri Issuer => new($"https://{Host}/"); +} diff --git a/apps/api/OAuth/OAuthRegistration.cs b/apps/api/OAuth/OAuthRegistration.cs new file mode 100644 index 0000000..d604d4c --- /dev/null +++ b/apps/api/OAuth/OAuthRegistration.cs @@ -0,0 +1,253 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Security.Cryptography; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; +using Npgsql; +using Progmasoft.OAuth.Developers; +using Progmasoft.OAuth.Storage; +using Progmasoft.Progmaweb.Api.Accounts; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth; + +/// <summary>Registers Progmasoft OAuth: its tables, the OpenIddict server, its sign-in cookie and its pages.</summary> +internal static class OAuthRegistration +{ + /// <summary>The cookie scheme of an account signed in to Progmasoft OAuth.</summary> + /// <remarks> + /// It is separate from the session of the account site: signing in here opens no account-site session, and the + /// cookie is a <c>__Host-</c> cookie of the OAuth host only. + /// </remarks> + public const string CookieScheme = "ProgmasoftOAuth"; + + /// <summary>How long a sign-in to Progmasoft OAuth lasts.</summary> + public static readonly TimeSpan SignInLifetime = TimeSpan.FromHours(8); + + /// <summary>Adds the services of Progmasoft OAuth.</summary> + /// <param name="services">The service collection.</param> + /// <param name="configuration">The configuration of the service.</param> + /// <param name="accountStore">Where the accounts are kept; the OAuth tables are kept in the same place.</param> + /// <param name="isProduction">Whether the service runs in production, where the token keys are required.</param> + /// <returns>The settings, as the pipeline needs them.</returns> + public static OAuthOptions AddProgmasoftOAuth( + this IServiceCollection services, + IConfiguration configuration, + AccountStoreKind accountStore, + bool isProduction) + { + IConfigurationSection section = configuration.GetSection(OAuthOptions.SectionName); + OAuthOptions settings = section.Get<OAuthOptions>() ?? new OAuthOptions(); + services.Configure<OAuthOptions>(section); + + // With the memory account store the OAuth tables live in an in-memory SQLite database, one per process, which + // a kept-open connection holds alive and every context opens again by name. SQLite, unlike Entity + // Framework's in-memory provider, runs the bulk updates OpenIddict uses to revoke a reused refresh token's + // chain, so development and the tests exercise the same revocation as production. + string memoryDatabase = + $"Data Source=progmasoft-oauth-{Guid.NewGuid():N};Mode=Memory;Cache=Shared"; + services.AddDbContext<OAuthDbContext>(options => + { + if (accountStore is AccountStoreKind.PostgreSql) + { + options.UseNpgsql(configuration.GetConnectionString(AccountStoreRegistration.ConnectionStringName)); + } + else + { + options.UseSqlite(memoryDatabase); + } + + options.UseOpenIddict(); + }); + if (accountStore is AccountStoreKind.PostgreSql) + { + // Registered after the account schema, which it refers to. + services.AddHostedService<OAuthSchemaInitializer>(); + } + else + { + services.AddSingleton(new MemoryOAuthDatabase(memoryDatabase)); + services.AddHostedService<MemoryOAuthDatabaseInitializer>(); + } + + services.AddOpenIddict() + .AddCore(core => core.UseEntityFrameworkCore().UseDbContext<OAuthDbContext>()) + .AddServer(server => + { + server.SetIssuer(settings.Issuer); + server.SetAuthorizationEndpointUris("connect/authorize") + .SetTokenEndpointUris("connect/token") + .SetUserInfoEndpointUris("connect/userinfo") + .SetEndSessionEndpointUris("connect/logout") + .SetRevocationEndpointUris("connect/revoke") + .SetIntrospectionEndpointUris("connect/introspect"); + + // OAuth 2.1: the authorization code with PKCE for every client, refresh tokens, and client + // credentials for services. The implicit and password grants are not offered at all. + server.AllowAuthorizationCodeFlow() + .AllowRefreshTokenFlow() + .AllowClientCredentialsFlow(); + server.RequireProofKeyForCodeExchange(); + // OAuth 2.1 allows only the S256 challenge; "plain" would put the verifier itself in the browser. + server.Configure(options => options.CodeChallengeMethods.Remove(CodeChallengeMethods.Plain)); + + server.RegisterScopes( + [Scopes.OpenId, .. OAuthScopes.All.Select(scope => scope.Name)]); + server.RegisterClaims( + Claims.Subject, Claims.Name, Claims.PreferredUsername, Claims.Email, Claims.EmailVerified); + + server.SetAuthorizationCodeLifetime(TimeSpan.FromMinutes(2)) + .SetAccessTokenLifetime(TimeSpan.FromMinutes(15)) + .SetIdentityTokenLifetime(TimeSpan.FromMinutes(15)) + .SetRefreshTokenLifetime(TimeSpan.FromDays(30)) + // OAuth 2.1 refresh token rotation: a refresh token that was used once is refused, and its reuse + // revokes the whole chain. OpenIddict tolerates reuse for 30 seconds unless told otherwise. + .SetRefreshTokenReuseLeeway(TimeSpan.Zero); + + AddKeys(server, settings, isProduction); + + server.UseAspNetCore() + .EnableAuthorizationEndpointPassthrough() + .EnableTokenEndpointPassthrough() + .EnableUserInfoEndpointPassthrough() + .EnableEndSessionEndpointPassthrough() + .EnableStatusCodePagesIntegration(); + }) + .AddValidation(validation => + { + validation.UseLocalServer(); + validation.UseAspNetCore(); + }); + + services.AddAuthentication() + .AddCookie(CookieScheme, options => + { + options.Cookie.Name = "__Host-ProgmasoftOAuth"; + options.Cookie.HttpOnly = true; + options.Cookie.IsEssential = true; + // Lax, so that the redirect back from the sign-in page to the authorization endpoint carries it. + options.Cookie.SameSite = SameSiteMode.Lax; + options.Cookie.SecurePolicy = CookieSecurePolicy.Always; + options.ExpireTimeSpan = SignInLifetime; + options.SlidingExpiration = false; + options.LoginPath = "/signin"; + options.LogoutPath = "/signout"; + options.AccessDeniedPath = "/signin"; + }); + services.AddAntiforgery(options => + { + options.Cookie.Name = "__Host-ProgmasoftOAuthForm"; + options.Cookie.SecurePolicy = CookieSecurePolicy.Always; + options.Cookie.SameSite = SameSiteMode.Strict; + options.FormFieldName = "form-token"; + }); + services.AddScoped<ApplicationRegistry>(); + return settings; + } + + /// <summary>Adds the keys that sign and encrypt tokens.</summary> + /// <remarks> + /// Production reads both keys from files outside the release, so that tokens survive a restart and a new + /// release. Every other environment makes keys that live as long as the process. + /// </remarks> + /// <param name="server">The OpenIddict server builder.</param> + /// <param name="settings">The settings that name the key files.</param> + /// <param name="isProduction">Whether the service runs in production.</param> + /// <exception cref="InvalidOperationException">A key file is missing in production.</exception> + private static void AddKeys(OpenIddictServerBuilder server, OAuthOptions settings, bool isProduction) + { + if (string.IsNullOrWhiteSpace(settings.SigningKeyPath) || string.IsNullOrWhiteSpace(settings.EncryptionKeyPath)) + { + if (isProduction) + { + throw new InvalidOperationException( + $"{OAuthOptions.SectionName}:{nameof(OAuthOptions.SigningKeyPath)} and " + + $"{OAuthOptions.SectionName}:{nameof(OAuthOptions.EncryptionKeyPath)} must name the token key " + + "files in production."); + } + + server.AddEphemeralSigningKey().AddEphemeralEncryptionKey(); + return; + } + + RSA signing = RSA.Create(); + signing.ImportFromPem(File.ReadAllText(settings.SigningKeyPath)); + // A key identifier derived from the public key lets clients pick the key of a token from the key set. + byte[] publicKey = signing.ExportSubjectPublicKeyInfo(); + server.AddSigningKey(new RsaSecurityKey(signing) + { + KeyId = Base64UrlEncoder.Encode(SHA256.HashData(publicKey)[..16]) + }); + + byte[] encryption = Convert.FromBase64String(File.ReadAllText(settings.EncryptionKeyPath).Trim()); + if (encryption.Length != 32) + { + throw new InvalidOperationException("The OAuth encryption key must be 256 bits, written as base64."); + } + + server.AddEncryptionKey(new SymmetricSecurityKey(encryption)); + } +} + +/// <summary>Brings the OAuth tables to the current schema before the service accepts requests.</summary> +/// <param name="dataSource">Connections to the database of the accounts.</param> +/// <param name="logger">Receives what was done.</param> +internal sealed class OAuthSchemaInitializer( + NpgsqlDataSource dataSource, + ILogger<OAuthSchemaInitializer> logger) : IHostedService +{ + /// <summary>Writes the schema version and the number of steps taken at this start.</summary> + private static readonly Action<ILogger, int, int, Exception?> SchemaReport = LoggerMessage.Define<int, int>( + LogLevel.Information, + new EventId(20, "OAuthSchema"), + "The OAuth tables are at schema version {Version}; {Taken} step(s) were taken at this start."); + + /// <inheritdoc/> + public async Task StartAsync(CancellationToken cancellationToken) + { + int taken = await OAuthSchema.ApplyAsync(dataSource, cancellationToken); + SchemaReport(logger, OAuthSchema.CurrentVersion, taken, null); + } + + /// <inheritdoc/> + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} + +/// <summary>Keeps the in-memory SQLite database of the OAuth tables alive for the lifetime of the process.</summary> +/// <remarks>A shared in-memory SQLite database exists as long as one connection to it is open.</remarks> +internal sealed class MemoryOAuthDatabase : IDisposable +{ + private readonly SqliteConnection keeper; + + /// <summary>Opens the connection that holds the database.</summary> + /// <param name="connectionString">The connection string of the shared in-memory database.</param> + public MemoryOAuthDatabase(string connectionString) + { + keeper = new SqliteConnection(connectionString); + keeper.Open(); + } + + /// <inheritdoc/> + public void Dispose() => keeper.Dispose(); +} + +/// <summary>Creates the OAuth tables in the in-memory database before the service accepts requests.</summary> +/// <param name="database">The connection that keeps the database alive.</param> +/// <param name="services">Creates the scope of the context.</param> +internal sealed class MemoryOAuthDatabaseInitializer(MemoryOAuthDatabase database, IServiceProvider services) + : IHostedService +{ + /// <inheritdoc/> + public async Task StartAsync(CancellationToken cancellationToken) + { + GC.KeepAlive(database); + await using AsyncServiceScope scope = services.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService<OAuthDbContext>().Database.EnsureCreatedAsync(cancellationToken); + } + + /// <inheritdoc/> + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/apps/api/OAuth/OAuthScopes.cs b/apps/api/OAuth/OAuthScopes.cs new file mode 100644 index 0000000..c19a339 --- /dev/null +++ b/apps/api/OAuth/OAuthScopes.cs @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth; + +/// <summary>One permission an application can ask an account for.</summary> +/// <param name="Name">The scope value of the OAuth request.</param> +/// <param name="Consent">What the consent page tells the account holder the application will be able to do.</param> +/// <param name="Resource"> +/// The audience of the access tokens that carry the scope, or <see langword="null"/> when only Progmasoft +/// Credentials itself serves the scope. +/// </param> +internal sealed record OAuthScope(string Name, string Consent, string? Resource); + +/// <summary>The scopes of Progmasoft OAuth.</summary> +/// <remarks> +/// Each scope grants one thing, so that an application asks only for what it needs and the account holder sees each +/// grant on its own line of the consent page. <c>openid</c> is not listed: it is the OpenID Connect request itself +/// and grants nothing but the account identifier. +/// </remarks> +internal static class OAuthScopes +{ + /// <summary>The audience of the ViGet scopes; ViGet accepts only access tokens issued for it.</summary> + public const string VigetResource = "viget"; + + /// <summary>Reading the packages the account has published.</summary> + public const string VigetPackagesRead = "viget.packages.read"; + + /// <summary>Publishing packages under the account.</summary> + public const string VigetPackagesPublish = "viget.packages.publish"; + + /// <summary>Yanking packages of the account.</summary> + public const string VigetPackagesYank = "viget.packages.yank"; + + /// <summary>Every scope an application may request besides <c>openid</c>, in the order the consent page lists them.</summary> + public static IReadOnlyList<OAuthScope> All { get; } = + [ + new(Scopes.Profile, "Read your Progmasoft account name.", null), + new(Scopes.Email, "Read the email address you sign in and registered with.", null), + new(VigetPackagesRead, "Read the packages you have published on ViGet.", VigetResource), + new(VigetPackagesPublish, "Publish packages to ViGet under your account.", VigetResource), + new(VigetPackagesYank, "Yank packages you have published on ViGet.", VigetResource), + new(Scopes.OfflineAccess, "Keep this access when you are not signed in, until you revoke it.", null), + ]; + + /// <summary>Finds a scope by its name.</summary> + /// <param name="name">The scope value.</param> + /// <returns>The scope, or <see langword="null"/> when Progmasoft OAuth has no such scope.</returns> + public static OAuthScope? Find(string name) => All.FirstOrDefault(scope => scope.Name == name); + + /// <summary>The audiences of a set of scopes.</summary> + /// <param name="scopes">Scope values that were granted.</param> + /// <returns>Each audience once.</returns> + public static IEnumerable<string> ResourcesOf(IEnumerable<string> scopes) => scopes + .Select(Find) + .Where(scope => scope?.Resource is not null) + .Select(scope => scope!.Resource!) + .Distinct(StringComparer.Ordinal); +} diff --git a/apps/api/OAuth/Pages/AllowedApplicationsEndpoints.cs b/apps/api/OAuth/Pages/AllowedApplicationsEndpoints.cs new file mode 100644 index 0000000..f442b3c --- /dev/null +++ b/apps/api/OAuth/Pages/AllowedApplicationsEndpoints.cs @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Collections.Immutable; +using OpenIddict.Abstractions; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth.Pages; + +/// <summary>The applications an account has allowed, and withdrawing an allowance.</summary> +internal static class AllowedApplicationsEndpoints +{ + /// <summary>Maps the pages.</summary> + /// <param name="app">The application.</param> + public static void MapAllowedApplications(this WebApplication app) + { + app.MapGet("/account/applications", ListAsync); + app.MapPost("/account/applications/{authorizationId}/revoke", RevokeAsync); + } + + private static async Task<IResult> ListAsync( + HttpContext context, + IOpenIddictAuthorizationManager authorizations, + IOpenIddictApplicationManager applications) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInFirst(context); + } + + List<string> rows = []; + await foreach (object authorization in authorizations.FindBySubjectAsync(account.Id.ToString(), + context.RequestAborted)) + { + if (!await authorizations.HasStatusAsync(authorization, Statuses.Valid, context.RequestAborted) + || !await authorizations.HasTypeAsync(authorization, AuthorizationTypes.Permanent, context.RequestAborted)) + { + continue; + } + + string? applicationId = await authorizations.GetApplicationIdAsync(authorization, context.RequestAborted); + object? application = applicationId is null + ? null + : await applications.FindByIdAsync(applicationId, context.RequestAborted); + string name = application is null + ? "A deleted application" + : await applications.GetDisplayNameAsync(application, context.RequestAborted) ?? "An application"; + ImmutableArray<string> scopes = await authorizations.GetScopesAsync(authorization, context.RequestAborted); + string id = (await authorizations.GetIdAsync(authorization, context.RequestAborted))!; + DateTimeOffset? created = await authorizations.GetCreationDateAsync(authorization, context.RequestAborted); + string grants = string.Join(", ", scopes.Select(scope => $"<code>{HtmlPage.Encode(scope)}</code>")); + rows.Add( + $"<li><strong>{HtmlPage.Encode(name)}</strong> " + + $"<span class=\"note\">since {created:yyyy-MM-dd}</span><br>{grants}" + + HtmlPage.Form(context, $"/account/applications/{Uri.EscapeDataString(id)}/revoke", + "<button class=\"secondary\" type=\"submit\">Withdraw</button>") + "</li>"); + } + + string body = "<h1>Applications you have allowed</h1>" + + (rows.Count == 0 ? "<p>You have not allowed any application.</p>" : $"<ul>{string.Concat(rows)}</ul>") + + "<p class=\"note\">Withdrawing ends the application's access tokens and refresh tokens at once; " + + "it will have to ask you again.</p><p><a href=\"/\">Back</a></p>"; + return HtmlPage.Render(context, "Allowed applications", body); + } + + private static async Task<IResult> RevokeAsync( + HttpContext context, + IOpenIddictAuthorizationManager authorizations, + IOpenIddictTokenManager tokens, + string authorizationId) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInFirst(context); + } + + if (!await OAuthAccount.IsGenuineFormAsync(context)) + { + return Results.BadRequest(); + } + + object? authorization = await authorizations.FindByIdAsync(authorizationId, context.RequestAborted); + // Another account's authorization is treated as absent. + if (authorization is not null + && await authorizations.GetSubjectAsync(authorization, context.RequestAborted) == account.Id.ToString()) + { + await authorizations.TryRevokeAsync(authorization, context.RequestAborted); + await tokens.RevokeByAuthorizationIdAsync(authorizationId, context.RequestAborted); + } + + return Results.Redirect("/account/applications"); + } +} diff --git a/apps/api/OAuth/Pages/HtmlPage.cs b/apps/api/OAuth/Pages/HtmlPage.cs new file mode 100644 index 0000000..a471f80 --- /dev/null +++ b/apps/api/OAuth/Pages/HtmlPage.cs @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Security.Cryptography; +using System.Text; +using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Antiforgery; + +namespace Progmasoft.OAuth.Pages; + +/// <summary>Renders the pages of Progmasoft OAuth: plain HTML forms, no script.</summary> +/// <remarks> +/// The pages need no JavaScript, so the content security policy allows none. The one stylesheet is inline and +/// allowed by its digest. The policy has no <c>form-action</c>: a form here posts to this host, and the +/// redirection that follows a consent goes to the address the application registered, which browsers would check +/// against <c>form-action</c> as well. +/// </remarks> +internal static class HtmlPage +{ + /// <summary>The stylesheet of every page.</summary> + internal const string Stylesheet = + "body{margin:0;font:16px/1.5 system-ui,-apple-system,'Segoe UI',sans-serif;color:#1d1d1f;background:#f6f7f9}" + + "main{max-width:34rem;margin:3rem auto;padding:2rem;background:#fff;border:1px solid #dcdfe4;border-radius:12px}" + + "h1{font-size:1.5rem;margin:0 0 1rem}h2{font-size:1.1rem;margin:1.5rem 0 .5rem}" + + "label{display:block;margin:.75rem 0 .25rem;font-weight:600}" + + "input[type=text],input[type=email],input[type=password],input[type=url],textarea{box-sizing:border-box;" + + "width:100%;padding:.55rem .65rem;border:1px solid #b8bec8;border-radius:8px;font:inherit}" + + "textarea{min-height:5rem}button{margin-top:1rem;padding:.55rem 1rem;border:0;border-radius:8px;" + + "background:#1f4fd6;color:#fff;font:inherit;cursor:pointer}button.secondary{background:#e5e8ee;color:#1d1d1f}" + + "button.danger{background:#b3261e}.error{color:#b3261e}.note{color:#5b6270;font-size:.9rem}" + + "code{font:14px ui-monospace,SFMono-Regular,Consolas,monospace;background:#eef0f4;padding:.1rem .3rem;" + + "border-radius:4px;word-break:break-all}ul{padding-left:1.2rem}a{color:#1f4fd6}" + + ".row{display:flex;gap:.5rem;flex-wrap:wrap}.check{font-weight:400}" + + "@media(prefers-color-scheme:dark){body{background:#121316;color:#e8e9ec}main{background:#1b1d22;" + + "border-color:#30343c}input[type=text],input[type=email],input[type=password],input[type=url],textarea" + + "{background:#121316;color:#e8e9ec;border-color:#454a54}code{background:#262a31}a{color:#8fb0ff}" + + "button.secondary{background:#30343c;color:#e8e9ec}.note{color:#a3a9b5}}"; + + /// <summary>The content security policy source that allows <see cref="Stylesheet"/>.</summary> + internal static readonly string StylesheetSource = + "'sha256-" + Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(Stylesheet))) + "'"; + + /// <summary>Encodes text for an HTML element or attribute.</summary> + /// <param name="text">The text.</param> + /// <returns>The encoded text.</returns> + public static string Encode(string? text) => HtmlEncoder.Default.Encode(text ?? string.Empty); + + /// <summary>Answers with a page.</summary> + /// <param name="context">The request.</param> + /// <param name="title">The title of the page.</param> + /// <param name="body">The content of the page, already encoded.</param> + /// <param name="statusCode">The status of the response.</param> + /// <returns>The result.</returns> + public static IResult Render(HttpContext context, string title, string body, int statusCode = 200) + { + IHeaderDictionary headers = context.Response.Headers; + headers.ContentSecurityPolicy = + $"default-src 'none'; style-src {StylesheetSource}; img-src 'self'; frame-ancestors 'none'; base-uri 'none'"; + headers.CacheControl = "no-store"; + string html = + "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">" + + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" + + "<meta name=\"robots\" content=\"noindex\">" + + $"<title>{Encode(title)} · Progmasoft</title><style>{Stylesheet}</style></head>" + + $"<body><main>{body}</main></body></html>"; + return Results.Content(html, "text/html; charset=utf-8", Encoding.UTF8, statusCode); + } + + /// <summary>A form that posts to this host, with the token that proves it was served here.</summary> + /// <param name="context">The request that renders the form.</param> + /// <param name="action">The path the form posts to.</param> + /// <param name="content">The fields and buttons, already encoded.</param> + /// <returns>The form.</returns> + public static string Form(HttpContext context, string action, string content) + { + IAntiforgery antiforgery = context.RequestServices.GetRequiredService<IAntiforgery>(); + AntiforgeryTokenSet tokens = antiforgery.GetAndStoreTokens(context); + return $"<form method=\"post\" action=\"{Encode(action)}\">" + + $"<input type=\"hidden\" name=\"{Encode(tokens.FormFieldName)}\" value=\"{Encode(tokens.RequestToken)}\">" + + content + "</form>"; + } + + /// <summary>A hidden field.</summary> + /// <param name="name">The name of the field.</param> + /// <param name="value">The value of the field.</param> + /// <returns>The field.</returns> + public static string Hidden(string name, string? value) => + $"<input type=\"hidden\" name=\"{Encode(name)}\" value=\"{Encode(value)}\">"; + + /// <summary>A paragraph that reports an error, or nothing.</summary> + /// <param name="message">The message, or <see langword="null"/>.</param> + /// <returns>The paragraph.</returns> + public static string Error(string? message) => + string.IsNullOrEmpty(message) ? string.Empty : $"<p class=\"error\" role=\"alert\">{Encode(message)}</p>"; +} diff --git a/apps/api/OAuth/Pages/SignInEndpoints.cs b/apps/api/OAuth/Pages/SignInEndpoints.cs new file mode 100644 index 0000000..af739f1 --- /dev/null +++ b/apps/api/OAuth/Pages/SignInEndpoints.cs @@ -0,0 +1,162 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Security.Claims; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Options; +using Progmasoft.Progmaweb.Api.Accounts; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth.Pages; + +/// <summary>The account signed in to Progmasoft OAuth.</summary> +internal static class OAuthAccount +{ + /// <summary>Finds the account of the sign-in cookie.</summary> + /// <remarks>An account that no longer exists ends the sign-in.</remarks> + /// <param name="context">The request.</param> + /// <returns>The account, or <see langword="null"/> when nobody is signed in.</returns> + public static async Task<AccountRecord?> CurrentAsync(HttpContext context) + { + AuthenticateResult result = await context.AuthenticateAsync(OAuthRegistration.CookieScheme); + string? subject = result.Principal?.FindFirst(Claims.Subject)?.Value; + if (!result.Succeeded || !Guid.TryParse(subject, out Guid id)) + { + return null; + } + + AccountService accounts = context.RequestServices.GetRequiredService<AccountService>(); + AccountRecord? account = await accounts.FindAsync(id, context.RequestAborted); + if (account is null) + { + await context.SignOutAsync(OAuthRegistration.CookieScheme); + } + + return account; + } + + /// <summary>Sends a visitor to the sign-in page and back to where they were.</summary> + /// <param name="context">The request.</param> + /// <returns>The redirection.</returns> + public static IResult SignInFirst(HttpContext context) => Results.Redirect( + "/signin?ReturnUrl=" + Uri.EscapeDataString(context.Request.Path + context.Request.QueryString)); + + /// <summary>Whether a form carries the token this host served with it.</summary> + /// <param name="context">The request.</param> + /// <returns><see langword="true"/> when the form is genuine.</returns> + public static Task<bool> IsGenuineFormAsync(HttpContext context) => + context.RequestServices.GetRequiredService<IAntiforgery>().IsRequestValidAsync(context); + + /// <summary>A return address that stays on this host.</summary> + /// <param name="returnUrl">The requested address.</param> + /// <returns>The address, or <c>/</c> when it would leave the host.</returns> + public static string LocalReturnUrl(string? returnUrl) => + !string.IsNullOrEmpty(returnUrl) && returnUrl[0] == '/' && (returnUrl.Length == 1 || + (returnUrl[1] != '/' && returnUrl[1] != '\\')) + ? returnUrl + : "/"; +} + +/// <summary>The home page, the sign-in page and signing out.</summary> +internal static class SignInEndpoints +{ + /// <summary>Maps the pages.</summary> + /// <param name="app">The application.</param> + public static void MapSignInPages(this WebApplication app) + { + app.MapGet("/", (Delegate)HomeAsync); + app.MapGet("/signin", SignInPage); + app.MapPost("/signin", SignInAsync).RequireRateLimiting("account-auth"); + app.MapPost("/signout", (Delegate)SignOutAsync); + } + + private static async Task<IResult> HomeAsync(HttpContext context) + { + AccountRecord? account = await OAuthAccount.CurrentAsync(context); + string body = "<h1>Progmasoft OAuth</h1>" + + "<p>Sign in with Progmasoft: an OAuth 2.1 and OpenID Connect provider for Progmasoft accounts. " + + "Any developer can register an application.</p>"; + if (account is null) + { + body += "<p><a href=\"/signin\">Sign in</a> to register applications or to review the applications you " + + "have allowed.</p>"; + } + else + { + body += $"<p>Signed in as <strong>{HtmlPage.Encode(account.AccountName)}</strong>.</p>" + + "<ul><li><a href=\"/developers\">Your applications</a></li>" + + "<li><a href=\"/account/applications\">Applications you have allowed</a></li></ul>" + + HtmlPage.Form(context, "/signout", "<button class=\"secondary\" type=\"submit\">Sign out</button>"); + } + + body += "<p class=\"note\">Discovery document: <a href=\"/.well-known/openid-configuration\">" + + "/.well-known/openid-configuration</a></p>"; + return HtmlPage.Render(context, "Progmasoft OAuth", body); + } + + private static IResult SignInPage(HttpContext context, IOptions<OAuthOptions> options, string? returnUrl) => + RenderSignIn(context, options.Value, OAuthAccount.LocalReturnUrl(returnUrl), null, null); + + private static async Task<IResult> SignInAsync( + HttpContext context, + AccountService accounts, + IOptions<OAuthOptions> options) + { + if (!await OAuthAccount.IsGenuineFormAsync(context)) + { + return Results.BadRequest(); + } + + IFormCollection form = await context.Request.ReadFormAsync(context.RequestAborted); + string returnUrl = OAuthAccount.LocalReturnUrl(form["returnUrl"]); + string? email = form["email"]; + AccountRecord? account = await accounts.VerifyPasswordAsync(email, form["password"], context.RequestAborted); + if (account is null) + { + // One message for every failure, as the account API gives: it does not tell registered addresses apart. + return RenderSignIn(context, options.Value, returnUrl, email, + "The email address or the password is not right.", StatusCodes.Status401Unauthorized); + } + + ClaimsIdentity identity = new(OAuthRegistration.CookieScheme, Claims.Name, Claims.Role); + identity.AddClaim(new Claim(Claims.Subject, account.Id.ToString())); + identity.AddClaim(new Claim(Claims.Name, account.AccountName)); + await context.SignInAsync(OAuthRegistration.CookieScheme, new ClaimsPrincipal(identity), + new AuthenticationProperties { IsPersistent = false }); + return Results.Redirect(returnUrl); + } + + private static async Task<IResult> SignOutAsync(HttpContext context) + { + if (!await OAuthAccount.IsGenuineFormAsync(context)) + { + return Results.BadRequest(); + } + + await context.SignOutAsync(OAuthRegistration.CookieScheme); + return Results.Redirect("/"); + } + + private static IResult RenderSignIn( + HttpContext context, + OAuthOptions options, + string returnUrl, + string? email, + string? error, + int statusCode = StatusCodes.Status200OK) + { + string fields = + HtmlPage.Hidden("returnUrl", returnUrl) + + "<label for=\"email\">Email address</label>" + + $"<input id=\"email\" name=\"email\" type=\"email\" autocomplete=\"username\" required value=\"{HtmlPage.Encode(email)}\">" + + "<label for=\"password\">Password</label>" + + "<input id=\"password\" name=\"password\" type=\"password\" autocomplete=\"current-password\" required>" + + "<button type=\"submit\">Sign in</button>"; + string body = "<h1>Sign in to Progmasoft</h1>" + HtmlPage.Error(error) + + HtmlPage.Form(context, "/signin", fields) + + $"<p class=\"note\">No account yet? <a href=\"{HtmlPage.Encode(options.RegistrationUrl)}\">" + + "Create a Progmasoft account</a>.</p>"; + return HtmlPage.Render(context, "Sign in", body, statusCode); + } +} diff --git a/apps/api/OAuth/Storage/OAuthDbContext.cs b/apps/api/OAuth/Storage/OAuthDbContext.cs new file mode 100644 index 0000000..76e8544 --- /dev/null +++ b/apps/api/OAuth/Storage/OAuthDbContext.cs @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using Microsoft.EntityFrameworkCore; +using OpenIddict.EntityFrameworkCore.Models; + +namespace Progmasoft.OAuth.Storage; + +/// <summary>The tables of Progmasoft OAuth: OpenIddict's, and who owns each application.</summary> +/// <remarks> +/// The tables are named <c>oauth_*</c> so that they sit next to the account tables of the same database without a +/// clash. <see cref="OAuthSchema"/> creates them; Entity Framework only reads and writes rows. +/// </remarks> +/// <param name="options">Options of the context.</param> +internal sealed class OAuthDbContext(DbContextOptions<OAuthDbContext> options) : DbContext(options) +{ + /// <summary>Which account registered which application.</summary> + public DbSet<ApplicationOwner> ApplicationOwners => Set<ApplicationOwner>(); + + /// <inheritdoc /> + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.UseOpenIddict(); + modelBuilder.Entity<OpenIddictEntityFrameworkCoreApplication>().ToTable("oauth_applications"); + modelBuilder.Entity<OpenIddictEntityFrameworkCoreAuthorization>().ToTable("oauth_authorizations"); + modelBuilder.Entity<OpenIddictEntityFrameworkCoreScope>().ToTable("oauth_scopes"); + modelBuilder.Entity<OpenIddictEntityFrameworkCoreToken>().ToTable("oauth_tokens"); + modelBuilder.Entity<ApplicationOwner>(owner => + { + owner.ToTable("oauth_application_owners"); + owner.HasKey(entry => entry.ApplicationId); + owner.HasIndex(entry => entry.AccountId); + owner.HasOne<OpenIddictEntityFrameworkCoreApplication>() + .WithMany() + .HasForeignKey(entry => entry.ApplicationId) + .OnDelete(DeleteBehavior.Cascade); + }); + } +} + +/// <summary>The account that registered an application and may change or delete it.</summary> +internal sealed class ApplicationOwner +{ + /// <summary>Identifier of the OpenIddict application.</summary> + public string ApplicationId { get; set; } = string.Empty; + + /// <summary>Identifier of the owning account.</summary> + public Guid AccountId { get; set; } + + /// <summary>When the application was registered.</summary> + public DateTimeOffset CreatedAt { get; set; } +} diff --git a/apps/api/OAuth/Storage/OAuthSchema.cs b/apps/api/OAuth/Storage/OAuthSchema.cs new file mode 100644 index 0000000..c591a29 --- /dev/null +++ b/apps/api/OAuth/Storage/OAuthSchema.cs @@ -0,0 +1,204 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using Npgsql; + +namespace Progmasoft.OAuth.Storage; + +/// <summary>The tables of <see cref="OAuthDbContext"/> and the steps that bring a database to them.</summary> +/// <remarks> +/// <para> +/// The same numbered steps as the account tables, in a version table of their own: a database records the steps it +/// has taken in <c>oauth_schema_versions</c>, and <see cref="ApplyAsync"/> takes the missing ones in one +/// transaction. A step is never edited after it has been released. +/// </para> +/// <para> +/// Step 1 is the script Entity Framework generates for <see cref="OAuthDbContext"/>, so that the tables are exactly +/// what OpenIddict's stores read and write; a test compares the two. The steps run after the account steps, since +/// an application owner refers to an account. +/// </para> +/// </remarks> +internal static class OAuthSchema +{ + /// <summary>Key of the advisory lock that lets one process at a time change these tables.</summary> + private const long MigrationLockKey = 0x50726F4F41757468; + + /// <summary>The statements Entity Framework generates for the model, as step 1 holds them.</summary> + internal const string ModelScript = + """ + CREATE TABLE oauth_applications ( + "Id" text NOT NULL, + "ApplicationType" character varying(50), + "ClientId" character varying(100), + "ClientSecret" text, + "ClientType" character varying(50), + "ConcurrencyToken" character varying(50), + "ConsentType" character varying(50), + "DisplayName" text, + "DisplayNames" text, + "JsonWebKeySet" text, + "Permissions" text, + "PostLogoutRedirectUris" text, + "Properties" text, + "RedirectUris" text, + "Requirements" text, + "Settings" text, + CONSTRAINT "PK_oauth_applications" PRIMARY KEY ("Id") + ); + + CREATE TABLE oauth_scopes ( + "Id" text NOT NULL, + "ConcurrencyToken" character varying(50), + "Description" text, + "Descriptions" text, + "DisplayName" text, + "DisplayNames" text, + "Name" character varying(200), + "Properties" text, + "Resources" text, + CONSTRAINT "PK_oauth_scopes" PRIMARY KEY ("Id") + ); + + CREATE TABLE oauth_application_owners ( + "ApplicationId" text NOT NULL, + "AccountId" uuid NOT NULL, + "CreatedAt" timestamp with time zone NOT NULL, + CONSTRAINT "PK_oauth_application_owners" PRIMARY KEY ("ApplicationId"), + CONSTRAINT "FK_oauth_application_owners_oauth_applications_ApplicationId" FOREIGN KEY ("ApplicationId") REFERENCES oauth_applications ("Id") ON DELETE CASCADE + ); + + CREATE TABLE oauth_authorizations ( + "Id" text NOT NULL, + "ApplicationId" text, + "ConcurrencyToken" character varying(50), + "CreationDate" timestamp with time zone, + "Properties" text, + "Scopes" text, + "Status" character varying(50), + "Subject" character varying(400), + "Type" character varying(50), + CONSTRAINT "PK_oauth_authorizations" PRIMARY KEY ("Id"), + CONSTRAINT "FK_oauth_authorizations_oauth_applications_ApplicationId" FOREIGN KEY ("ApplicationId") REFERENCES oauth_applications ("Id") + ); + + CREATE TABLE oauth_tokens ( + "Id" text NOT NULL, + "ApplicationId" text, + "AuthorizationId" text, + "ConcurrencyToken" character varying(50), + "CreationDate" timestamp with time zone, + "ExpirationDate" timestamp with time zone, + "Payload" text, + "Properties" text, + "RedemptionDate" timestamp with time zone, + "ReferenceId" character varying(100), + "Status" character varying(50), + "Subject" character varying(400), + "Type" character varying(150), + CONSTRAINT "PK_oauth_tokens" PRIMARY KEY ("Id"), + CONSTRAINT "FK_oauth_tokens_oauth_applications_ApplicationId" FOREIGN KEY ("ApplicationId") REFERENCES oauth_applications ("Id"), + CONSTRAINT "FK_oauth_tokens_oauth_authorizations_AuthorizationId" FOREIGN KEY ("AuthorizationId") REFERENCES oauth_authorizations ("Id") + ); + + CREATE INDEX "IX_oauth_application_owners_AccountId" ON oauth_application_owners ("AccountId"); + + CREATE UNIQUE INDEX "IX_oauth_applications_ClientId" ON oauth_applications ("ClientId"); + + CREATE INDEX "IX_oauth_authorizations_ApplicationId_Status_Subject_Type" ON oauth_authorizations ("ApplicationId", "Status", "Subject", "Type"); + + CREATE UNIQUE INDEX "IX_oauth_scopes_Name" ON oauth_scopes ("Name"); + + CREATE INDEX "IX_oauth_tokens_ApplicationId_Status_Subject_Type" ON oauth_tokens ("ApplicationId", "Status", "Subject", "Type"); + + CREATE INDEX "IX_oauth_tokens_AuthorizationId" ON oauth_tokens ("AuthorizationId"); + + CREATE UNIQUE INDEX "IX_oauth_tokens_ReferenceId" ON oauth_tokens ("ReferenceId"); + """; + + /// <summary>The steps, in order. The version of a step is its position, counted from one.</summary> + private static readonly string[] Steps = + [ + // 1: OpenIddict's applications, authorizations, scopes and tokens, and the owners of applications. Deleting + // an account deletes its ownership rows; the applications themselves are deleted through the portal. + ModelScript + """ + + ALTER TABLE oauth_application_owners + ADD CONSTRAINT oauth_application_owners_account_fk + FOREIGN KEY ("AccountId") REFERENCES accounts (id) ON DELETE CASCADE; + """ + ]; + + /// <summary>The version a database has after every step.</summary> + public static int CurrentVersion => Steps.Length; + + /// <summary>Takes the steps a database has not taken yet.</summary> + /// <remarks> + /// Processes that start together wait for one another on an advisory lock, so each step is taken once. A + /// database that is newer than this program is refused. + /// </remarks> + /// <param name="dataSource">Connections to the database.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>The number of steps that were taken; zero when the database was current.</returns> + /// <exception cref="InvalidOperationException">The database has taken steps this program does not know.</exception> + public static async Task<int> ApplyAsync(NpgsqlDataSource dataSource, CancellationToken cancellationToken) + { + await using NpgsqlConnection connection = await dataSource.OpenConnectionAsync(cancellationToken); + await using NpgsqlTransaction transaction = await connection.BeginTransactionAsync(cancellationToken); + + await ExecuteAsync(connection, transaction, $"SELECT pg_advisory_xact_lock({MigrationLockKey})", cancellationToken); + await ExecuteAsync( + connection, + transaction, + """ + CREATE TABLE IF NOT EXISTS oauth_schema_versions ( + version integer PRIMARY KEY, + applied_at timestamptz NOT NULL DEFAULT now() + ) + """, + cancellationToken); + + int version; + await using (NpgsqlCommand read = new( + "SELECT coalesce(max(version), 0) FROM oauth_schema_versions", connection, transaction)) + { + version = (int)(await read.ExecuteScalarAsync(cancellationToken))!; + } + + if (version > Steps.Length) + { + throw new InvalidOperationException( + $"The OAuth tables are at schema version {version}, and this program knows version {Steps.Length}. " + + "Run the release that created them, or a newer one."); + } + + int taken = 0; + for (int step = version; step < Steps.Length; step++) + { + await ExecuteAsync(connection, transaction, Steps[step], cancellationToken); + await using NpgsqlCommand record = new( + "INSERT INTO oauth_schema_versions (version) VALUES ($1)", connection, transaction); + record.Parameters.AddWithValue(step + 1); + await record.ExecuteNonQueryAsync(cancellationToken); + taken++; + } + + await transaction.CommitAsync(cancellationToken); + return taken; + } + + /// <summary>Runs statements that return nothing.</summary> + /// <param name="connection">The connection to run them on.</param> + /// <param name="transaction">The transaction they belong to.</param> + /// <param name="sql">The statements.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>A task that completes when the statements have run.</returns> + private static async Task ExecuteAsync( + NpgsqlConnection connection, + NpgsqlTransaction transaction, + string sql, + CancellationToken cancellationToken) + { + await using NpgsqlCommand command = new(sql, connection, transaction); + await command.ExecuteNonQueryAsync(cancellationToken); + } +} diff --git a/apps/api/Progmaweb.Api.csproj b/apps/api/Progmaweb.Api.csproj index 29086cb..3e18bf0 100644 --- a/apps/api/Progmaweb.Api.csproj +++ b/apps/api/Progmaweb.Api.csproj @@ -13,7 +13,11 @@ </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="10.0.11" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.13" /> <PackageReference Include="Npgsql" Version="10.0.3" /> + <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" /> + <PackageReference Include="OpenIddict.AspNetCore" Version="7.7.2" /> + <PackageReference Include="OpenIddict.EntityFrameworkCore" Version="7.7.2" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Progmaweb.Api.Tests" /> diff --git a/apps/api/Program.cs b/apps/api/Program.cs index 31b46a2..aeeff29 100644 --- a/apps/api/Program.cs +++ b/apps/api/Program.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Google; using Microsoft.AspNetCore.HttpOverrides; using Progmasoft.Progmaweb.Api.Accounts; +using Progmasoft.OAuth; using Progmasoft.Progmaweb.Api.Security; WebApplicationBuilder builder = WebApplication.CreateBuilder(args); @@ -18,6 +19,9 @@ AccountStoreKind accountStore = builder.Services.AddAccountStore( builder.Environment.IsProduction()); builder.Services.AddSingleton<AccountService>(); builder.Services.AddSingleton<SessionService>(); +// Progmasoft OAuth, the OAuth 2.1 and OpenID Connect provider on its own host; see OAuth/OAuthRegistration.cs. +builder.Services.AddProgmasoftOAuth(builder.Configuration, accountStore, builder.Environment.IsProduction()); +builder.Services.AddAuthorization(); AuthenticationBuilder authentication = builder.Services .AddAuthentication() .AddCookie(AccountEndpoints.ExternalCookieScheme, options => @@ -66,6 +70,19 @@ builder.Services.AddHealthChecks(); builder.Services.AddRateLimiter(options => { options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + // The OAuth endpoints and the developer portal: generous for real clients, a ceiling for scripted abuse. + options.AddPolicy("oauth", context => + { + string partition = context.Connection.RemoteIpAddress?.ToString() ?? "unknown"; + return RateLimitPartition.GetSlidingWindowLimiter(partition, _ => new SlidingWindowRateLimiterOptions + { + AutoReplenishment = true, + PermitLimit = 60, + QueueLimit = 0, + SegmentsPerWindow = 6, + Window = TimeSpan.FromMinutes(1) + }); + }); options.AddPolicy("account-auth", context => { string partition = context.Connection.RemoteIpAddress?.ToString() ?? "unknown"; @@ -99,7 +116,10 @@ if (!app.Environment.IsDevelopment()) app.UseHttpsRedirection(); app.UseMiddleware<SecurityHeadersMiddleware>(); +// Before authentication, where OpenIddict answers its own endpoints: OAuth only on its host, and nothing else there. +app.UseMiddleware<OAuthHostFilter>(); app.UseAuthentication(); +app.UseAuthorization(); app.UseRateLimiter(); app.UseExceptionHandler(); @@ -111,6 +131,7 @@ app.MapGet("/api/v1/status", () => Results.Ok(new version = "1.0.0" })); app.MapAccountEndpoints(); +app.MapProgmasoftOAuth(); app.Run(); diff --git a/apps/api/appsettings.Development.json b/apps/api/appsettings.Development.json index cedca2b..b91cc83 100644 --- a/apps/api/appsettings.Development.json +++ b/apps/api/appsettings.Development.json @@ -5,6 +5,6 @@ "Microsoft.AspNetCore": "Information" } }, - "AllowedHosts": "localhost;127.0.0.1;account.localhost" + "AllowedHosts": "localhost;127.0.0.1;account.localhost;credentials.localhost" } diff --git a/apps/api/appsettings.json b/apps/api/appsettings.json index e6b208a..1bbeb26 100644 --- a/apps/api/appsettings.json +++ b/apps/api/appsettings.json @@ -5,7 +5,7 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com", + "AllowedHosts": "localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com;credentials.progmasoft.com", "AccountSessions": { "LifetimeHours": 720, "CookieName": "__Host-ProgmasoftSession" diff --git a/apps/api/packages.lock.json b/apps/api/packages.lock.json index 70c33f8..f0c6781 100644 --- a/apps/api/packages.lock.json +++ b/apps/api/packages.lock.json @@ -8,11 +8,451 @@ "resolved": "10.0.11", "contentHash": "v/OZld8HxGa5hudLWiChuCf5asMrE36n19sR1RK5cC65SGJoYvQAcwnz3yoAOLDSw90PYc3hgFCh1FW83sakUg==" }, + "Microsoft.EntityFrameworkCore.Sqlite": { + "type": "Direct", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13", + "Microsoft.Extensions.DependencyModel": "10.0.13", + "SQLitePCLRaw.bundle_e_sqlite3": "2.1.13", + "SQLitePCLRaw.core": "2.1.13" + } + }, "Npgsql": { "type": "Direct", "requested": "[10.0.3, )", "resolved": "10.0.3", "contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==" + }, + "Npgsql.EntityFrameworkCore.PostgreSQL": { + "type": "Direct", + "requested": "[10.0.3, )", + "resolved": "10.0.3", + "contentHash": "IPGrrZnRkuW7OlHDhUESZz4G5DLkW7Nej/O3Cx+0iTsgyU5XJxBgpsvTHLloo3WWuAKKbDHXBvWPVkX1deRh1Q==", + "dependencies": { + "Microsoft.EntityFrameworkCore": "[10.0.4, 11.0.0)", + "Microsoft.EntityFrameworkCore.Relational": "[10.0.4, 11.0.0)", + "Npgsql": "10.0.3" + } + }, + "OpenIddict.AspNetCore": { + "type": "Direct", + "requested": "[7.7.2, )", + "resolved": "7.7.2", + "contentHash": "b6cqAcvJfo0OhKVD7YZkfwcRq7PsXCAb39MaHE+/NGHZ9thmXH9VtlLEdxdH5nnH4pdsWppqsLJ3cprfr9gJrA==", + "dependencies": { + "OpenIddict": "7.7.2", + "OpenIddict.Client.AspNetCore": "7.7.2", + "OpenIddict.Client.DataProtection": "7.7.2", + "OpenIddict.Server.AspNetCore": "7.7.2", + "OpenIddict.Server.DataProtection": "7.7.2", + "OpenIddict.Validation.AspNetCore": "7.7.2", + "OpenIddict.Validation.DataProtection": "7.7.2" + } + }, + "OpenIddict.EntityFrameworkCore": { + "type": "Direct", + "requested": "[7.7.2, )", + "resolved": "7.7.2", + "contentHash": "OspAqs92TbxK80Oakuo2olN0w8ZkozqjaqDXkEmS6Z2fHTE3kF3JhCjVUnFMpgHoVqTVrlcxUPJAaiYxxB17Zw==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Relational": "10.0.11", + "OpenIddict.Core": "7.7.2", + "OpenIddict.EntityFrameworkCore.Models": "7.7.2" + } + }, + "Microsoft.Bcl.Cryptography": { + "type": "Transitive", + "resolved": "10.0.2", + "contentHash": "LG9Yll3B5aNpxv0+D47g6LiOiKBIlodhcHdQwcYzo8VeexFLGqx5ymetmA2aBRyo9cCcWsQWrFsdbsr8LvmWDw==" + }, + "Microsoft.Data.Sqlite.Core": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "Gge8XsSCOwcbkbdmt2UDAe6kIv9Q0vA6yb3wsTStjjexaMFLTWfc/1gH4kbhJ+zWiXRTRA4lG2sOQNVfir204w==", + "dependencies": { + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.EntityFrameworkCore": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "u/z4nTQUJ5nJEXAQekgQEQZkh0delp4gL+ESHn7Z6k037c8HC5mSNu1/YdBgxGm7DtLjhOxktNl+aQMzw6wN7A==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Abstractions": "10.0.13", + "Microsoft.EntityFrameworkCore.Analyzers": "10.0.13" + } + }, + "Microsoft.EntityFrameworkCore.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "ARw+tZ3eiTosnK5nJPUGEzeUQcjyqCqs3qKA3lPtIRH5yJo3qIgxm7AvkZVIT9iWkS2083UsWe3Rj1MysW3p5A==" + }, + "Microsoft.EntityFrameworkCore.Analyzers": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zBx6VeEz/hkhlm0BJ2V+9xebUuDDIszcKvurJceQHuZPEXuXubrL6Lneo9VZiliRyJbQlB2oNKLkJXd3gHteQA==" + }, + "Microsoft.EntityFrameworkCore.Relational": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "QU/sbTtDR5wVAJRVecC1GwM7mwH8bvKOZNm+lulzMr5rhjdb8DDEFIqqdhF08JIo51DPv5uQdZ1nXoZsD5pTag==", + "dependencies": { + "Microsoft.EntityFrameworkCore": "10.0.13" + } + }, + "Microsoft.EntityFrameworkCore.Sqlite.Core": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==", + "dependencies": { + "Microsoft.Data.Sqlite.Core": "10.0.13", + "Microsoft.EntityFrameworkCore.Relational": "10.0.13", + "Microsoft.Extensions.DependencyModel": "10.0.13", + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.Extensions.AmbientMetadata.Application": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "/FYCIyhRLrDwIg29tB/21/Rp7XMaEP/gWR5Cxyi4GgWcN/v/XXUpU52yhQux0s2SQy1Z0C1wnhptCMvLaaT45Q==" + }, + "Microsoft.Extensions.Compliance.Abstractions": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "7I0DXMTCqpXpXg+SLLDlfedtv6DN5Lgiv+PR3MclzqKPOHNB17YP42KMNI61ckSrffh0xsuIqQyCIjvWc6vUuw==" + }, + "Microsoft.Extensions.DependencyInjection.AutoActivation": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "LXwOAsnrflu2ln+Bxj7y3Zc/Pn4HquCCRzW81oOIuRsM8F75TxwA/ZpSFZ5E1+YkVpndz7BcHY4ThFSjjA4vbQ==" + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ==" + }, + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "tXmzwQeWgiycaLOtvSFnz0TPkJxXTyZrkwSVPTr83FgSiMj3BD/8eIbvrpGi5rzc2AgfKyegKo1ntJlJFey1Zg==" + }, + "Microsoft.Extensions.Http.Diagnostics": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "2pYnolFkigH7N6A5WHdGx93iZ8dIhrBnu4ZkjvB6RwbHzYmIy/iXVe12pdrViNDdeBSmKZ5FA9YP/xhwLT7q7A==", + "dependencies": { + "Microsoft.Extensions.Telemetry": "10.8.0" + } + }, + "Microsoft.Extensions.Http.Polly": { + "type": "Transitive", + "resolved": "10.0.11", + "contentHash": "DIxaTXWdbjRJihAIutpDIgPbpD9PwW8lW0EIawlNH4zs7coCgwPnd9rYlzXYkuKKphnjcKYlo6gXFeg6z15GLg==", + "dependencies": { + "Polly": "7.2.4", + "Polly.Extensions.Http": "3.0.0" + } + }, + "Microsoft.Extensions.Http.Resilience": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "XtbZyYVxSNn1Aj2Z0PA8yauS12hPszTWDZ3GtZ5Vww7Ai3d8Pm841jMBnTvoTf1t9mRf3eSB38V5KUWxH6/4oQ==", + "dependencies": { + "Microsoft.Extensions.Http.Diagnostics": "10.8.0", + "Microsoft.Extensions.Resilience": "10.8.0" + } + }, + "Microsoft.Extensions.Resilience": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "RH/gv0ZcCnQ3d30lxb8+T2o661TwZq/K5eMwp488goQLX1QYqWN3i8L8XlN9DhrqP2Zcf0EtsWaKpJO3yHDUTw==", + "dependencies": { + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.8.0", + "Microsoft.Extensions.Telemetry.Abstractions": "10.8.0", + "Polly.Extensions": "8.4.2", + "Polly.RateLimiting": "8.4.2" + } + }, + "Microsoft.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "IIWjDZguUJt6yNld9J4V88xuOUzpC76wBwfnRJLRmacmyTTl9jA8+KP5PuHPi7CKz/Vk/q+lQYmobiopuzapzA==", + "dependencies": { + "Microsoft.Extensions.AmbientMetadata.Application": "10.8.0", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.8.0", + "Microsoft.Extensions.Telemetry.Abstractions": "10.8.0" + } + }, + "Microsoft.Extensions.Telemetry.Abstractions": { + "type": "Transitive", + "resolved": "10.8.0", + "contentHash": "XHlOerNKjVrPJqbuFi196tyFhS7eNMoPUC800xJmCGsSiruE/goGoKyBKzS1HeelAGnoFPFrS+LgNitXNeEYRQ==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "10.8.0" + } + }, + "Microsoft.IdentityModel.Abstractions": { + "type": "Transitive", + "resolved": "8.19.2", + "contentHash": "HJbo/lnSfNHUfphPRT910poQc4T2/9+8svFLvzuaYHGAOJ2Tu+oEDqpX0BVP3BJ4OuUM1kylEKyaiX2fCAK3Cw==" + }, + "Microsoft.IdentityModel.JsonWebTokens": { + "type": "Transitive", + "resolved": "8.19.2", + "contentHash": "ui3fuBT4fs8kdKfBthI4NzLYIBIneEVS8UrL1JVBzAn80UiKmngBBi0BEByE7n/9c+EElcfFlCMFFTqpkBSLNA==", + "dependencies": { + "Microsoft.IdentityModel.Tokens": "8.19.2" + } + }, + "Microsoft.IdentityModel.Logging": { + "type": "Transitive", + "resolved": "8.19.2", + "contentHash": "r5YLDIxGOnkVJHrqXv/iD1FM1CgGrQOdriXuvuWvTPmKbnGANhEysq9XKmN6IHjf2a+9bAGEpnoRBsAQlvJU5w==", + "dependencies": { + "Microsoft.IdentityModel.Abstractions": "8.19.2" + } + }, + "Microsoft.IdentityModel.Protocols": { + "type": "Transitive", + "resolved": "8.19.2", + "contentHash": "sGxSsSrZXNmca6D+jHH2rVRyo2nNRd/g4H9CFbPmLLq0xgoH1U0orLWE5minfijw7+zq49tBs7txenbfAErRoQ==", + "dependencies": { + "Microsoft.IdentityModel.Tokens": "8.19.2" + } + }, + "Microsoft.IdentityModel.Tokens": { + "type": "Transitive", + "resolved": "8.19.2", + "contentHash": "GtPC1S02uH1gOO4fQ+zRysIicKmEXaYFP8PIkdJYXqMyruYhopre4ozVHp0XiDSA0+GJvOZH9prxCPvgBMg4Ww==", + "dependencies": { + "Microsoft.Bcl.Cryptography": "10.0.2", + "Microsoft.IdentityModel.Logging": "8.19.2" + } + }, + "OpenIddict": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "XMCdZzYZY7CRn3HgLheDI5aMuL6Tit1xO7VaiDVH/qz2Tf295RCbgpBCDcMRh3QYYBqi7RTJIiIKpqhlky91UQ==", + "dependencies": { + "OpenIddict.Abstractions": "7.7.2", + "OpenIddict.Client": "7.7.2", + "OpenIddict.Client.SystemIntegration": "7.7.2", + "OpenIddict.Client.SystemNetHttp": "7.7.2", + "OpenIddict.Client.WebIntegration": "7.7.2", + "OpenIddict.Core": "7.7.2", + "OpenIddict.Server": "7.7.2", + "OpenIddict.Validation": "7.7.2", + "OpenIddict.Validation.ServerIntegration": "7.7.2", + "OpenIddict.Validation.SystemNetHttp": "7.7.2" + } + }, + "OpenIddict.Abstractions": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "rt5feUxOneeZ15jz2koGFVbLWA9gbDu4yPgr9nArFx6YpwP+iaNZHENTi44pTxCXo6wMBaeaApjn1ZMvCu3EEw==", + "dependencies": { + "Microsoft.IdentityModel.Tokens": "8.19.2" + } + }, + "OpenIddict.Client": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "KontwqVvIJeuHilCTwVoCGu2C82To0qWGf+CSG3/iTdX6P8TLVP1pFrOsGzsdtIv/iQNU32mY+ODHcpfb5w6yg==", + "dependencies": { + "Microsoft.IdentityModel.JsonWebTokens": "8.19.2", + "Microsoft.IdentityModel.Protocols": "8.19.2", + "OpenIddict.Abstractions": "7.7.2" + } + }, + "OpenIddict.Client.AspNetCore": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "a98jz1NJOeRHUnapuIAnNh+vtq2TYKE04Ui+xP+jPTT6SXMK1CHx99sjivV//DCmjppeAl8MCpjitWCpCnvdDQ==", + "dependencies": { + "OpenIddict.Client": "7.7.2" + } + }, + "OpenIddict.Client.DataProtection": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "Yy+wKySBdjB7PCvCFP+YHDWBsgmzNbRHbpl9CoOy5tjRrWJ2OQvZg/4Wchw1bYBSri521d/IIloTp3HsZMXmNQ==", + "dependencies": { + "OpenIddict.Client": "7.7.2" + } + }, + "OpenIddict.Client.SystemIntegration": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "4Do/ynyqKdVPyY4yu/mnIxz4YAe9gc9sIMiSrra+yl1Sj0RZytOTvCcV/3r8/wJWOqsnYsg/W/lkiG8AKfq5Xg==", + "dependencies": { + "OpenIddict.Client": "7.7.2" + } + }, + "OpenIddict.Client.SystemNetHttp": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "u7Kw197UetHPvnGosaAWXmfjnP0F4OsvQG+vqyv58eJBmIs3zJKo+80AHYfs/CpOKjgZSIA56WnhStqZr5MflA==", + "dependencies": { + "Microsoft.Extensions.Http.Polly": "10.0.11", + "Microsoft.Extensions.Http.Resilience": "10.8.0", + "OpenIddict.Client": "7.7.2" + } + }, + "OpenIddict.Client.WebIntegration": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "7abzcKwUkVjMJLLamTNwE73RWLjzMKp3Fj972aQLte7XyYPKG8ZC4gMgZBPcSrL2EE/+hhemPjm8C07Yr10Gaw==", + "dependencies": { + "OpenIddict.Client": "7.7.2", + "OpenIddict.Client.SystemNetHttp": "7.7.2" + } + }, + "OpenIddict.Core": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "VsPYuXWx1YtbKFyW/O2vV/egJtTXmAOUE7AJq+I/laT3WIroeiDqHT8jDnhjIhDjHcjfNupR/u5nhWD6t5ocqg==", + "dependencies": { + "OpenIddict.Abstractions": "7.7.2" + } + }, + "OpenIddict.EntityFrameworkCore.Models": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "ESK3iS3UJR4XBDlX0YTgiE24xWM7QfO6AtoJphMx1zLhzup5JUOEXyoosP8Z/vh4B1/cj+QUTz+314Us7/hqCg==" + }, + "OpenIddict.Server": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "azPkMKSMTSlvIKwdesbSaHvTdaNWndqrw/e6P9lyP5/6QG5IhrTK3y2rHWQlv14EU9xG/YegLimP61zapq+ocg==", + "dependencies": { + "Microsoft.IdentityModel.JsonWebTokens": "8.19.2", + "OpenIddict.Abstractions": "7.7.2" + } + }, + "OpenIddict.Server.AspNetCore": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "Nde/hqZbxCbhP8KE5laXbLzsgMFEClaAPL3hiGUezob6ixsq5ga84yQ4aPVrI35sD8Cd6BOh74DkqwvWwZRrfg==", + "dependencies": { + "OpenIddict.Server": "7.7.2" + } + }, + "OpenIddict.Server.DataProtection": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "TYzZUTRNAYOSHP8mJ0qq+R+N0AWDTDSycHEZhC/qVtjBjT0J7GMTVheBP2fhfHksleAsYNLpNuAIYK27rzTqGA==", + "dependencies": { + "OpenIddict.Server": "7.7.2" + } + }, + "OpenIddict.Validation": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "B5hHtkAZsayfci4uUFmaNF2onJ/WllYbbb94oZyhG/759VB6S6f04Humye7q8dRJa1VoEN7P3I/ep32aCofQLQ==", + "dependencies": { + "Microsoft.IdentityModel.JsonWebTokens": "8.19.2", + "Microsoft.IdentityModel.Protocols": "8.19.2", + "OpenIddict.Abstractions": "7.7.2" + } + }, + "OpenIddict.Validation.AspNetCore": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "amZ0SwrgqqUZUsQbGks3qKSlAMybv0YaqbT97hS2Ph3R/IcdTFTXe770LMR32MI6TxWKvEVWCMO+itqEIJCykw==", + "dependencies": { + "OpenIddict.Validation": "7.7.2" + } + }, + "OpenIddict.Validation.DataProtection": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "y5nCO4MGWnMffUA8NiPo7Td7S/JX1MnrbZqLAoof0ZPDqgKp0a8pYrfbRRLwUWd2xLRUJuODXRnsw6I4EbuAEA==", + "dependencies": { + "OpenIddict.Validation": "7.7.2" + } + }, + "OpenIddict.Validation.ServerIntegration": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "2h1LlTkWScAFQoYaKBJ3sbAd3lM7o0gRux0XLg+8D//3Bqlla6p9VjM53DrdnyGWQ1wK3x8cmFcEqDTPePoGZw==", + "dependencies": { + "OpenIddict.Server": "7.7.2", + "OpenIddict.Validation": "7.7.2" + } + }, + "OpenIddict.Validation.SystemNetHttp": { + "type": "Transitive", + "resolved": "7.7.2", + "contentHash": "aEIceyMGX92VokcMBGsJtongfs1z2yQma745CPPWq0Uk9exUqitvXbPm+7TGM0lNh7Fh8hB8QhvNPctDQcIqAg==", + "dependencies": { + "Microsoft.Extensions.Http.Polly": "10.0.11", + "Microsoft.Extensions.Http.Resilience": "10.8.0", + "OpenIddict.Validation": "7.7.2" + } + }, + "Polly": { + "type": "Transitive", + "resolved": "7.2.4", + "contentHash": "bw00Ck5sh6ekduDE3mnCo1ohzuad946uslCDEENu3091+6UKnBuKLo4e+yaNcCzXxOZCXWY2gV4a35+K1d4LDA==" + }, + "Polly.Core": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" + }, + "Polly.Extensions": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", + "dependencies": { + "Polly.Core": "8.4.2" + } + }, + "Polly.Extensions.Http": { + "type": "Transitive", + "resolved": "3.0.0", + "contentHash": "drrG+hB3pYFY7w1c3BD+lSGYvH2oIclH8GRSehgfyP5kjnFnHKQuuBhuHLv+PWyFuaTDyk/vfRpnxOzd11+J8g==", + "dependencies": { + "Polly": "7.1.0" + } + }, + "Polly.RateLimiting": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", + "dependencies": { + "Polly.Core": "8.4.2" + } + }, + "SQLitePCLRaw.bundle_e_sqlite3": { + "type": "Transitive", + "resolved": "2.1.13", + "contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==", + "dependencies": { + "SQLitePCLRaw.lib.e_sqlite3": "2.1.13", + "SQLitePCLRaw.provider.e_sqlite3": "2.1.13" + } + }, + "SQLitePCLRaw.core": { + "type": "Transitive", + "resolved": "2.1.13", + "contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q==" + }, + "SQLitePCLRaw.lib.e_sqlite3": { + "type": "Transitive", + "resolved": "2.1.13", + "contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A==" + }, + "SQLitePCLRaw.provider.e_sqlite3": { + "type": "Transitive", + "resolved": "2.1.13", + "contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==", + "dependencies": { + "SQLitePCLRaw.core": "2.1.13" + } } } } diff --git a/docs/OAUTH.md b/docs/OAUTH.md new file mode 100644 index 0000000..3b14fde --- /dev/null +++ b/docs/OAUTH.md @@ -0,0 +1,99 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 --> + +# Progmasoft OAuth + +Progmasoft OAuth lets any application sign people in with their Progmasoft account and, with their consent, act on +their behalf. It is an OAuth 2.1 authorization server and an OpenID Connect provider at +`https://credentials.progmasoft.com/`. Any developer with a Progmasoft account can register applications. + +## Register an application + +Sign in at `https://credentials.progmasoft.com/developers` and register the application: + +| Field | Meaning | +| --- | --- | +| Type | **Confidential** for a server that keeps a client secret; **public** for a browser or native application, which has no secret. The type cannot change later. | +| Name | What the consent page shows, 3 to 64 characters. | +| Homepage | Optional, `https://` only. | +| Redirection addresses | Up to 10, compared exactly. `https://` addresses; `http://` only for a loopback address (`127.0.0.1`, `[::1]`, `localhost`); for public clients also a private-use scheme in reverse DNS order, such as `com.example.app:/callback` (RFC 8252). No fragments, user information or wildcards. | +| Addresses after sign-out | Optional, the same rules; where `/connect/logout` may send the account holder. | +| Scopes | The scopes the application may request; see below. | +| Service access | Allows the client credentials grant; confidential clients only. | + +The portal shows the client identifier (`pmo_…`) and, for a confidential client, the client secret. The secret is +shown once and stored only as a hash; make a new one in the portal if it is lost. An account can register 10 +applications. Deleting an application ends every authorization and token it holds. + +## Endpoints + +The discovery documents list everything: `/.well-known/openid-configuration` and +`/.well-known/oauth-authorization-server`. + +| Endpoint | Path | +| --- | --- | +| Authorization | `/connect/authorize` | +| Token | `/connect/token` | +| User information | `/connect/userinfo` | +| End session | `/connect/logout` | +| Revocation | `/connect/revoke` | +| Introspection | `/connect/introspect` (confidential clients) | +| Key set | `/.well-known/jwks` | + +## Flows + +- **Authorization code with PKCE**, for every client. `code_challenge_method` must be `S256`; requests without a + challenge, and `plain` challenges, are refused. Confidential clients also authenticate at the token endpoint with + their secret (`client_secret_post` or `client_secret_basic`). +- **Refresh tokens**, with `offline_access`. Each refresh returns a new refresh token and retires the old one. A + retired refresh token that is presented again is treated as stolen: the whole chain of tokens is revoked. +- **Client credentials**, when allowed. The token names the application itself (`sub` is the client identifier) and + carries no account scope. + +The implicit grant, the resource owner password grant and the device flow are not offered. + +## Scopes + +| Scope | Grants | Claims | +| --- | --- | --- | +| `openid` | An OpenID Connect sign-in: the account identifier | `sub` | +| `profile` | Reading the Progmasoft account name | `name`, `preferred_username` | +| `email` | Reading the email address the account signs in and registered with | `email`, `email_verified` | +| `viget.packages.read` | Reading the packages the account has published on ViGet | — | +| `viget.packages.publish` | Publishing packages to ViGet under the account | — | +| `viget.packages.yank` | Yanking packages of the account on ViGet | — | +| `offline_access` | Refresh tokens: access while the account holder is not signed in | — | + +`sub` is a stable, opaque identifier; use it, not the account name or the address, to recognize an account. Account +registration does not verify email addresses, so `email_verified` is always `false`. + +Access tokens that carry a ViGet scope have the audience `viget`; ViGet accepts only such tokens for its package +operations. + +## Consent + +Every application asks for consent, and the consent page lists each requested scope on its own line together with +the application's name, the account that registered it, and the host the account holder returns to. An application +that already holds consent for the requested scopes gets its code without the page, unless it sends +`prompt=consent`. `prompt=none` returns `login_required` or `consent_required` instead of showing a page. + +Account holders review and withdraw consent at `https://credentials.progmasoft.com/account/applications`. +Withdrawing ends the application's tokens at once. + +## Tokens + +| Token | Lifetime | +| --- | --- | +| Authorization code | 2 minutes, single use | +| Access token | 15 minutes | +| Identity token | 15 minutes | +| Refresh token | 30 days, single use | + +Identity tokens are signed JSON Web Tokens; verify them with the key set. Access tokens are encrypted for Progmasoft +services; a client treats them as opaque and asks the introspection or user information endpoint when it needs +their content. + +## Limits + +The token endpoint, the authorization endpoint and the portal accept 60 requests a minute from one address; the +sign-in form accepts 12 in three minutes. More are answered with 429. diff --git a/docs/README.md b/docs/README.md index f799195..e597b08 100644 --- a/docs/README.md +++ b/docs/README.md @@ -10,6 +10,7 @@ so; [Known limitations](LIMITATIONS.md) collects those places. | --- | --- | | [Architecture](ARCHITECTURE.md) | which process serves which host, how a request travels, and where the trust boundaries are | | [Account API](ACCOUNT-API.md) | every endpoint of the account service: requests, responses, errors, cookies and limits | +| [OAuth](OAUTH.md) | Progmasoft OAuth for developers: registering applications, flows, scopes, consent, tokens and limits | | [Localization](LOCALIZATION.md) | which languages are published, how a page picks one, how Hebrew is laid out, and how to add a language | | [Development](DEVELOPMENT.md) | how to run, test and document the project locally, and what each CI check enforces | | [Known limitations](LIMITATIONS.md) | what is deliberately missing or temporary, and what that means for operations | diff --git a/ops/README.md b/ops/README.md index d316a6a..08fa832 100644 --- a/ops/README.md +++ b/ops/README.md @@ -110,3 +110,34 @@ are Progmaweb responsibilities; the Tala and ViGet website repository does not o Apply those fragments deliberately rather than copying the directory over `/etc`. The accompanying mail README records the DNS, TLS, OpenDKIM, Postfix, Dovecot, sender-login, filesystem-permission, and secret-handling contract. + +## Progmasoft OAuth + +The account API also serves Progmasoft OAuth, the OAuth 2.1 and OpenID Connect provider, on +`credentials.progmasoft.com` (see [OAuth](../docs/OAUTH.md)). Nginx sends every path of that host to the API; the API +answers OAuth paths only there and nothing else there. The OAuth tables (`oauth_*`) live in the account database and +are created by the API at start, like the account tables. + +Production needs two keys, kept outside the releases so that tokens survive a release and a restart: + +```sh +install -d -m 0750 -o root -g progmaweb /etc/progmaweb/oauth +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out /etc/progmaweb/oauth/signing.pem +openssl rand -base64 32 > /etc/progmaweb/oauth/encryption.key +chown root:progmaweb /etc/progmaweb/oauth/*; chmod 0640 /etc/progmaweb/oauth/* +restorecon -R /etc/progmaweb/oauth +``` + +`/etc/progmaweb/account.env` names them: + +```text +OAuth__SigningKeyPath=/etc/progmaweb/oauth/signing.pem +OAuth__EncryptionKeyPath=/etc/progmaweb/oauth/encryption.key +``` + +The service refuses to start in production without them. Replacing the signing key invalidates identity tokens that +clients still hold; replacing the encryption key invalidates every access token, authorization code and refresh +token, so every application has to ask again. Back up both files with the database. + +The certificate of `progmasoft.com` must name `credentials.progmasoft.com` as well; expand it with certbot's webroot +plugin before the vhost is enabled, then check `/.well-known/openid-configuration` and the sign-in page from outside. diff --git a/ops/nginx/progmaweb.conf b/ops/nginx/progmaweb.conf index b7d5d8a..fd24489 100644 --- a/ops/nginx/progmaweb.conf +++ b/ops/nginx/progmaweb.conf @@ -185,3 +185,51 @@ server { proxy_read_timeout 60s; } } + +# Progmasoft OAuth: the OAuth 2.1 and OpenID Connect provider of Progmasoft +# accounts. Every path goes to the account API, which serves OAuth only on this +# host and nothing else here; its pages set their own content security policy. +server { + listen 80; + listen [::]:80; + server_name credentials.progmasoft.com; + + location ^~ /.well-known/acme-challenge/ { + root /var/lib/letsencrypt; + default_type text/plain; + } + + location / { + return 308 https://credentials.progmasoft.com$request_uri; + } +} + +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + server_name credentials.progmasoft.com; + + ssl_certificate /etc/letsencrypt/live/progmasoft.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/progmasoft.com/privkey.pem; + include /etc/letsencrypt/options-ssl-nginx.conf; + + client_max_body_size 64k; + + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header X-Robots-Tag "noindex, nofollow, noarchive" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + + location / { + proxy_pass http://127.0.0.1:5085; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_read_timeout 30s; + } +}