-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
236 lines (221 loc) · 10.3 KB
/
Copy pathmiddleware.ts
File metadata and controls
236 lines (221 loc) · 10.3 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
import { authMiddleware } from "@/auth";
import { NextResponse, type NextRequest } from "next/server";
import { getArtifactSandboxOrigin } from "@/lib/content/artifact-sandbox-config";
import { inAppSignInCallbackUrl } from "@/lib/auth/sign-in-callback";
import {
isArtifactDataE2EProbeEnabled,
isLocalArtifactDataActionProbe,
} from "@/lib/auth/artifact-data-e2e-probe";
import { isOidcProviderResumePath } from "@/lib/oauth/resume-path";
// Public paths that don't require authentication
const PUBLIC_PATHS = [
"/",
"/signout",
"/api/auth",
"/api/public",
"/api/health",
"/api/healthz", // Lightweight health check for ECS/Docker
"/api/ping",
"/api/auth/federated-signout",
// SECURITY: All routes under /api/v1/* MUST use withApiAuth() wrapper.
// This bypass only skips NextAuth session checks — API routes handle their own auth.
"/api/v1", // External API routes handle their own auth via Bearer token (#677)
"/api/mcp", // MCP endpoint handles its own auth via Bearer token (#686)
"/api/oauth", // OAuth2/OIDC endpoints handle their own auth (#686)
"/.well-known", // OIDC discovery document (#686)
"/auth/error",
// Agent Workspace bootstrap (#912). API calls verify router-signed invocation
// context. The original Google Workspace flow remains link-authenticated;
// provider-specific reusable grants are deliberately excluded below and
// require a same-owner AI Studio session.
"/api/agent", // Agent endpoints verify router-signed invocation context
"/agent-connect", // Consent page and OAuth callback — signed JWT in URL
// Canva, Plaud, and AI Studio intentionally are NOT public. Their external
// OAuth grants are stored in a local owner's reusable credential slot, so
// both the start and callback must carry a live AI Studio session whose email
// matches that immutable owner. A signed link alone proves integrity, not who
// opened it. The Cognito data flow remains separate and has its own identity
// semantics.
"/agent-connect-data",
// Atrium public reader (#1057): /p/[slug] is the anonymous public_web reader
// route (spec §20). It is world-readable by design — the page itself gates
// strictly on visibility_level='public' + a live public_web publication and
// consults no session — so it must NOT be redirected to sign-in. A non-public
// or unpublished slug 404s (existence-masking), never redirects.
"/p",
// SEO endpoints (#1059): sitemap enumerates ONLY objects passing the exact
// /p/[slug] public gate (app/sitemap.ts); robots.txt points crawlers at it.
// Both must be crawler-reachable without a session or the /p/ content is
// undiscoverable.
"/sitemap.xml",
"/robots.txt",
];
// Unlike PUBLIC_PATHS, entries here do not expose descendant routes. Google
// Drive push notifications authenticate with a high-entropy channel token plus
// channel/resource identifiers inside the route, but future sibling handlers
// must not silently inherit that browser-session exemption.
const EXACT_PUBLIC_PATHS = new Set([
"/api/repositories/connectors/google/webhook",
]);
// Atrium artifact sandbox (#1052): the app embeds an <iframe> pointing at a
// SEPARATE origin that runs untrusted artifact code (spec §19.2/§28.1). The app's
// own CSP `frame-src` must explicitly allow that origin, or the browser blocks
// the frame. The origin (`ATRIUM_SANDBOX_ORIGIN`) is a CloudFront domain injected
// by the CDK deploy — known only at runtime — so the CSP is built HERE (middleware
// runs per request and can read runtime env) instead of in next.config (which is
// evaluated at build time).
//
// SINGLE SOURCE OF TRUTH: the origin is resolved via `getArtifactSandboxOrigin()`
// from artifact-sandbox-config.ts — the SAME resolver the iframe `src` uses. This
// guarantees the CSP `frame-src` entry and the iframe `src` resolve to byte-
// identical origins (including the same env-var priority and the same-origin
// fail-closed guard). A divergent local resolver here previously read the env vars
// in the opposite priority order, so a mixed local/CDK env could allowlist origin
// A while the iframe pointed at origin B → the browser silently blocks the frame.
// The shared module is Edge-Runtime safe (only `URL` + `process.env`).
//
// Built once at module init; the sandbox origin is stable for the process life.
// frame-src keeps 'self' + the Canva embed origin and appends the sandbox origin
// only when configured (otherwise the artifact preview frame is simply blocked,
// matching the component's fail-closed behavior).
const SANDBOX_FRAME_ORIGIN = getArtifactSandboxOrigin();
const FRAME_SRC = [
"'self'",
"https://www.canva.com",
"https://docs.google.com",
...(SANDBOX_FRAME_ORIGIN ? [SANDBOX_FRAME_ORIGIN] : []),
].join(" ");
const CONTENT_SECURITY_POLICY =
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.amazonaws.com https://apis.google.com; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data: https: blob:; " +
"font-src 'self' data:; " +
"connect-src 'self' https://*.amazonaws.com wss://*.amazonaws.com https://api.anthropic.com https://api.openai.com https://apis.google.com; " +
`frame-src ${FRAME_SRC}; ` +
"frame-ancestors 'none';";
const ARTIFACT_DATA_E2E_PROBE_HEADER =
"X-AIStudio-Artifact-Data-E2E-Probe";
function artifactDataE2EProbeContext(req: NextRequest) {
// nextUrl.hostname may be derived from Host, so loopback is defense in depth;
// the production NODE_ENV check is the non-negotiable deployment boundary.
return {
nodeEnv: process.env.NODE_ENV,
probeFlag: process.env.ATRIUM_ARTIFACT_DATA_E2E_ACTION_PROBE,
hostname: req.nextUrl.hostname,
};
}
/**
* Local authenticated-E2E harness only: after Playwright loads the protected
* page with a valid session, it clears the session cookie and invokes the
* Artifact Data Server Actions. Let only those exact development-mode POSTs
* reach the actions so their own auth boundary is exercised through the real
* Next.js transport. The local E2E runner opts in explicitly and binds its
* server to loopback; ordinary development servers do not enable the probe.
* Deployed builds always use NODE_ENV=production, where this exception is
* disabled and the page itself also returns 404.
*/
function isLocalArtifactDataActionProbeRequest(req: NextRequest): boolean {
const context = artifactDataE2EProbeContext(req);
if (!isArtifactDataE2EProbeEnabled(context)) return false;
return isLocalArtifactDataActionProbe({
...context,
method: req.method,
pathname: req.nextUrl.pathname,
hasNextActionHeader: req.headers.has("next-action"),
});
}
function isArtifactDataE2EProbeHealthCheck(req: NextRequest): boolean {
return (
isArtifactDataE2EProbeEnabled(artifactDataE2EProbeContext(req)) &&
req.nextUrl.pathname === "/api/healthz"
);
}
export default authMiddleware((req) => {
const { nextUrl, auth } = req;
const isLoggedIn = !!auth;
// Check if path is public
const isPublicPath =
isLocalArtifactDataActionProbeRequest(req) ||
EXACT_PUBLIC_PATHS.has(nextUrl.pathname) ||
PUBLIC_PATHS.some(
(path) =>
nextUrl.pathname === path || nextUrl.pathname.startsWith(path + "/"),
) ||
isOidcProviderResumePath(nextUrl.pathname);
// Create response with security headers
let response: NextResponse;
// Track whether this is a passthrough (NextResponse.next()) response.
// next.config.mjs headers() applies to passthrough responses, so HSTS and
// Referrer-Policy are already set globally there. Only set them here on
// direct responses (401s, redirects) to avoid duplicate headers that violate
// RFC 6797 and could confuse security scanners.
let isPassthrough = false;
// Allow public paths
if (isPublicPath) {
response = NextResponse.next();
isPassthrough = true;
}
// Allow static assets
else if (
nextUrl.pathname.startsWith("/_next") ||
nextUrl.pathname.startsWith("/static") ||
nextUrl.pathname.match(/\.(jpg|jpeg|png|gif|ico|css|js)$/i)
) {
response = NextResponse.next();
isPassthrough = true;
}
// Handle API routes differently - return 401 instead of redirecting
else if (!isLoggedIn && nextUrl.pathname.startsWith("/api/")) {
response = NextResponse.json(
{ error: "Unauthorized" },
{ status: 401 }
);
}
// Redirect unauthenticated users to sign-in for non-API routes
else if (!isLoggedIn) {
const callbackUrl = inAppSignInCallbackUrl(nextUrl);
response = NextResponse.redirect(new URL(`/api/auth/signin?callbackUrl=${encodeURIComponent(callbackUrl)}`, nextUrl));
}
else {
response = NextResponse.next();
isPassthrough = true;
}
// Add security headers to all responses
response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
response.headers.set('Pragma', 'no-cache');
response.headers.set('Expires', '0');
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('X-XSS-Protection', '1; mode=block');
if (isArtifactDataE2EProbeHealthCheck(req)) {
// The local runner uses this marker to avoid reusing an ordinary dev server
// whose process environment cannot exercise the cleared-session probe.
response.headers.set(ARTIFACT_DATA_E2E_PROBE_HEADER, "enabled");
}
// CSP is set here (not next.config) so frame-src can include the runtime-known
// Atrium sandbox origin. Single source → no intersection with a build-time
// policy. See next.config.mjs note (#1052).
response.headers.set('Content-Security-Policy', CONTENT_SECURITY_POLICY);
// HSTS and Referrer-Policy: set only on direct responses (401s, redirects)
// where next.config.mjs headers() does not apply. The ALB terminates TLS;
// HSTS tells browsers to always use HTTPS when connecting to the ALB.
// Passthrough responses receive these headers from next.config.mjs headers().
if (!isPassthrough) {
response.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
}
return response;
});
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api/auth (NextAuth routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!api/auth|_next/static|_next/image|favicon.ico).*)",
],
};