Repository navigation
DEMO: Local PEAKS MCP plugin with OAuth — DO NOT MERGE #1413
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
srkirkland
wants to merge
3
commits into
master
Choose a base branch
from
srk/peaks-mcp-demo
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,817
−3
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| { | ||
| "name": "peaks-demo", | ||
| "interface": { "displayName": "PEAKS local demo" }, | ||
| "plugins": [ | ||
| { | ||
| "name": "peaks", | ||
| "source": { "source": "local", "path": "./plugins/peaks" }, | ||
| "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" }, | ||
| "category": "Productivity" | ||
| } | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| # Disposable demo overlay; the base sandbox stays unchanged. | ||
| services: | ||
| certificates: | ||
| image: busybox:1.37 | ||
| user: root | ||
| volumes: | ||
| - ../.local/mcp:/source:ro | ||
| - sandbox-mcp-certs:/certs | ||
| command: ["sh", "-c", "cp /source/localhost.pfx /certs/localhost.pfx && chown 1654:1654 /certs/localhost.pfx && chmod 600 /certs/localhost.pfx"] | ||
| initialize: | ||
| environment: | ||
| PEAKS_MCP_DEMO: "1" | ||
| app: | ||
| environment: | ||
| PEAKS_SANDBOX: "1" | ||
| McpDemo__Enabled: "true" | ||
| McpDemo__Issuer: ${MCP_DEMO_ISSUER:-https://localhost:5446/} | ||
| McpDemo__AllowNgrok: ${MCP_DEMO_ALLOW_NGROK:-false} | ||
| McpDemo__ChatGptRedirectUri: ${MCP_DEMO_CHATGPT_REDIRECT_URI:-} | ||
| ASPNETCORE_URLS: http://+:8080;https://+:8443 | ||
| ASPNETCORE_HTTPS_PORT: ${MCP_DEMO_HTTPS_PORT:-5446} | ||
| Kestrel__Certificates__Default__Path: /certs/localhost.pfx | ||
| Kestrel__Certificates__Default__Password: peaks-local-demo | ||
| ELASTIC_APM_ENABLED: "false" | ||
| Stackify__ElasticUrl: "" | ||
| ports: | ||
| - "127.0.0.1:${MCP_DEMO_HTTPS_PORT:-5446}:8443" | ||
| volumes: | ||
| - sandbox-mcp-certs:/certs:ro | ||
| depends_on: | ||
| certificates: | ||
| condition: service_completed_successfully | ||
| volumes: | ||
| sandbox-mcp-certs: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| .git | ||
| .local | ||
| **/bin | ||
| **/obj | ||
| **/node_modules | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Globalization; | ||
| using System.Linq; | ||
| using System.Security.Claims; | ||
| using System.Text.Json; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Keas.Core.Data; | ||
| using Keas.Mvc.Mcp; | ||
| using Microsoft.AspNetCore; | ||
| using Microsoft.AspNetCore.Authentication; | ||
| using Microsoft.AspNetCore.Authentication.Cookies; | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using Microsoft.EntityFrameworkCore; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using OpenIddict.Abstractions; | ||
| using OpenIddict.Server.AspNetCore; | ||
| using static OpenIddict.Abstractions.OpenIddictConstants; | ||
|
|
||
| namespace Keas.Mvc.Controllers; | ||
|
|
||
| [AllowAnonymous, ApiExplorerSettings(IgnoreApi = true)] | ||
| [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] | ||
| public sealed class DemoAuthorizationController : Controller | ||
| { | ||
| private const string Scheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; | ||
| private IServiceProvider Services => HttpContext.RequestServices; | ||
|
|
||
| [HttpPost("oauth/register"), IgnoreAntiforgeryToken, RequestSizeLimit(8192)] | ||
| public async Task<IActionResult> Register(CancellationToken ct) | ||
| { | ||
| var settings = Services.GetService<DemoSettings>(); | ||
| if (settings == null) return NotFound(); | ||
| if (!Request.HasJsonContentType()) return StatusCode(415); | ||
| try | ||
| { | ||
| using var document = await JsonDocument.ParseAsync(Request.Body, new JsonDocumentOptions { MaxDepth = 8 }, ct); | ||
| var root = document.RootElement; | ||
| var redirects = root.GetProperty("redirect_uris").EnumerateArray().Select(x => x.GetString()).ToArray(); | ||
| if (redirects.Length < 1 || redirects.Length > 4 || redirects.Any(x => !ValidRedirect(x) && !settings.AllowsHostedRedirect(x))) return BadRegistration(); | ||
| if (root.TryGetProperty("token_endpoint_auth_method", out var method) && method.GetString() != "none") return BadRegistration(); | ||
| if (root.TryGetProperty("grant_types", out var grants) && grants.EnumerateArray().Any(x => x.GetString() != GrantTypes.AuthorizationCode && x.GetString() != GrantTypes.RefreshToken)) return BadRegistration(); | ||
| if (root.TryGetProperty("response_types", out var responses) && responses.EnumerateArray().Any(x => x.GetString() != ResponseTypes.Code)) return BadRegistration(); | ||
| var name = root.TryGetProperty("client_name", out var clientName) ? clientName.GetString() : "Local Codex"; | ||
| if (string.IsNullOrWhiteSpace(name) || name.Length > 100 || name.Any(char.IsControl)) return BadRegistration(); | ||
| var manager = Services.GetRequiredService<IOpenIddictApplicationManager>(); | ||
| var gate = Services.GetRequiredService<DemoClientRegistrationLock>().Gate; | ||
| await gate.WaitAsync(ct); | ||
| try | ||
| { | ||
| if (await manager.CountAsync(ct) >= 100) return StatusCode(429, new { error = "registration_limit" }); | ||
| var descriptor = new OpenIddictApplicationDescriptor | ||
| { | ||
| ClientId = Guid.NewGuid().ToString("N"), ClientType = ClientTypes.Public, | ||
| DisplayName = name, ConsentType = ConsentTypes.Explicit | ||
| }; | ||
| foreach (var redirect in redirects) descriptor.RedirectUris.Add(new Uri(redirect)); | ||
| descriptor.Permissions.UnionWith(new[] { Permissions.Endpoints.Authorization, Permissions.Endpoints.Token, | ||
| Permissions.Endpoints.Revocation, Permissions.GrantTypes.AuthorizationCode, Permissions.GrantTypes.RefreshToken, | ||
| Permissions.ResponseTypes.Code, Permissions.Prefixes.Scope + DemoSettings.Scope, | ||
| Permissions.Prefixes.Resource + Services.GetRequiredService<DemoSettings>().Resource }); | ||
| descriptor.Requirements.Add(Requirements.Features.ProofKeyForCodeExchange); | ||
| await manager.CreateAsync(descriptor, ct); | ||
| return StatusCode(201, new { client_id = descriptor.ClientId, client_name = name, | ||
| redirect_uris = redirects, token_endpoint_auth_method = "none", | ||
| grant_types = new[] { "authorization_code", "refresh_token" }, response_types = new[] { "code" }, | ||
| scope = DemoSettings.Scope + " offline_access" }); | ||
| } | ||
| finally { gate.Release(); } | ||
| } | ||
| catch (Exception exception) when (exception is JsonException || exception is InvalidOperationException || exception is KeyNotFoundException || exception is ArgumentException) | ||
| { return BadRegistration(); } | ||
| } | ||
|
|
||
| public static bool ValidRedirect(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && | ||
| (uri.Scheme == "http" || uri.Scheme == "https") && | ||
| (uri.Host == "localhost" || uri.Host == "127.0.0.1" || uri.Host == "[::1]") && | ||
| uri.UserInfo.Length == 0 && uri.Fragment.Length == 0 && uri.Query.Length == 0; | ||
|
|
||
| [HttpGet("oauth/authorize")] | ||
| public Task<IActionResult> Authorize(CancellationToken ct) => AuthorizeCore(false, ct); | ||
|
|
||
| [HttpPost("oauth/authorize"), ValidateAntiForgeryToken, RequestSizeLimit(16384)] | ||
| public Task<IActionResult> Consent(CancellationToken ct) => AuthorizeCore(true, ct); | ||
|
|
||
| private async Task<IActionResult> AuthorizeCore(bool submitted, CancellationToken ct) | ||
| { | ||
| var settings = Services.GetService<DemoSettings>(); | ||
| if (settings == null) return NotFound(); | ||
| var request = HttpContext.GetOpenIddictServerRequest(); | ||
| var userId = await BrowserUser(ct); | ||
| if (userId == null) | ||
| { | ||
| if (submitted || request.HasPromptValue(PromptValues.None)) return Reject(Errors.LoginRequired); | ||
| return LocalRedirect("/login?returnUrl=" + Uri.EscapeDataString(Request.Path + Request.QueryString)); | ||
| } | ||
| if (request.HasPromptValue(PromptValues.None)) return Reject(Errors.ConsentRequired); | ||
| var applications = Services.GetRequiredService<IOpenIddictApplicationManager>(); | ||
| var application = await applications.FindByClientIdAsync(request.ClientId, ct); | ||
| if (application == null) return Reject(Errors.InvalidClient); | ||
| if (!submitted) | ||
| { | ||
| Response.Headers["Referrer-Policy"] = "strict-origin"; | ||
| return View("Consent", new DemoConsent(await applications.GetDisplayNameAsync(application, ct), userId, | ||
| Request.Query.Where(p => p.Key != "decision" && p.Key != "__RequestVerificationToken") | ||
| .ToDictionary(p => p.Key, p => p.Value.ToString()))); | ||
| } | ||
| if (Request.Form["decision"] != "allow") return Reject(Errors.AccessDenied); | ||
| var principal = new ClaimsPrincipal(new ClaimsIdentity("PeaksDemoOAuth")); | ||
| principal.SetClaim(Claims.Subject, userId); | ||
| var deadline = Services.GetRequiredService<TimeProvider>().GetUtcNow().AddHours(8); | ||
| principal.SetClaim(DemoSettings.DeadlineClaim, deadline.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)); | ||
| principal.SetScopes(request.GetScopes()); | ||
| principal.SetResources(settings.Resource); | ||
| var authorizations = Services.GetRequiredService<IOpenIddictAuthorizationManager>(); | ||
| var authorization = await authorizations.CreateAsync(principal, userId, await applications.GetIdAsync(application, ct), | ||
| AuthorizationTypes.Permanent, principal.GetScopes(), ct); | ||
| principal.SetAuthorizationId(await authorizations.GetIdAsync(authorization, ct)); | ||
| return SignIn(principal, Scheme); | ||
| } | ||
|
|
||
| [HttpPost("oauth/token"), IgnoreAntiforgeryToken, RequestSizeLimit(16384)] | ||
| public async Task<IActionResult> Token(CancellationToken ct) | ||
| { | ||
| if (Services.GetService<DemoSettings>() == null) return NotFound(); | ||
| var principal = (await HttpContext.AuthenticateAsync(Scheme)).Principal; | ||
| if (principal == null || !long.TryParse(principal.GetClaim(DemoSettings.DeadlineClaim), out var deadline) || | ||
| !await Services.GetRequiredService<ApplicationDbContext>().Users.AnyAsync(x => x.Id == principal.GetClaim(Claims.Subject), ct)) | ||
| return Reject(Errors.InvalidGrant); | ||
| var remaining = DateTimeOffset.FromUnixTimeSeconds(deadline) - Services.GetRequiredService<TimeProvider>().GetUtcNow(); | ||
| if (remaining <= TimeSpan.Zero) return Reject(Errors.InvalidGrant); | ||
| principal.SetAccessTokenLifetime(remaining < TimeSpan.FromMinutes(15) ? remaining : TimeSpan.FromMinutes(15)); | ||
| principal.SetRefreshTokenLifetime(remaining); | ||
| return SignIn(principal, Scheme); | ||
| } | ||
|
|
||
| [HttpGet("oauth/connections")] | ||
| public async Task<IActionResult> Connections(CancellationToken ct) | ||
| { | ||
| if (Services.GetService<DemoSettings>() == null) return NotFound(); | ||
| var userId = await BrowserUser(ct); | ||
| if (userId == null) return LocalRedirect("/login?returnUrl=%2Foauth%2Fconnections"); | ||
| Response.Headers["Referrer-Policy"] = "strict-origin"; | ||
| var authorizations = Services.GetRequiredService<IOpenIddictAuthorizationManager>(); | ||
| var applications = Services.GetRequiredService<IOpenIddictApplicationManager>(); | ||
| var connections = new List<DemoConnection>(); | ||
| await foreach (var authorization in authorizations.FindAsync(subject: userId, client: null, status: Statuses.Valid, type: AuthorizationTypes.Permanent, scopes: null, cancellationToken: ct)) | ||
| { | ||
| var clientId = await authorizations.GetApplicationIdAsync(authorization, ct); | ||
| var client = await applications.FindByIdAsync(clientId, ct); | ||
| connections.Add(new DemoConnection(await authorizations.GetIdAsync(authorization, ct), | ||
| client == null ? "MCP client" : await applications.GetDisplayNameAsync(client, ct), | ||
| (await authorizations.GetCreationDateAsync(authorization, ct))?.AddHours(8))); | ||
| } | ||
| return View("Connections", new DemoConnections(userId, connections)); | ||
| } | ||
|
|
||
| [HttpPost("oauth/connections/{id}/revoke"), ValidateAntiForgeryToken] | ||
| public async Task<IActionResult> Revoke(string id, CancellationToken ct) | ||
| { | ||
| if (Services.GetService<DemoSettings>() == null) return NotFound(); | ||
| var userId = await BrowserUser(ct); | ||
| if (userId == null) return Unauthorized(); | ||
| var authorizations = Services.GetRequiredService<IOpenIddictAuthorizationManager>(); | ||
| var authorization = await authorizations.FindByIdAsync(id, ct); | ||
| if (authorization == null || await authorizations.GetSubjectAsync(authorization, ct) != userId) return NotFound(); | ||
| if (!await authorizations.TryRevokeAsync(authorization, ct)) return Conflict(); | ||
| await Services.GetRequiredService<IOpenIddictTokenManager>().RevokeByAuthorizationIdAsync(id, ct); | ||
| return LocalRedirect("/oauth/connections"); | ||
| } | ||
|
|
||
| private async Task<string> BrowserUser(CancellationToken ct) | ||
| { | ||
| var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); | ||
| if (!result.Succeeded || !result.Principal.HasClaim("peaks:local-login", "true")) return null; | ||
| var id = result.Principal.FindFirstValue(ClaimTypes.NameIdentifier); | ||
| return await Services.GetRequiredService<ApplicationDbContext>().Users.AnyAsync(x => x.Id == id, ct) ? id : null; | ||
| } | ||
| private IActionResult BadRegistration() => BadRequest(new { error = "invalid_client_metadata" }); | ||
| private IActionResult Reject(string error) => Forbid(new AuthenticationProperties(new Dictionary<string, string> | ||
| { [OpenIddictServerAspNetCoreConstants.Properties.Error] = error }), Scheme); | ||
| } | ||
|
|
||
| public sealed record DemoConsent(string Client, string User, Dictionary<string, string> Parameters); | ||
| public sealed record DemoConnection(string Id, string Client, DateTimeOffset? Expires); | ||
| public sealed record DemoConnections(string User, List<DemoConnection> Connections); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use
IgnoreQueryFilters()in the MCP demo person lookup, and skip inactive people.The
SingleAsyncat line 214 uses the globalActivequery filter.SeedDemoDataAsynckeeps UI edits between rebuilds, so a person can be deactivated and still exist. The filtered query then matches no row.SingleAsyncthrows, and the transaction rolls back. Every run withPEAKS_MCP_DEMO=1fails until that person is reactivated.The line 75 lookup in the same file already uses
IgnoreQueryFilters(). Apply the same pattern here. Skip the fixture when the person is missing or inactive.Proposed change
Committable suggestion