-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
415 lines (353 loc) · 14.6 KB
/
Copy pathProgram.cs
File metadata and controls
415 lines (353 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Sample.Api;
using Shiny.Net.HttpServer;
using Shiny.Net.HttpServer.Cors;
using Shiny.Net.HttpServer.FileBrowser;
using Shiny.Net.HttpServer.Jwt;
using Shiny.Net.HttpServer.OpenApi;
using Shiny.Net.HttpServer.RateLimiting;
using Shiny.Net.HttpServer.Security;
using Shiny.Net.HttpServer.Tunneling;
using Shiny.Net.HttpServer.WebDav;
// ---------------------------------------------------------------------------
// The whole ramp, in one app. Every tier below is optional and they all compose:
//
// Tier 0 OnRequest one delegate, no routing
// Tier 1 MapGet/MapPost raw handlers behind a route template
// Tier 2 Use middleware, ASP.NET Core shaped
// Tier 3 [Route] generated typed endpoints — see WidgetEndpoints.cs
// ---------------------------------------------------------------------------
var builder = HttpServer.CreateBuilder();
builder.Configure(o =>
{
o.Port = 8080;
o.HideExceptionDetails = false;
});
builder.Services.AddLogging(l => l.AddSimpleConsole(c => c.SingleLine = true).SetMinimumLevel(LogLevel.Information));
builder.Services.AddSingleton<IGreeter, Greeter>();
builder.Services.AddSingleton<IWidgetStore, InMemoryWidgetStore>();
builder.Services.AddScoped<RequestId>();
builder.Services.AddSingleton<RequestTimingMiddleware>();
builder.Services.AddSingleton<IUserDirectory, InMemoryUserDirectory>();
// --- The authorization mechanics, set at registration ---
//
// The signing key is generated per run because this is a sample. A real app loads it from
// configuration or a keychain: a key that changes on restart invalidates every token already
// issued.
var signingKey = JwtSigningKey.CreateSecret();
builder.Services
.AddAuthentication()
.AddJwtBearer(o =>
{
o.Issuer = SampleAuth.Issuer;
o.Audience = SampleAuth.Audience;
o.SigningKey = signingKey;
});
builder.Services.AddAuthorization(o =>
{
o.AddPolicy("admin", p => p.RequireRole("admin"));
// Everything else stays open here. Uncommenting this flips the whole app to deny-by-default,
// leaving only [AllowAnonymous] endpoints reachable:
// o.SetFallbackPolicy(p => p.RequireAuthenticatedUser());
});
// --- Who may reach the server, how often, and from where ---
builder.Services.AddCors(o =>
{
o.AddDefaultPolicy(p => p.WithOrigins("https://app.example.com").AllowAnyHeader().AllowAnyMethod());
o.AddPolicy("public", p => p.AllowAnyOrigin().WithMethods("GET"));
});
builder.Services.AddRateLimiter(o =>
{
// Per caller address by default. A hundred requests a minute is generous for a demo and small
// enough to see working.
o.GlobalPolicy = new FixedWindowRateLimitPolicy(100, TimeSpan.FromMinutes(1));
o.AddTokenBucket("uploads", capacity: 5, tokensPerPeriod: 1, period: TimeSpan.FromSeconds(10));
});
builder.Services.AddIpFilter(o =>
// Nothing is filtered by default here — an "admin" policy is registered for the one route that
// wants it. Setting a DefaultPolicy would apply to every request, including the 404s.
o.AddPolicy("admin", p => p.AllowLoopback())
);
var app = builder.Build();
// --- Tier 2: middleware, wraps everything below ---
//
// Two forms, same contract. A lambda for something small:
app.Use((ctx, next) =>
{
// Registered as a callback rather than set after next(): by the time the handler returns,
// headers are on the wire and mutating them throws. OnStarting runs just before they go.
ctx.Response.OnStarting(() =>
{
ctx.Response.Headers["X-Served-By"] = "Shiny";
return ValueTask.CompletedTask;
});
return next(ctx);
});
// ...and a class once it has dependencies or deserves its own tests:
app.Use<RequestTimingMiddleware>();
// CORS first of all: a preflight arrives without credentials, so authentication ahead of it would
// 401 the browser's question and the real request would never be sent.
app.UseCors();
// Then the two that exist to stop work from happening — both before routing, so a throttled or
// blocked request costs nothing beyond parsing.
app.UseRateLimiter();
app.UseIpFilter();
// Identify the caller before routing; decide whether they may have the endpoint after it.
app.UseAuthentication();
app.UseAuthorization();
// --- Tier 3: generated endpoints. One call registers every [Route] class in this assembly. ---
app.MapSampleApiEndpoints();
// --- The OpenAPI document, built from the same metadata the generator wrote the binders from ---
app.MapOpenApi(configure: o =>
{
o.Title = "Sample Widgets API";
o.Version = "1.0.0";
o.Description = "Demonstrates all four tiers of Shiny.Net.HttpServer.";
o.AddBearerAuthentication();
});
// --- Tier 1: routed raw handlers ---
//
// Describe() puts a raw route in the OpenAPI document with more than just its path.
app.MapGet("/ping", ctx => ctx.Response.WriteAsync("pong"))
.Describe(o =>
{
o.Summary = "Liveness probe";
o.Tags.Add("ops");
o.Responses.Add(new ApiResponse { StatusCode = 200, Type = typeof(string), ContentType = "text/plain" });
});
app.MapGet("/hello/{name}", ctx =>
{
var greeter = ctx.GetRequiredService<IGreeter>();
return ctx.Response.WriteAsync(greeter.Greet(ctx.Request.RouteValues["name"]!));
});
// Per-route policies. Each applies to the route just mapped, the same way RequireAuthorization does.
app.MapGet("/status", ctx => ctx.Response.WriteAsync("ok"))
.RequireCors("public")
.DisableRateLimiting();
app.MapGet("/admin/keys", ctx => ctx.Response.WriteAsync("nothing to see here"))
.RequireIpFilter("admin");
// IResult with JsonTypeInfo passed directly — the most explicit AOT-safe JSON you can write.
app.MapGet("/users/{id:int}", ctx =>
{
ctx.Request.RouteValues.TryGetInt32("id", out var id);
return id is > 0 and < 1000
? Results.Ok(new User(id, $"user-{id}"), SampleJson.Default.User)
: Results.NotFound();
});
// A catch-all route parameter: everything after the prefix, slashes included, arrives as one value.
app.MapGet("/catch-all/{*path}", ctx =>
Results.Text($"catch-all captured: {ctx.Request.RouteValues["path"]}"));
// Proves the scope really is per request: both resolutions inside one request are the same
// instance, and a second request gets a different one.
app.MapGet("/scope", ctx =>
{
var a = ctx.GetRequiredService<RequestId>();
var b = ctx.GetRequiredService<RequestId>();
return ctx.Response.WriteAsync($"same-instance={ReferenceEquals(a, b)} id={a.Value}");
});
app.MapPost("/echo", async ctx =>
{
var body = await ctx.Request.ReadBodyAsStringAsync();
await ctx.Response.WriteAsync($"echo:{body}");
});
app.MapGet("/boom", _ => throw new InvalidOperationException("deliberate failure"));
// --- One directory, served two ways ---
//
// The same folder is mapped below as a JSON API and as a drive. Which one a caller wants depends
// entirely on what the caller is: a script speaks HTTP, a desktop speaks WebDAV.
var filesRoot = Directory.CreateDirectory(Path.Combine(AppContext.BaseDirectory, "files-root"));
if (!File.Exists(Path.Combine(filesRoot.FullName, "readme.txt")))
File.WriteAllText(Path.Combine(filesRoot.FullName, "readme.txt"), "Edit me from your file manager.\n");
// --- A directory, as an API ---
//
// curl http://localhost:8080/files # JSON listing
// curl http://localhost:8080/files/readme.txt # the bytes
// curl -X PUT --data 'hello' -H "Authorization: Bearer $TOKEN" http://localhost:8080/files/notes.txt
// curl -X DELETE -H "Authorization: Bearer $TOKEN" http://localhost:8080/files/notes.txt
//
// The file browser is mapped as routes rather than middleware, and that is the whole reason it
// hands its endpoints back: reads stay open here while anything that changes a file needs an admin
// token — a distinction middleware could not express. Get a token from POST /api/auth/login as
// ada/hunter2, or swap the call below for .RequireAuthorization() to close the reads too.
app.MapFileBrowser("/files", o =>
{
o.RootPath = filesRoot.FullName;
o.AllowWrite = true;
o.AllowDelete = true;
})
.RequireAuthorizationForChanges("admin");
// --- The same directory, as a drive ---
//
// One call maps the twenty-two routes of an RFC 4918 class 1 & 2 WebDAV mount. Point Finder (Go →
// Connect to Server) or Explorer (Map network drive) at http://localhost:8080/dav and the folder
// opens as a drive — no client to write, and no client to install.
//
// A browser GET of the same URL shows a plain HTML index, which is the quickest way to see it
// working without mounting anything.
app.MapWebDav("/dav", o =>
{
o.RootPath = filesRoot.FullName;
o.AllowWrite = true;
o.AllowDelete = true;
o.DisplayName = "Sample";
});
// Left open because this sample binds loopback and nothing else can reach it. A mount anyone else
// can see needs both of these — a WebDAV client sends its password on every single request:
//
// app.MapWebDav("/dav", …).RequireAuthorization(); // or .RequireAuthorizationForChanges()
// builder.Configure(o => o.Certificate = …); // see /httpserver/tls/
// --- Controlling the server from inside the app ---
//
// The server is an ordinary object: hold onto it and start, stop or restart it whenever. This
// sample exposes it over HTTP for demonstration, but the same two calls sit behind a toggle in a
// MAUI app. With AddHttpServer(..., autoStart: false) the server is registered and configured but
// never listening until something asks it to.
app.MapGet("/server/status", ctx => ctx.Response.WriteAsync($"{app.State} {app.ListenUrl}"));
app.MapPost("/server/restart", async ctx =>
{
// Not awaited inline: restarting tears down the connection this request arrived on.
_ = Task.Run(async () =>
{
await Task.Delay(100);
await app.RestartAsync();
});
await ctx.Response.WriteAsync("restarting");
});
app.StateChanged += (_, state) => Console.WriteLine($" [server] {state}");
// --- Tier 0: everything no route claimed ---
app.OnRequest(ctx =>
{
ctx.Response.StatusCode = StatusCodes.Status404NotFound;
return ctx.Response.WriteAsync($"no route for {ctx.Request.Path}");
});
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; cts.Cancel(); };
await app.StartAsync(cts.Token);
Console.WriteLine($"Serving on {app.ListenUrl} — Ctrl+C to stop");
// --- Optional: also serve through a relay tunnel ---
//
// dotnet run --project samples/Sample.Api -- --tunnel localhost:5050 --subdomain demo
//
// The tunnel dials out, so this works from behind NAT where nothing can connect in. Requests that
// arrive through it hit exactly the same routes as the local port above.
Task? tunnel = null;
if (Args.Value("--tunnel") is { } relayAddress)
{
var (relayHost, relayPort) = relayAddress.Split(':') switch
{
[var h, var p] => (h, int.Parse(p)),
[var h] => (h, 5050),
_ => ("localhost", 5050)
};
var provider = new RelayTunnelProvider(
new RelayTunnelOptions
{
Host = relayHost,
Port = relayPort,
Subdomain = Args.Value("--subdomain"),
Token = Args.Value("--token") ?? "demo-token",
UseTls = false
},
app.Services!.GetRequiredService<ILoggerFactory>().CreateLogger<RelayTunnelProvider>()
);
tunnel = app.RunTunnelAsync(provider, app.Services!.GetRequiredService<ILogger<Program>>(), cts.Token);
}
try
{
await Task.Delay(Timeout.Infinite, cts.Token);
}
catch (OperationCanceledException)
{
}
if (tunnel is not null)
await tunnel;
await app.StopAsync();
static class Args
{
public static string? Value(string name)
{
var all = Environment.GetCommandLineArgs();
for (var i = 0; i < all.Length - 1; i++)
{
if (string.Equals(all[i], name, StringComparison.OrdinalIgnoreCase))
return all[i + 1];
}
return null;
}
}
interface IGreeter
{
string Greet(string name);
}
sealed class Greeter : IGreeter
{
public string Greet(string name) => $"Hello, {name}!";
}
/// <summary>Scoped: one instance per HTTP request/response exchange.</summary>
sealed class RequestId
{
public Guid Value { get; } = Guid.NewGuid();
}
/// <summary>
/// The same thing the lambda above does, as a type — constructor-injected, unit-testable, and
/// registered like any other service.
/// </summary>
sealed class RequestTimingMiddleware(ILogger<RequestTimingMiddleware> logger) : IHttpMiddleware
{
public async ValueTask InvokeAsync(HttpContext context, RequestDelegate next)
{
var sw = Stopwatch.StartNew();
await next(context);
logger.LogInformation(
"{Method} {Path} -> {Status} ({Elapsed}ms)",
context.Request.Method,
context.Request.Path,
context.Response.StatusCode,
sw.ElapsedMilliseconds
);
}
}
sealed class InMemoryWidgetStore : IWidgetStore
{
readonly Dictionary<int, Widget> widgets = new()
{
[1] = new Widget(1, "bolt"),
[2] = new Widget(2, "flange"),
[3] = new Widget(3, "grommet")
};
int next = 4;
public ValueTask<Widget?> FindAsync(int id, CancellationToken cancellationToken)
=> new(this.widgets.GetValueOrDefault(id));
public ValueTask<IReadOnlyList<Widget>> ListAsync(int take, string? search, CancellationToken cancellationToken)
{
IEnumerable<Widget> query = this.widgets.Values;
if (!string.IsNullOrWhiteSpace(search))
query = query.Where(w => w.Name.Contains(search, StringComparison.OrdinalIgnoreCase));
return new ValueTask<IReadOnlyList<Widget>>(query.Take(take).ToArray());
}
public ValueTask<Widget> AddAsync(string name, CancellationToken cancellationToken)
{
var widget = new Widget(this.next++, name);
this.widgets[widget.Id] = widget;
return new ValueTask<Widget>(widget);
}
public ValueTask<bool> RemoveAsync(int id, CancellationToken cancellationToken)
=> new(this.widgets.Remove(id));
}
/// <summary>
/// Stand-in for a real user store. Passwords are compared in plain text here because this is a
/// sample; anything real hashes them with a slow KDF.
/// </summary>
sealed class InMemoryUserDirectory : IUserDirectory
{
readonly SampleUser[] users =
[
new("ada", "Ada Lovelace", "hunter2", ["admin", "user"]),
new("linus", "Linus Torvalds", "penguin", ["user"])
];
public SampleUser? Verify(string username, string password) => this.users.FirstOrDefault(
u => string.Equals(u.Username, username, StringComparison.OrdinalIgnoreCase) && u.Password == password
);
}