Request header field sentry-trace is not allowed by Access-Control-Allow-Headers in preflight response - next.js

I'm developing a Frontend using NextJS and Keycloak for auth-purpose. After adding Sentry, I'm facing this issue here, where the token endpoint of Keycloak is returning an error; So I can log in.
I've tried many things:
Change the web-origin config of Keycloak, which (obviously) doesn't change or solves the problem
Play with the Sentry client config, without success, because the denyUrls property still make the Sentry SDK send the sentry-trace into the request.
Now I don't have any more Idea, so I coming here for more help.

So after some investigations, I came across this tracingOrigins property that can be set using integrations like this:
integrations: [
new (Sentry.Integrations as any).BrowserTracing({
tracingOrigins: [
process.env.NEXT_PUBLIC_URL,
process.env.NEXT_PUBLIC_BACKEND_URL,
process.env.NEXT_PUBLIC_MATOMO_URL,
],
}),
],
This config is done inside the sentry.client.config.ts file. The downside is that, urls which are not included there, are simply not tracked.

Unfortunately, Keycloak has hardcoded list of allowed headers, so you can't configure Keycloak for sentry-trace header.
You can have some non ideal work arounds:
don't use sentry
compile own hacked Keycloak version, where you allow that header
add reverse proxy in front of Keycloak, which will add sentry-trace header to allowed headers
...

I've solved this issue on a nextJs application by adding the following header to the static sourcemap response.
'Access-Control-Allow-Headers' on next.config.js
const CONFIG = {
headers: () => [
{
source: "/_next/:path*",
headers: [
{ key: "Access-Control-Allow-Origin", value: SHOP_ORIGIN },
{ key: 'Access-Control-Allow-Headers', value: '*' },
],
},
],
}

Related

How to override AWS Amplify Api domain endpoint

I have added a custom domain to the API Gateway due to CORS/Cookies/Infosec and other fun reasons.
I then added the following code to hack the correct domain into my Amplify configuration:
import { Amplify, API } from "aws-amplify"
const myfunc () => {
const amplifyEndpoint = API._restApi._options.endpoints[0]
Amplify.configure({
aws_cloud_logic_custom: [
{
...amplifyEndpoint,
endpoint: process.env.REACT_APP_API_URL || amplifyEndpoint.endpoint,
},
]
})
const response = await API.post("MyApiNameHere", "/some-endpoint", {data:"here"})
}
This works but a) is this really the correct way to do it? and b) I'm seeing a weird issue whereby the first API.post request of the day from a user is missing the authorization & x-amz-security-token headers that I expect Amplify to be magically providing. If a user refreshes the page, the headers are sent and everything works as expected.
[edit] turns out my missing headers issue is unrelated to this override, so still need to get to the bottom of that!
The more correct place looks to be in the index.js:
import { Amplify, API } from "aws-amplify"
import awsExports from "./aws-exports"
Amplify.configure(awsExports)
const amplifyEndpoint = API._restApi._options.endpoints[0]
Amplify.configure({
aws_cloud_logic_custom: [
{
...amplifyEndpoint,
endpoint: process.env.REACT_APP_API_URL || amplifyEndpoint.endpoint,
},
]
})
That way it's done once - rather than needing to be done in each API call.
Naturally you would need some more complicated logic if you were dealing with multiple endpoints.

Problem to generate the client generator component of API Patform with nuxt.js

I have an api-platform project.
https://localhost:8888/api does show the API documentation.
When i want to generate the client generator component with the command:
npx #api-platform/client-generator https://127.0.0.1:8000/api . --generator nuxt
I have this response:
{
api: Api { entrypoint: 'https://127.0.0.1:8000/api', resources: [] },
error: {
response: Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: [Object],
[Symbol(Response internals)]: [Object]
}
},
response: Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
[Symbol(Response internals)]: {
url: 'https://127.0.0.1:8000/api',
status: 200,
statusText: 'OK',
headers: [Headers],
counter: 0
}
},
status: 200
}
No components have been generated and not sure where to go from there.
I did the setup successfully on my side (until I got a CORS issue probably because I was using https://demo.api-platform.com).
Here is my Github repo for a working client side boilerplate'd Nuxt app that I've got.
Some things are questionable like the usage of Moment.js in 2022, the fact that this is a Nuxt app used as an SPA only (ssr: false), some not up to-date configuration like for nuxt-i18n modules, the components: false, the fact that there are still some ESlint warnings/errors in the various files, the use of an additional vue-i18n package on top of nuxt-i18n but the setup looks kinda okay otherwise.
I mean, at the end it's kinda removing all the nice stuff from Nuxt to have a basic usual Vue.js app as an SPA but yeah, fine let's say.
There is this line in entrypoint.js
export const ENTRYPOINT = 'https://demo.api-platform.com'
Maybe setting this one up to your own local address may work.
If it doesn't, maybe try to host it on Heroku or alike, a real hosted server is maybe needed. Otherwise, it could also be a migration/DB/any-other-backend issue.
It's not an issue on the Nuxt.js side itself at least.

firebase function url rewrite breaking cookies

I have two cloud functions, youtubeRedirect and youtubeToken. Before doing the URL rewrite, (as found here https://firebase.google.com/docs/hosting/functions), everything was working.
youtubeRedirect takes the user to a google auth screen, and provides a redirect to the youtubeToken function. It sets these two cookies
res.cookie('state', state.toString(), { maxAge: 3600000, secure: true, httpOnly: true });
res.cookie('UID', req.query.uid);
When the user is redirect to youtubeToken, the cookie value is checked;
if (!req.cookies.state) {throw new Error('State cookie not set or expired.');}
When using URL rewrites for my custom domain, it fails at this point as req.cookies is empty. When I check my cookies in Chrome, I can see the cookies have been set for my custom domain. I have rewritten both youtubeRedirect and youtubeToken in my firebase.json file
"hosting": {
"public": "api",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "/youtubeRedirect",
"function": "youtubeRedirect"
},
{
"source": "/youtubeToken",
"function": "youtubeToken"
}
]
}
The auth side of things is working fine - authorised redirect URI's etc. all changed beforehand, where it used to redirect to us-central1-[appName].cloudfunctions.net it now redirects to my custom domain. The redirection to youtubeToken is working - my brower URL is showing my custom domain.
If I revert everything back to using the us-central1-[appName].cloudfunctions.net function address, it all works. Checking the cookies in devtools shows that the cookies are set as I expect. If I run it all with my custom domain, the cookies are also there... except the function itself cannot find them.
It seems to be that the cookies are being checked somehow before the URL rewrite has occurred, and failing? Really struggling to see a solution to this!
I thought I had found a smoking gun when having console.log(req.get('host')) in youtubeToken returned us-central1-[appName].cloudfunctions.net however placing it within youtubeRedirect has the same outcome, so that just confused me further...
Found the answer in another question
When using Firebase Hosting together with Cloud Functions or Cloud Run, cookies are generally stripped from incoming requests. This is necessary to allow for efficient CDN cache behavior. Only the specially-named __session cookie is permitted to pass through to the execution of your app.
Source
My solution is to set the cookie like so in youtubeRedirect
const sessionCookie = {
state: state.toString(),
UID: req.query.uid
}
res.cookie('__session', JSON.stringify(sessionCookie), { maxAge: 3600000, secure: true, httpOnly: true });
And then retrieve it in youtubeToken
const sessionCookie = JSON.parse(req.cookies.__session)
if (!sessionCookie.state) {

How to create a firebase dynamic link with the REST API

I'm trying to generate a dynamic link in firebase using the REST API. I've tried following instruction on the following page of the documentation: https://firebase.google.com/docs/dynamic-links/rest#create_a_short_link_from_parameters
My apologies in advance for bad formatting, but my request looks something like this:
POST https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=
with headers:
Content-Type: application/json
and body:
{
"dynamicLinkInfo":{
"domainUriPrefix":"https://<myDomain>.page.link/",
"link":"https://www.google.com/",
"androidInfo":{
"androidPackageName":"com.<companyName>.<appname>"
}
}
}
The response i get is:
{
"error": {
"code": 400,
"message": "Invalid Dynamic Link domain: '' or Domain Uri Prefix: 'https://<myDomain>.page.link/'. Expecting exactly one. Dynamic Link Domain isPresent = false, Domain URI prefix isPresent = false, [https://firebase.google.com/docs/dynamic-links/rest#create_a_short_link_from_parameters]",
"status": "INVALID_ARGUMENT"
}
}
My firebase project has a the .page.link domain registered within the project. In the dynamic links section of the firebase project it does show up. I've tested creating links in the firebase console and i've even been able to manually make dynamic short-links using the react-native-firebase package so i'm pretty sure nothing is wrong with my project.
You cannot have / at the end of domainuriprefix. Can you try removing it?
I want to add another solution.
In my case a simple white space in front of 'https' was the trigger.
"message": "Invalid Dynamic Link domain: '' or Domain Uri Prefix: ' https://[...]'
You do need to add the https:// portion to your domainUriPrefix ->
{
"dynamicLinkInfo":{
"domainUriPrefix":"<myDomain>.page.link",
"link":"https://www.google.com/",
"androidInfo":{
"androidPackageName":"com.<companyName>.<appname>"
}
}
}

firebase hosting blocking script due to CORS issue

I am using firebase hosting to host few scripts and trying to access them from another site. it naturally gets blocked due to CORS issues. based on my research on other forum threads etc i modified the firebase.json as below
{
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"headers": [ {
"source" : "**",
"headers" : [ {
"key" : "Access-Control-Allow-Origin",
"value" : "*"
} ]
}]
}
}
which essentially allow any url to access the resources hosted here. however, on trying to run my site i still see below
Access to XMLHttpRequest at 'https://oracle-bot-sdk.firebaseapp.com//loader.json'
from origin 'https://insurance-bot.moblize.it' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
what else is needed?
In addition to your firebase.json changes for cors, your firebase functions http / https function needs to also include the cors plugin.
Example
const cors = require('cors')({origin: true});
const functions = require('firebase-functions');
const app = functions.https.onRequest((req, res) => {
cors(req, res, () => {
// Your app stuff here
// Send Response
res.status(200).send(<response data>);
});
});
Express App Example
import express from "express";
const cors = require('cors')({origin: true});
const app = express();
app.get('**', (req, res) => {
cors(req, res, () => {
// Your App Here
// Send response
res.status(200).send(<response data>);
});
});
More documentation Serve Dynamic Content with Cloud Functions - Create an HTTP function to your Hosting site (Cors is not mentioned in the documentation btw)
Is the site (https://insurance-bot.moblize.it/) that is calling to https://oracle-bot-sdk.firebaseapp.com a Firebase hosted app?
I only ask because with version 4.2+ of Firebase Tools allows you to setup Multisite hosting using the same Firebase Project. I am not sure if that would help your situation out at all. Just wanted to mention it.
In the error message:
insurance-bot.moblize.it/:1 Failed to load https://oracle-bot-sdk.firebaseapp.com//loader.json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://insurance-bot.moblize.it' is therefore not allowed access.
I noticed an extra '/' in https://oracle-bot-sdk.firebaseapp.com//loader.json. I doubt that is the issue, but wanted to mention it.
There is something that you could try. Similar to the answers above but a little different:
"headers": [
{
"source": "*",
"headers": [
{
"key": "Access-Control-Allow-Origin",
"value": "*"
}
]
}
]
Also I would read some of the info here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Access-Control-Allow-Origin If you have not already.
I hope I was able to help in some way. Let me know.
My guess that you've mixed up firebase hosting and firebase cloud functions. Firebase hosting is made for hosting static websites and web apps. As you try to access from your website that is hosted on different domain your configuration for hosting is not applied. You mentioned that you host some scripts and it sounds like cloud functions. And good old CORS headers can help to your cloud functions like:
exports.corsEnabledFunction = (req, res) => {
res.set("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Methods", "GET");
res.set("Access-Control-Allow-Headers", "Content-Type");
res.set("Access-Control-Max-Age", "3600");
// Continue with function code
...
}
More info: https://cloud.google.com/functions/docs/writing/http#handling_cors_requests
Make sure you have the Blaze or Flame plan, I think Spark plan blocks external access, maybe for the same reason as it does with cloud functions
Cloud Functions for Firebase - Billing account not configured
Go to the Google Cloud Console: https://console.cloud.google.com/functions/
Click the checkbox next to the function on which you want to grant access.
Click Show Info Panel in the top right corner to show the Permissions tab.
Click Add member.
In the New members field, type allUsers.
Select the role Cloud Functions > Cloud Functions Invoker from the Select a role drop-down menu.
Click Save.
taken from: https://github.com/firebase/firebase-functions/issues/645#issuecomment-605835353
This was the best solution for me as posted above
Go to the Google Cloud Console: https://console.cloud.google.com/functions/
Click the checkbox next to the function on which you want to grant access.
Click Show Info Panel in the top right corner to show the Permissions tab.
Click Add member.
In the New members field, type allUsers.
Select the role Cloud Functions > Cloud Functions Invoker from the Select a role drop-down menu.
Click Save.
taken from: https://github.com/firebase/firebase-functions/issues/645#issuecomment-605835353
Try pasting this as it's directly from the documentation, Customize Hosting Behavior:
"hosting": {
// Add the "headers" section within "hosting".
"headers": [ {
"source" : "**/*.#(eot|otf|ttf|ttc|woff|font.css)",
"headers" : [ {
"key" : "Access-Control-Allow-Origin",
"value" : "*"
} ]
}
}
Firebase hosting CORS doesn't work WITH custom domain.
However, CORS API works with https://yyyyyyy.web.app/ or firebaseapp.com domain

Resources